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.

[adrotate banner=”5″]

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:

[code lang=”java”] 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.");
}
[/code]

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 :

[code language=”java” collapse=”1″]

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");
}
}

[/code]

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

[code language=”java” collapse=”1″]

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){}

}
}

[/code]

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

A seasoned blogger and a content marketer for close to a decade now. I write about Food, Technology, Lifestyle, Travel, and Finance related posts. Blogging brings me joy and the best part is I get to read and e-meet so many amazing bloggers! PS: I'm also the founder for Socialmaharaj.com :) Favorite Quote: "Traveling is like reading a book, one who hasn't traveled, hasn't turned a page.

Check Also

Arduino UNO

Arduino Project Ideas to implement this summer vacations

It’s that time of the year (again) when parents would be scouting for dance, music, …

47 comments

  1. 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

  2. give me information about RxTx serial port

  3. 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.

  4. 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

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

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

      • 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.

Share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.