Arduino Serial Read Using Java

How to communicate with an Arduino board using Java application.

Intro

In this example I will show how to read data sending by an Arduino board using Java application. The Arduino board elaborates a random number and print the data via the serial port. The Java application is designed to find the COM port where the Arduino is connected, establish the connection between Arduino and your PC, read the data coming from the serial port and finally plot the data via a real-time chart using JFreeChart  . The Java application is developed in NetBeans IDE 8.X  It uses the RXTX library for serial communication and the java library Ardulink  as communications protocol. Warm thanks to Luciano Zu for developing the Ardulink project. The entire project is available on github at this link Download ZIP Arduino Serial Read Using Java project.

Hardware

Arduino UNO microcontroller board http://arduino.cc/en/Main/arduinoBoardUno

Arduino Sketch

The Arduino sketch for this project is available at this link on Github. The program set the serial port baud rate and generate a random number between 0 and 100. I have choose as data a random number only as an example. You can send any kind of data, such as those coming from an analog sensor (potentiometer, temperature sensor, pressure sensor) connected to your Arduino board. The most important piece of the sketch is the communications protocol, which I have implemented in the function printData

void printData ( int data ){
 Serial.print("SERIAL");
 Serial.print(data);
 Serial.write(255); 
}

The function printData first print the string SERIAL in order to communicate at the PC that a data is coming, in this way you can ignore any spurious message at the serial port. Then the function print the data and finally write the byte 255 which means the end of data transfer.

System Configuration

Just a while for setting up your system and correctly launch the Java application.

Java Environment

Download Java SE development kit JDK and NetBeans IDE Windows x86 version (32 bit). The JDK includes the Java Runtime Environment JRE

RXTX Library

The Java application communicate via serial port using the RXTX java library. Download the RXTX java library at this link More information about the RXTX library is available at the RXTX wiki

Windows Configure the RXTX Library

Navigate to the JDK directory in your PC and find the jre directory: C:\Program Files (x86)\Java\jdk1.8.0_20\jre Open the RXTX library folder and copy the files in the jre directory RXTXcomm.jar → …\lib\ext rxtxSerial.dll → …\bin

NetBean IDE 8.X

Download ZIP of the project from the Github repository. Import the zip folder in NetBeans IDE and the environment is ready to load all the libraries to launch the java application.

Java Application

Java application GUI for communication with an Arduino board

Java application GUI for communication with an Arduino board

The Java application has three main features

  1. Find the COM serial port connected to the Arduino board
  2. Establish a connection between the Arduino and your PC
  3. Read the data available at the connection port and plot the data in a real-time chart

The connection between Arduino and your PC is made possible by Ardulink open source java library. The Java application GUI uses two Ardulink java swing components:

  1. SerialConnectionPanel() this swing component is able to search for and select the COM serial port connected to Arduino
  2. ConnectionStatus() this swing components shows the connection status between Arduino and your PC

The Java application GUI has also two JButton for connect – disconnect the Arduino board and a JFreeChart to plot the real-time data. The Java SerialRead class implements the Ardulink interface RawDataListener The connection and communication between the Arduino board and PC is implemented in the instruction


// init the connection between Arduino and PC
boolean connected = link.connect(comPort, baudRate);

The Link class is the main Ardulink class for the communication between PC and Arduino at the specific serial port comPort with the specific baud rate baudRate. I have add an action listener to the connect – disconnect buttons to process the corresponding action event. Finally, the Java application read and build the string at the serial port, check if the message starts with the string “SERIAL” then print the data to the console and add a new data point to the real-time chart.

Resources

These are the main resources I used to design the Java application

Ardulink

The open source Java project for the control of Arduino boards http://www.ardulink.org/ Ardulink Javadoc http://www.ardulink.org/javadoc/index.html

Arduino and Java Interfacing

Refer to the Arduino Playground http://playground.arduino.cc/Interfacing/Java for more information about Java and Arduino interfacing.

JFreeChart

The real-time data chart is developed based on this example JFreeChart: Dynamic Data Demo 3 on java2s.com http://www.java2s.com/Code/Java/Chart/JFreeChartDynamicDataDemo3.htm This example is designed to plot multiple chart while I need only one plot.

Acknowledgments

Special thanks to Luciano Zu ( he’s the best! ) for developing the open source Ardulink java library and for helping me with important suggestions.

Advertisements

25 comments

  1. Muhmmad Alfi · · Reply

    HI Macro, I’m Alfi..
    I want to create a digital seismic detector using arduino , which data can be through piezoelectric sensors through ADC , when data is entered into the form of a graph java interfaces such as interfaces you above . then I have to calculate the incoming garfik to get ricther scale value to my show into the textfield java , thanks macro

  2. Hi Alfi,

    look at Arduino skecth on Github https://github.com/marcomauro/Arduino-SerialRead-Java/blob/master/ArduinoJava_sketch/ArduinoJava_sketch.ino

    delete the instruction

    // generate different seed number if pin 0 is unconnected
    randomSeed(analogRead(0));

    change the instructions
    randNumber = random(maxNumber);
    // serial write data for Java
    printData(randNumber);

    using these:

    int data;
    data = analogRead(A0);
    printData(data);

    So the the analog signal connected to the analog pin A0 will be displayed in the chart

    Let me know if it helps
    cheers

    1. Muhammad Alfi · · Reply

      like this ?

      void setup(){
      Serial.begin(9600);
      analogReference(DEFAULT);
      }

      void loop(){
      int alfi;
      alfi = analogRead(A3);
      Serial.print(alfi);
      Serial.print(“\n”);
      delay(100);
      }

      1. yes good work !

        If you would use the java application interface as it is, you have to modify the sketch a little bit, like this:

        void setup(){
        Serial.begin(115200); // default baud rate 115200
        analogReference(DEFAULT);
        }

        void loop(){
        int alfi;
        alfi = analogRead(A3);
        Serial.print(“SERIAL”); // start the data message
        Serial.print(alfi); // print data
        Serial.write(255); // end data message
        delay(100); // wait a little more if you want
        }

  3. Muhammad · · Reply

    ok macro, i’ll rry 🙂

  4. muhammad alfi · · Reply

    Can send data graphs of java obtained from arduino , when raised into java chart data , then the value of the data that is sent to a mobile phone via sms gateway . can it?

    1. Hi Alfi, I think it is possible but I have never tried ! I am sorry I am not able to help

  5. loved it !! very nice!! keep going
    sarah saif alneaimi

  6. Thanks for your tutorial. I’m a beginner and i thougt i was following the whole tutorial correctly. When i ecxecute the code the following message show up… Do you have any solution?

    Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
    at org.zu.ardulink.gui.SerialConnectionPanel.getConnectionPort(SerialConnectionPanel.java:129)
    at arduinoserialread.SerialRead$1.actionPerformed(SerialRead.java:131)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

    1. Sorry for the comment.. I’ve fix it by myself!

      1. Sounds great ! don’t worry

      2. Derek · ·

        Please, how did you fix this?? I am having the same issue but cannot seem to fix it.

  7. Hi, thanks for your tutorial. I’ve tried to make this step by step, but the following error shows up :

    Exception in thread “AWT-EventQueue-0” java.lang.NoClassDefFoundError: gnu/io/NoSuchPortException
    at org.zu.ardulink.Link.(Link.java:165)
    at org.zu.ardulink.Link.createInstance(Link.java:119)
    at org.zu.ardulink.Link.(Link.java:70)
    at arduinoserialread.SerialRead.(SerialRead.java:56)
    at arduinoserialread.main$1.run(main.java:35)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException: gnu.io.NoSuchPortException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    … 19 more

    Do you have any idea about what am I doing wrong?
    Thank you.

    1. Hi Ana,
      Do you see the COM port connected to your computer ?
      I guess the issue is caused by one of these:
      1) Windows Configure the RXTX Library
      2) Ardulink. jar library correctly add to the project

      hope this helps let me know
      marco

  8. Hi,
    I’ve tried this on another computer with Win x64(like mine) and it didn’t work either. Then, I’ve tried it on Win x32 and it worked. I don’t know if this is the issue, but that’s my guessing..

    1. I think you are right. I have tested the application using java environment JRE 8 for 32-bit OS. Indeed it works. I will try to fix it or find a work around on 64-bit OS asap! cheers

      1. Thank you!

  9. Derek · · Reply

    Hello. I am trying to implement this code but I cannot get it running. After several attempts to fix the situation I am always met with the following problem when trying to run the application:

    Exception in thread “AWT-EventQueue-0” java.lang.NoClassDefFoundError: gnu/io/NoSuchPortException
    at org.zu.ardulink.Link.(Link.java:165)
    at org.zu.ardulink.Link.createInstance(Link.java:119)
    at org.zu.ardulink.Link.(Link.java:70)
    at arduinoserialread.SerialRead.(SerialRead.java:56)
    at arduinoserialread.main$1.run(main.java:35)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException: gnu.io.NoSuchPortException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    … 19 more

    Does anybody know how I can fix this issue? Thanks.

    1. Hi Derek,
      Same issue highlighted by Ana in the previous post. Try Java for Win-32 bit, I have tested the application using java environment JRE 8 for 32-bit OS. Indeed it works. I will try to fix it or find a work around on 64-bit OS

      1. So, I fixed that issue. It was with the rxtx library. I did not have it installed in the appropriate location. Now, I’m coming across another error. The error is now:

        Exception in thread “Thread-4” java.lang.ArrayIndexOutOfBoundsException: 1024
        at org.zu.ardulink.connection.serial.SerialConnection$SerialReader.run(SerialConnection.java:290)
        at java.lang.Thread.run(Thread.java:745)

        Is there any way to solve this? I have gone through the code and everything seems to be fine. When I run the program, it shows the interface for the graph, it lets me set a baud rate, select the COM port and click ‘Connect.’ But, I am receiving no information from the arduino and after a few seconds I’m greeted with the above exception. Any ideas? Thanks.

  10. Grace Christina · · Reply

    Hi, is it possible to receive data type float in the parseInput method of RawDataListener? Thank you

    1. Hi !
      It is interesting and I would like to do the same, but as far as I know RawDataListener accept only integer input.
      You can ask to Luciano Zu the creator of Ardulink for more info
      http://www.ardulink.org/contact-us/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: