Home / Technology / Arduino / Arduino – Serial Communication using Java and RXTX
Arduino UNO
Arduino UNO

Arduino – Serial Communication using Java and RXTX

From the I had purchased the Arduino Uno, I was busy tinkering with it day in and day out. Started by simple LED ON/OFF tutorials, then moved to playing around with sensors – temperature, motion, photo resistors etc. But even then, the only thing I wanted to achieve was to be able to send and receive data from the Arduino and PC and vice versa. This took me over 4 days to understand(Mind you – haven’t understood it completely yet !!) This guide will help you to communicate with your Arduino Board using Java and RXTX library.

Initially was working on my Ubuntu machine along with the UNO. (Always prefer programming on a Linux based PC as it’s easy and things are straight forward – I think so ! :P) Things were fine until I tried serial communication. My God, the first time I did something and I remember that the TX LED was on and nothing was happening, thought it was all over, but finally managed to get over it. After fidgeting with things like “su ln /dev/ttyACM0 dev/ttyUSB0, uccp -aG dialout user, RFFile locks..” I thought to move to my Windows machine.

Few clicks here and there plus fresh installation of JDK x86 (due to a problem with RXTXserial files for x64 + Netbeans), it was all ready in less that 3 hours !! Truly amazing !! Windows doing stuff that my Ubuntu couldn’t managed to rather was too complex.

Let’s come to the real thing. A big thanks to the Arduino forum that helped me get this one.

To begin with, here’s the sketch for Arduino UNO:

int val = 0;
int led = 8;

void setup()
{
	Serial.begin(9600);
	pinMode(led, OUTPUT);
}
void loop()
{
	delay(100);
}
void serialEvent() // To check if there is any data on the Serial line
{
	while (Serial.available())
	{
		val = Serial.parseInt();
		if(val == 1)   //Switch on the LED, if the received value is 1.
		{
			digitalWrite(led, HIGH);
		}
		else if(val == 0) //Switch off the LED, if the received value is 1.
		{
			digitalWrite(led, LOW);
		}
	}
Serial.println("Succesfully received.");
}

Once the sketch was ready, simply upload it on the UNO.

Now to the main thing – Java code alongwith RXTX Libraries.

To enable serial communication over COM ports, this library is a must. Simply download and extract it. Follow the method explained on their website. If you are using a x64 bit computer, then you might have to download the x86 JDK. I worked on Netbeans on x64 pc and had to get the 32 one. Once that was ready, right click on your projects->properties->libraries->Add folder/jar files. Copy all the files in your Arduino / lib folder and put them here. Now head to run tab. See the platform tab, add a new platform(x86 / 32 bit JDK that you recently installed) and select it.

Used the original code given on Arduino website to setup the Serial Communication. Modified it to this one :


package Arduino;
/**
*
* @author Atulmaharaj
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialClass implements SerialPortEventListener {

public SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM11", // Windows
};

public static BufferedReader input;
public static OutputStream output;
/** Milliseconds to block while waiting for port open */
public static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
public static final int DATA_RATE = 9600;

public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}

try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);

// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
char ch = 1;
output.write(ch);

// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}

public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}

public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}

}

public static synchronized void writeData(String data) {
System.out.println("Sent: " + data);
try {
output.write(data.getBytes());
} catch (Exception e) {
System.out.println("could not write to port");
}
}

public static void main(String[] args) throws Exception {
SerialClass main = new SerialClass();
main.initialize();
Thread t=new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {Thread.sleep(1500);
writeData("2");} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}

Used this code and created another class that inherited this one and made the program:


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
import Arduino.SerialClass;
import Arduino.SerialClass;
import java.io.IOException;

public class TestClass
{
public static BufferedReader input;
public static OutputStream output;

public static synchronized void writeData(String data) {
System.out.println("Sent: " + data);
try {
output.write(data.getBytes());
} catch (Exception e) {
System.out.println("could not write to port");
}
}

public static void main(String[] ag)
{

try
{
SerialClass obj = new SerialClass();
int c=0;
obj.initialize();
input = SerialClass.input;
output = SerialClass.output;
InputStreamReader Ir = new InputStreamReader(System.in);
BufferedReader Br = new BufferedReader(Ir);
while (c!=3)
{
System.out.println("LED ON / OFF MENU.");
System.out.println("1.LED ON");
System.out.println("2.LED OFF");
System.out.print("Enter your choice :");
c = Integer.parseInt(Br.readLine());

switch(c)
{
case 1:
writeData("1");
break;

case 2:
writeData("0");
break;

case 3:
System.exit(0);
}
}

String inputLine=input.readLine();
System.out.println(inputLine);

obj.close();

}
catch(Exception e){}

}
}

So after some tiring sessions, the output is amazing ! (Might be simple for many, but making this happen wasn’t an easy task – atleast for me !) This has certainly opened doors for further creativity. I guess, the decision to get the Arduino was a perfect one !!

About Atulmaharaj

Maintaining the blog for the past 3 years, I'm a Foodie, Techie, Cricket Enthu, Traveler, Blogger and a Cook ! You'll find posts within a wide range of topics from food to technology. Favorite Quote: "Traveling is like reading a book, one who hasn't traveled, hasn't turned a page.
  • outsorts

    i know i missed something but can you tell me why am i facing this problem:
    when i run the the java application first it runs properly but i get an error “serial port already in use” when i try to open the arduino serial monitor.
    and vise versa if i open the arduino serial monitor first i get this error “gnu.io.PortInUseException: Unknown Application” in the java console.
    i’m newbie in using the Rxtx library so can you tell me what am i missing.
    i’m using the java code in the arduino website: http://playground.arduino.cc/Interfacing/Java

    • I faced that problem sometimes in Ubuntu. Hence I thought of trying to code in windows. And I must say, I didn’t face this problem. Though, I get port in use exception sometime when I send some data to arduino, but get the correct output. Because its working how I want it to, I didn’t further explore the reason why the exception occurred at the first place.

      But the code here works perfectly alright…

      • Stable Library
        =========================================
        Native lib Version = RXTX-2.2pre2
        Java lib Version = RXTX-2.1-7
        WARNING: RXTX Version mismatch
        Jar version = RXTX-2.1-7
        native lib Version = RXTX-2.2pre2
        Could not find COM port.
        LED ON / OFF MENU.
        1.LED ON
        2.LED OFF
        Enter your choice :1
        Sent: 1
        Exception in thread “main” java.lang.NullPointerException
        at TestClass.TestClass.writeData(TestClass.java:28)
        at TestClass.TestClass.main(TestClass.java:57)
        Java Result: 1
        i am getting this output can u please help me ?

        • Hey,
          It did show exception when I did this too. But it didn’t affect the working though. I did try resolving it, haven’t got the breakthrough yet, also currently busy with exams so have been away from arduino for sometime now…

    • snop

      I have faced the same problem. To solve it you must close any terminal kind tool which you use to monitor the device or any other thing that can use your device. Then you must go to My Computer click right and choose Properties , then open Device Manager and remove the device from your computer’s port,then it will push you to restart your computer. Afterwards you can go to the Device Manager and load your device to the ports again. And finally you can run your program without getting this error.

  • Bob Coyle

    I’m interfacing the Arduino with visual basic (under windows) and I get the same behavior. I was under the impression that it was caused by both apps competing for the same com port.

  • AKEEL

    I am not having much experience in java, so please tell how to create new java class and how to name them because i am getting trouble with importing the packages i need your help soon i need to create a java program to communicate with arduino

    • For serial communication with Arduino in java, you will have to first download the RXTX library and import on your project. Once that is configured, write the program as you do in java. For more refer to source code given or feel free to contact me again..,

  • AKEEL

    i have downloaded the library!from your link in the post
    how to use that zipfile? how to configure them?

    • Extract the file. You should find a jar file in it. Now in netbeans, create a new java project, right click on it and choose properties, in the window choose libraries, and on it click add folder/jar file. Choose ur file and you are done.

  • AKEEL

    k then what should be the name for that new project(i mean the class name..)

  • AKEEL

    after import all imports with gnu are shown as errors in both programs

    • Pratibimb

      @AKEEL: you can chose any project name. But make sure to name the class files with class name. For example, file containing SerialClass should have name SerialClass.java similarly other file should be named TestClass.

      2) all imports with gnu are showing error because you need to add RXTXcomm.jar file to your project. For example in eclipse: goto Project Properties (Alt+Enter) -> java build path -> Libraries – Add external JARs -> and add the RXTXcomm.jar from the downloaded zip.

  • Pratibimb

    @AKEEL: you can chose any project name. But make sure to name the class files with class name. For example, file containing SerialClass should have name SerialClass.java similarly other file should be named TestClass.

    2) all imports with gnu are showing error because you need to add RXTXcomm.jar file to your project. For example in eclipse: goto Project Properties (Alt+Enter) -> java build path -> Libraries – Add external JARs -> and add the RXTXcomm.jar from the downloaded zip.

  • Jose Luis Gomes Araujo

    hi, i attempt to do one easy program but I have difficulties in find this libs
    import Arduino.SerialClass;
    import Arduino.SerialClass;

    • Sorry for the delay in replying. Was busy with exams.
      Firstly you need to create the “SerialClass.java” file. In this example, Arduino is the package and the file name is SerialClass. The line in the blog post where it says “Used the original code given on Arduino website to setup the Serial Communication.”, please find the code for the SerialClass below this line.
      Hope it helps. Do keep me updated on the progress !

  • Many thanks and much love from Turkey, brother!
    Just like you, I did spend too much time looking for a feasible solution until I stumbled upon this site – awesome work!

    • Thanks so much 🙂 Glad that this helped you !

  • liam

    Thank you for writing this! I spent hours trying to figure it out before I found your site.

    • Hey Liam, I’m glad this helped you… 🙂

  • thanks for you post atul i got the output but i wan to build a GUI using awt swings and applets
    any suggestions 😀

    • Hey, u’re welcome… Well I did want to make a GUI but haven’t made one yet..as and when I do it, it’ll be here…

  • package TestClass;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import java.util.Enumeration;
    import Arduino.SerialClass;
    import Arduino.SerialClass;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Label;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    public class TestClass extends Frame implements ActionListener
    {

    TextField t1;
    Button b1,b2;
    public static BufferedReader input;
    public static OutputStream output;
    //private Object Br;

    TestClass()
    {

    //l1=new Label():
    t1=new TextField(100);
    b1=new Button(“Probe”);
    b2=new Button(“clear”);
    add(t1);
    add(b1);
    add(b2);
    b1.addActionListener(this);
    b2.addActionListener(this);
    setFont(new Font(“Arial”,Font.BOLD,24));
    setBackground(Color.CYAN);
    setForeground(Color.BLUE);
    setLayout(new FlowLayout());
    setTitle(“Mr.Mft”);
    setSize(500,500);
    setVisible(true);

    }

    public static synchronized void writeData(String data) {
    System.out.println(“Sent: ” + data);
    try {
    output.write(data.getBytes());
    } catch (Exception e) {
    System.out.println(“could not write to port”);
    }
    }
    public void actionPerformed(ActionEvent ae)
    {

    String buttonName=ae.getActionCommand();
    if(buttonName.equals(“Probe”))
    {
    try
    {

    SerialClass obj=new SerialClass();
    String s;
    obj.initialize();
    input=SerialClass.input;
    output=SerialClass.output;
    InputStreamReader ir=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(ir);
    s=br.readLine();
    t1.setText(“”+s);
    String inputLine=input.readLine();
    System.out.println(inputLine);
    obj.close();

    }
    catch(Exception e)
    {
    System.out.println(e);

    }
    }
    if(buttonName.equals(“Clear”))
    {

    //tf1.setText(“”);
    //tf2.setText(“”);
    t1.setText(“”);
    }

    }

    }
    //throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.
    output:Native lib Version = RXTX-2.2pre2
    Java lib Version = RXTX-2.1-7
    WARNING: RXTX Version mismatch
    Jar version = RXTX-2.1-7
    native lib Version = RXTX-2.2pre2
    Started
    Succesfully received.
    java.io.IOException: Underlying input stream returned zero bytes
    Sent: 2
    Succesfully received

    When i press the probe button here it should read the serial port data and display it on the GUI Textbox but the GUI itself is not coming atul any suggestions or modification?

    • Brother, didn’t try the code as don’t have my arduino now…

  • fine yaar 😀
    change ur wesite font? looking gud

  • snop

    Hi I am trying to do a similar serial communicati,on with gps device from usb. I used driver to make it as serial COM port to use java API to get data from gps and used RXTXComm.jar and its libraries in my program. I changed my device’s property to 4800baud rate as mentioned in nmea standarts. But I am getting this error.

    Trying port: COM10
    java.io.IOException: Underlying input stream returned zero bytes
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:287)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:154)
    at java.io.BufferedReader.readLine(BufferedReader.java:317)
    at java.io.BufferedReader.readLine(BufferedReader.java:382)
    at GPSReader.serialEvent(GPSReader.java:208)
    at gnu.io.RXTXPort.sendEvent(RXTXPort.java:772)
    at gnu.io.RXTXPort.eventLoop(Native Method)
    at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1641)

    Have you got any ideas to fix this? I would appreciate. Thanks already! 🙂

    • Hey,
      thanks a lot for your helpful replies. Actually, I don’t have the device as of now and nor do I have the GPS module, so I’m afraid I won’t be able to help you out…sorry… Happy New Year btw 🙂

  • silvio

    Muito abrigado pela ajuda! Estou no brasil e achei o blog muito bom!

    • Eu não sei o idioma, mas muito obrigado! (Usado o Google Translate para isso)

  • Learn

    From where did you get the “java.util.Enumeration” please ?

    • Learn

      I added the Enumeration jar to my java project, but still getting error for “import java.util.Enumeration;”.

      • Learn

        I was able to add the java.util jar, and it got rid of that error. However, now, when I tried to ran your code, I got the following errors. Let me know please what I am doing wrong.

        java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
        Exception in thread “main” java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
        at java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.lang.Runtime.loadLibrary0(Unknown Source)
        at java.lang.System.loadLibrary(Unknown Source)
        at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
        at Arduino.SerialClass.initialize(SerialClass.java:35)
        at Arduino.SerialClass.main(SerialClass.java:109)

        Thanks in advance.

  • Learn

    I tried to install the RXTX libraries, but all related links are no longer available.
    I was able to get the “RXTXcomm.jar”, and added it to my Java project successfully. However, I was not able to download the following .dll files:
    rxtxSerial.dll
    rxtxParallel.dll

  • very interesting article. I have to read it with more attention. I have developed a java library, called Ardulink, that can do the same thing and I have to check if I can improve my code with yours.

  • kailash t

    give me information about RxTx serial port

    • I guess the RXTX link is down and I’ll have to find the files that I had used… Will post them once I get access to my system…

  • xwalter

    you have install the correct RXTX version .If the native library is 2.2 you have to link your java application to rxtx2.2 otherwise you get a mismatch error

  • victor

    RXTX is no longer prefered. The scm is an alternative library to rxtx/javaxcomm for serial port communication.
    Wiki : http://www.embeddedunveiled.com/
    Repository : https://github.com/RishiGupta12/serial-communication-manager
    Video : https://www.youtube.com/watch?v=fYLQbelGunQ

    • Thanks a lot Victor for the update. Someone also commented on a video I posted on YouTube. This was something I did during my summer holidays long back, and this was the only option then. It worked for me so thought to make it easier for others too 🙂 as for the new library, I haven’t used it yet. But again thanks 🙂 have a good time 🙂

  • OSama

    Thank you! Great Work

  • satish kadam

    Thank you…!!!

    • Atulmaharaj

      It’s been quite some time (few years) since I worked on this. I’m glad this helped you 🙂

Get Amazing Stories

Get a weekly digest of all the posts from the blog delivered right to your inbox, just a click away, Sign Up Now - We promise, we'll never spam.
Name
Email address
Secure and Spam free...
%d bloggers like this: