Serial Communication in Java with Example Program

This is more of a follow-up to my previous post about serial programming in Java (here) and how to install the RXTX libraries (here).  This post also assumes that Java is already properly set up with RXTX.

Generally, communication with serial ports involves these steps (in no particular order):

  • Searching for serial ports
  • Connecting to the serial port
  • Starting the input output streams
  • Adding an event listener to listen for incoming data
  • Disconnecting from the serial port
  • Sending Data
  • Receiving Data

I wrote an example program that includes all of those steps in it and are each in their own separate method within the class, but first I will go through my hardware set up.

Hardware Setup

My current hardware setup is as follows:

  • PC connected to an XBee
  • Arduino connected to an XBee

User input is given from the PC through the a Java GUI that contains code for serial communication, which is the code presented here.

The Arduino is responsible for reading this data.  This set up is pretty much using my computer as a remote control for whatever device is on the Arduino end.  It could be a motor control, on-off switch, etc.

Existing Code

The purpose of this post is to discuss serial programming in Java, and not GUI’s.  However, I did create a GUI for testing purposes.  See the Code Downloads section for the actual files.

Above is the picture of the GUI complete with the buttons that I use to interact with the program.  I also added key bindings which I can use to control the throttle.

When the program is first started, none of the GUI elements will work except for the combo box and the connect button.  Once a successful connection is made the controls are enabled.  This is done through the use of the setConnected(true) and the toggleControls() methods shown in the example code that follows.


The imports i used for this program were as follows:

import java.awt.Color;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;

Depending on the Java IDE it might already know to tell you to use these imports except for the first one.  That first import is specific to RXTX, and all its library methods/classes are in there.

Class Declaration

The code here reads:

public class Communicator implements SerialPortEventListener

I named my class Communicator, but the name is really up to the programmer.  The name pretty much reflects its intended use.

The class should also implement the SerialPortEventListener class.  This is a class in RXTX and is required in order to receive incoming data.

On some IDE’s this may generate a public void method called serialEvent().  This method will be defined later.

Class Variables and Constants

Below are the variables and constants that I defined in my class.  What the variables are for is in the comments but a more detailed explanation will follow.

    //passed from main GUI
    GUI window = null;

    //for containing the ports that will be found
    private Enumeration ports = null;
    //map the port names to CommPortIdentifiers
    private HashMap portMap = new HashMap();

    //this is the object that contains the opened port
    private CommPortIdentifier selectedPortIdentifier = null;
    private SerialPort serialPort = null;

    //input and output streams for sending and receiving data
    private InputStream input = null;
    private OutputStream output = null;

    //just a boolean flag that i use for enabling
    //and disabling buttons depending on whether the program
    //is connected to a serial port or not
    private boolean bConnected = false;

    //the timeout value for connecting with the port
    final static int TIMEOUT = 2000;

    //some ascii values for for certain things
    final static int SPACE_ASCII = 32;
    final static int DASH_ASCII = 45;
    final static int NEW_LINE_ASCII = 10;

    //a string for recording what goes on in the program
    //this string is written to the GUI
    String logText = "";

I could have easily put the variable definitions in the constructor but it wouldn’t change anything.

The GUI object is another class that I wrote separate from this one that contains all the GUI elements.  The GUI class extends javax.swing.JFrame.

The HashMap is for mapping each of the ports’ names to the actual object. What that means is that I can associate (put() method) the name of a serial port, say a string that says COM1, to an object in the code.  Later, I can access the name COM1 from the HashMap by using the get() method and it will return the object that it was associated with previously.

The CommPortIdentifiers object is needed to gather the list of ports that are available for connection. by using its getPortIdentifiers() method.

The SerialPort object is for storing the data for the port once a successful connection is made.

The InputStream and OutputStream is the object that is required for sending and receiving data.

The Boolean variable bConnected is just a flag that I use for enabling and disabling elements on the GUI.

The constant TIMEOUT is a number required when opening the port so that it knows how long to try for before stopping.

The constants for the ASCII values are some values that I use to send through the output stream that act as delimiters for data.

The string logText is basically what the comment says.  When stuff happens in the program, the program stores a string in this variable and it will be appended to a text area in the GUI.

Searching for Available Serial Ports

The method below is for searching for available serial ports on the computer.  Code adapted from Discovering Available Comm Ports from the Reference Material.

    //search for all the serial ports
    //pre style="font-size: 11px;": none
    //post: adds all the found ports to a combo box on the GUI
    public void searchForPorts()
        ports = CommPortIdentifier.getPortIdentifiers();

        while (ports.hasMoreElements())
            CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

            //get only serial ports
            if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
                portMap.put(curPort.getName(), curPort);

The method getPortIdentifiers() returns an Enumeration of all the comm ports on the computer.  The code can iterate through each element inside the Enumeration and determine whether or not it is a serial port.  The method getPortType() can identify what kind of port it is.  If it is a serial port, then the code will add its name to a combo box in the GUI (so that users can pick what port to connect to).  The serial port that is found should also be mapped to the HashMap so we can identify the object later.  This is helpful because the names listed in the combo box are the actual names of the object (COM1, COM2, etc), and so we can use these names to identify the actual object they are tied to.

Connecting to the Serial Port

The method below is for connecting to the serial port once they have been found (see previous section).  See How to Open A Serial Port in the Reference Material for more information.

    //connect to the selected port in the combo box
    //pre style="font-size: 11px;": ports are already found by using the searchForPorts
    //post: the connected comm port is stored in commPort, otherwise,
    //an exception is generated
    public void connect()
        String selectedPort = (String)window.cboxPorts.getSelectedItem();
        selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);

        CommPort commPort = null;

            //the method below returns an object of type CommPort
            commPort ="TigerControlPanel", TIMEOUT);
            //the CommPort object can be casted to a SerialPort object
            serialPort = (SerialPort)commPort;

            //for controlling GUI elements

            logText = selectedPort + " opened successfully.";
            window.txtLog.append(logText + "n");


            //enables the controls on the GUI if a successful connection is made
        catch (PortInUseException e)
            logText = selectedPort + " is in use. (" + e.toString() + ")";

            window.txtLog.append(logText + "n");
        catch (Exception e)
            logText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
            window.txtLog.append(logText + "n");

Using the HashMap we can retrieve the CommPortIdentifier object from the string that was mapped earlier.  This is achieved through the HashMap’s get() method.  The object must also be casted as a CommPortIdentifier because the get() method has a return type of Object.

The setConnected method just changes a boolean flag so that the program can store whether or not it is connected to a serial port or not.

The CommPort must also be initialized because the port object will be stored here once a successful connection is made.

The main method of interest here is the open() method.  This instructs the program to open the port, and this method will return the object for the opened port, which I store in in the previously initialized CommPort object.  I then cast this object as a SerialPort and store it as well.  This is helpful for accessing the methods and variables specific to the SerialPort class.

It should also be noted that the open() method requires the use of a try-catch block.  So applying that, I catch two different exceptions.  The PortInUseException is what the name says.  If the port is in use, then this exception is thrown.  The next catch block is just for the generic exceptions that occur.  I never came across that during testing, nor do I know how to replicate that.

I neglected to include any code for setting the baud rate and other settings on the XBee’s (see Hardware Configuration), because I already set those parameters previously using X-CTU (more on setting up XBee’s here).

Initializing the Input and Output Streams

This method is pretty short and is pretty straightforward to read.

    //open the input and output streams
    //pre style="font-size: 11px;": an open port
    //post: initialized input and output streams for use to communicate data
    public boolean initIOStream()
        //return value for whether opening the streams is successful or not
        boolean successful = false;

        try {
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            writeData(0, 0);

            successful = true;
            return successful;
        catch (IOException e) {
            logText = "I/O Streams failed to open. (" + e.toString() + ")";
            window.txtLog.append(logText + "n");
            return successful;

The streams are initialized by returning the input and output streams of the open serial port.  In order for the serial port object to not be null, it must store the object for the open serial port.

The getInputStream() and getOutputStream() methods both require a try-catch block.  The important exception to catch here is the IOException to signify whether the streams failed to open or not.  For more information see How to Open A Serial Port in the Reference Material.

I also call a method called writeData(0, 0).  This is the method that encapsulates the code required to write serial data.  More on that later.  Right now it is just used to set variables on the microcontroller side to zero.

Setting Up Event Listeners to Read Data

Once the port is open, the serial port must know whenever there is data to be read.  This approach is event driven rather than by polling.  When the event is hit, a special block of code will run.  This is advantageous to polling because polling requires constantly asking if data is available.  The code for the event driven approach is below.  See Event Based Two Way Communication for more information.

    //starts the event listener that knows whenever data is available to be read
    //pre style="font-size: 11px;": an open serial port
    //post: an event listener for the serial port that knows when data is received
    public void initListener()
        catch (TooManyListenersException e)
            logText = "Too many listeners. (" + e.toString() + ")";
            window.txtLog.append(logText + "n");

The code here is pretty much the whole reason why this class implements SerialPortEventListener.  The parameter for adding the event listener is just the object itself.  The base class has a method called serialEvent(event) that should be overridden before the event code will work.  Overriding that method defines what happens when the event is hit.

The method addEventListener(this) is the event that is always checking for SerialEvents.  It isn’t really important to know what the events actually are, just that the one we’re interested in is the one that tells us whenever data is received.  Adding the event listener is complemented by the method notifyOnDataAvailable(true), which definitely helps us achieve what I mentioned previously.

This code requires a try-catch box.  The exception here is that there may be too many event listeners.  I only use one in the code, so this exception should never be hit.

Disconnecting from the Serial Port

Once all the communication is completed, the serial port must be disconnected.  In some instances, some ports stay stuck open, which isn’t exactly a good thing.

    //disconnect the serial port
    //pre style="font-size: 11px;": an open serial port
    //post: closed serial port
    public void disconnect()
        //close the serial port
            writeData(0, 0);


            logText = "Disconnected.";
            window.txtLog.append(logText + "n");
        catch (Exception e)
            logText = "Failed to close " + serialPort.getName()
                              + "(" + e.toString() + ")";
            window.txtLog.append(logText + "n");

The code here requires a try-catch block so there it is.  The exception to catch here is pretty generic.

Before closing the port, I reset the data on the microcontroller.  That step is optional depending on the application.  For example, if the value sent to the microcontroller is controlling the speed of a motor, I’d want the motor to turn off if I turn off the remote control.

The event listener should be removed as it is no longer needed.

The method to close the port is the close() method.

The input and output streams should also be closed via the same method as above.

See How to Close A Serial Port in the Reference section for more information.

Reading Data – The serialEvent Method

This is a follow-up to the section on preparing to Read Data.  It has information on how to process the data that the program reads.

    //what happens when data is received
    //pre style="font-size: 11px;": serial event is triggered
    //post: processing on the data it reads
    public void serialEvent(SerialPortEvent evt) {
        if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
                byte singleData = (byte);

                if (singleData != NEW_LINE_ASCII)
                    logText = new String(new byte[] {singleData});
            catch (Exception e)
                logText = "Failed to read data. (" + e.toString() + ")";
                window.txtLog.append(logText + "n");

Since we only want to read data if it exists, we test the condition in the if statement above.  This could be redundant because we wouldn’t be in this method if the event never got triggered.

Reading the data requires a try-catch block.  The read() method returns an integer, but the value in it is actually a byte value so this is casted to a byte, in which I store in a variable called singleData.  When I was testing this code before, I noticed that the data being read would always have random new line characters in it, and I never knew why this happened.  I never wrote any new line characters.  Since I don’t want these, I add an if condition saying that if it encounters that, don’t display that data on the screen.

Java also has a nice way of converting bytes to a string.  A byte array can be used as a parameter when initializing a string, which is what I’ve done when I assign a value to logText.  See Converting byte to String for more information.

The exception here is just the usual generic one.

Writing Data

Here is the method for writing data.  In my application, I am writing two integers sequentially to my microcontroller.  Data that is sent to the MCU can be used for such things such as controlling motor speeds, which is what I am trying to do here.  I hope to use the data sent do control the PWM duty cycle of the motor for speed control.

    //method that can be called to send data
    //pre style="font-size: 11px;": open serial port
    //post: data sent to the other device
    public void writeData(int leftThrottle, int rightThrottle)
            //this is a delimiter for the data

            //will be read as a byte so it is a space key
        catch (Exception e)
            logText = "Failed to write data. (" + e.toString() + ")";
            window.txtLog.append(logText + "n");

The write() method here requires a try-catch block just like many of the other methods used for serial communication.  Using the output stream, I call that method to write an integer value.  I also write a dash and a space to separate the actual data being read.  See the ASCII Table for the values of what these characters should be.  This helps me differentiate the sets of data that is sent back and forth.  The dash separates the two integers being sent and the space separates the entire set.  On the Arduino end, four called to read() can separate the data without mixing things up.  Example of that later.

Putting All the Java Code Together

Once all these methods are setup, they need to be called somewhere in the program so we can put them to use.  When the program starts, the code for searching for serial ports will run so that it can populate the combo box on the GUI.  The GUI buttons also need to be disabled to reflect the fact they should be disabled when there is no connection to a port.  When the connect button is pressed, the input and output streams are started and the event listener is added.  The code for that is shown below.

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
        if (communicator.getConnected() == true)
            if (communicator.initIOStream() == true)

The if statement is needed such that the code will not run if a successful connection was not made.  This is the precondition for the initIOStream() and the initLIstener() methods.

When the user decides to disconnect from the serial port, the user only needs to call the disconnect() method when the disconnect button is pressed.

The up/down arrows on my GUI are set to write data to the serial port when they are pressed.  When data is written to the Arduino, the MCU will send the data back to the Java program, which will signal the event listener to display that data back to the screen.

Arduino Code

The Arduino code is pretty straight forward.  There are just a few calls to the read() method.

Update 6 May 2012: the syntax for the Arduino code has updated since the writing of this article.  Apparently, the lines

Serial.print(separator, BYTE);
Serial.print(space, BYTE);

are no longer valid and have since been replaced by the following:


The code below hasn’t been edited with this change, but basically the code required for writing a byte value through serial communication has changed.

// this is where we will put our data
int left = 0;
int right = 0;
byte space = 0;
byte separator = 0;

void setup(){
  // Start up our serial port, we configured our XBEE devices for 38400 bps. 

void loop(){
  // handle serial data, if any
  if (Serial.available() >= 4){
    left =;
    separator =;
    right =;
    space =;

    Serial.print(separator, BYTE);
    Serial.print(space, BYTE);

I first declare four variables to reflect the fact that I’m writing four different variables to the serial port.

In the loop method, I added a condition which will check whether there are four pieces of data available before reading them.  This again reflects the fact I’m writing four values.

The four variables initially declared store the values in the order that they are written, and then are just printed to the screen.

The print() method is able to convert the byte value to an actual character by adding a second parameter called BYTE.  The left and right variables don’t need it because the values written were integers to begin with, however, the dash and space characters were written as ASCII values.

For more information about Arduino and Java, and Arduino’s Serial library, please refer to those in the Reference Section.

Code Downloads

Here are the code downloads for the GUI, key bindings and the serial communication.  WordPress doesn’t allow uploads of zip or java files so I uploaded it all to Megaupload.

Link to download:

Other Examples

There are also other sites I looked at which had example code for serial port communication in Java.  The sites are Programming Serial and Parallel Ports and Serial Port Access Using RXTX in Java, which are both in the Reference section.

Reference Material

Below are a bunch of links to reference sites that I used to find some of the information written here.  I mostly referred to bits and pieces of each article to understand the serial code and to come up with the example I present here.  The list is in the order that I referenced them.

Discovering Available Comm Ports

The code on this page is pretty specific to the title of this heading, and the code is pretty easy to follow.

How to Open A Serial Port

This page provides a very concise and detailed explanation on what each line of code does in order to get a serial port open.  Definitely work a look if you’re trying to understand the code.

Event Based Two Way Communication

This page has example code on how to connect to a serial port and how to interact with it.  The code here uses events, rather than polling, to send data back and forth, which means that whenever data is received, the event code is triggered.

How to Close A Serial Port

This article is written by the same author who wrote the article on how to open serial ports.  Good example code here.

Converting byte to String

Just some code on how to convert a byte to a String.  Useful because serial data is in bytes, and the bytes can be converted to Strings to make them easier to manage and for displaying on the screen.


Having the ASCII Table is quite handy for serial data because data being sent and written are bytes, so being able to know what byte values correspond to what character really helps.

Arduino and Java

This article discusses how to use the serial port communication with Java and Arduino, which is exactly what I am after.  It has example code on pretty much the entire process of serial port communication, but it may be too much to read since there is little explanation about the code.

Arduino Serial Class

A good reference for Arduino’s Serial class methods.  Also has example code to look at.

Programming Serial and Parallel Ports

This article provides a brief introduction to programming serial ports and has information on the steps required to talk to the serial port.  However, the code examples in there may be hard to follow for someone new to serial programming.

Serial Port Access Using RXTX in Java

This page also has complete code for serial communication in Java, but what I was looking for here was how to use the write method to send serial data from Java.


  1. I really like your article and it cleared up a few things for me, but some of the code is cut off because your web page is not wide enough.

    • Thanks for letting me know!
      I hadn’t realized that the code got cut off. It must have been because I keep changing my blog template.
      It should be fixed now. I made the text smaller.

      My apologies for not responding earlier. I wasn’t home for the past few days.

  2. Actually, it is still cut off though not as bad. I did download the code though so I guess it is not a big deal. Perhaps you should make your code blocks scrollable. It is not that hard to do in CSS.

  3. Your article is very helpful and really good, I have downloaded your code and try one my arduino Duemilanove. But I found a small bug, when I click the buttons, sometimes it works well as 0-0,0-5,0-10(when I click the right button), but sometimes it comes conversely as 0-0,5-0,10-0 when I do the same command. I don’t know why, have you met this question?

    • Hi, thanks for your comment. I don’t think I’ve noticed anything of that sort happening, but it could be entirely possible and it sounds like something that happens consistently. I did have some problems before with the numbers not updating correctly and I thought I had fixed it, but I could be wrong. It could be that something went awry during the serial communication. As far as I know (I am trying to remember since I wrote this quite a while ago), the code explicitly says to update the right most throttle when the button to accelerate the right side is pressed, so it is really strange to see the opposite happen. I would like to take a look and try it for myself, but I will be a little bit busy for the next little while, so I don’t know if I will be able to do that. If you do find a fix for it, please let me know!

      • No problem,if I find a solution,I’ll tell you. Your code is very helpful to me as I want to control my robot and distance sensor over internet by java, but I also want to control it globally, that means I may have to do it by web interface(jsp or something) or by applet. Do you have some advise?

        • Thanks for your compliment!
          If I were to do something like that, I wouldn’t know how to do it as far as coding specifics go (I’ve never done anything like that before), but I’m relatively certain that there are libraries available to handle communication through the internet, but I’m not sure as to how you’d go from a remote computer to the robot. Maybe one way is to go from a client computer —-> server (with the serial comm stuff) —> robot, and then that way you could handle the net code separately from the serial code. I’m really not sure as to how feasible this method is or whether there are better alternative methods available. I just thought of it, but never tried it.

  4. How do i compile this? javac gives me errors.

  5. hi,this code is very helpful.but i want the GUI class code.please help me??????

  6. hi,i am doing my project using Xbee Device.i need to send a packet and then receive the response it possible with this code?????

    please suggest me.

  7. hi, your article is very helpful thanks a lot !! i wanted to download your code but as you surely know megaupload is closed… could you upload your code on an other site ? thank you very much !

  8. hello, when I compile this code I am getting errors for the parts of the code that are related to the GUI window. Here is the error I get: cannot find symbol
    symbol : class GUI
    location: class communicator.Communicator
    GUI window = null;
    Is it possible for me to see the code of the GUI?

    • I uploaded a new file that has all the source and it is under the heading “Code Downloads”. Perhaps that will help you!

  9. Hi! The source code download is not longer available. Could you please over a new one?

  10. The download link for the code is no longer available. Can you please provide a new link?

  11. This is a very insightful post. Thank you very much, it will surely help me begin my serial port communication project, which I have been intending to start for quite some time now.

  12. hi, i have question about the arduino pde file, how the arduino is suppose to know which pin it is assigned to perform output since ur codes dont have it ?

    im using bluetooth connection to control 4 directions of a rc car

    • The pins involved for the serial communication are the TX and RX pins (should be labeled on the board). On the Arduino side, there must be code to read the data sent through these pins.

      • could u pls give me some example codes as i’m quite new in this arduino thing, thanks in advance

        • Sorry, but the code is provided as is and I am unable to help on individual requests. There is already a lot of existing literature on the type of project that you are doing and referring to those will help a lot more. Thanks for understanding.

  13. Hello i am using different method for disconnecting from serial port, instead of removeEventLister() i am simply close inputstream and serial port, but this seems to crash the system and hang. any suggestions?

    • Sorry, but I have no quick solution to your problem. My only suggest to you would just to be look online to see what others have done and see if it can shed some light on your problem. It might help to maybe use a different method for disconnecting a serial port. Perhaps one that is written in existing literature.

  14. it give error like package does not exit and give 16 error.
    tell me how to run this code

  15. Jose Fakiolas

    March 10, 2012 at 13:50

    Man thanks a lot for this code!! I used to communicate with my precision GPS Trimble Pathfinder Pro XH, I modified the code because I just want to listen the NMEA output of the GPS. So I erased the part of write and the part of throtle and all that. But now I have to do something very important, I don’t know how : I need that the data I see in the Textarea of the program saved it in a MySQL database, but I don’t know how, because I’m not completely sure what is the variable that has the data, I think is logText. I’m new in Java I don’t have a lot of experience so I need your help. Your code is working great but now I need to save that data in a database. This is the data I received and see in the TextArea (is a NMEA frame): $GPGGA,074106.00,1100.836692,N,07448.486753,W,1,06,1.3,54.11,M,-6.15,M,,*54

    Thanks for your attention.

    • I’m glad you found the code helpful! The text inside a TextArea object should be accessible with the getText method.

  16. Hello, I am doing a embedded system project where i need to use the data sent by an external device wirelessly to interface my PC keyboard and mouse (my project is a game keypad design ). So,basically ,any key digital key i press on the game pad will reach my computer wirelessly ( i use serial communication) . My major doubts are as follows: 1. Sent data (in bits) reaches the COM port , how do i use them as input and operate my keyboard accordingly? 2.” Robot class ” in JAVA is the best option . But how do i get serial port data as input and program in it ? I read your post and i found it very interesting . I want to continuously read the incoming COM port data and emulate my keyboard and mouse function using robot class accordingly to my wish … please help me with your suggestions . Thank you !!

  17. Not findind any device on Windows. Any ideas?

  18. very helpful! thanks a lot for sharing

  19. I am using Zigbee cc2530 Texas instruments , i connected it with a serial cable to my PC and display measured data on GUI using Java , when i run your code the combo box of the ports is disabled so i think it do not see any of the ports , i try to trace the communicator class by adding some print statements i found out that it do not enter the while loop of the
    while (ports.hasMoreElements())
    I don’t know what’s the problem , and am a beginner with this serial programming
    so pls i need help as soon as possible

    Thnx in advance

    • Hmm, I can’t be certain. Since it’s not entering the loop, that is already a big help. It does tell you that “ports” has zero elements in it. Could be something wrong with the way data is being sent? Maybe “ports” hasn’t been initialized properly?

      It might be a good idea to look at where you have defined the “ports” variable and ensure that there actually is an object there.

      Not sure how much more I can help.

      • I fixed the problem of the ports , the problem was with the RXTX packages i didn’t install it probably since am using windows , now the problem is i connect to the port i need but it always gives me msg PortInUseExeception it says that the port am using is owned by unkown application.
        Thanx in advance again , and i need to thank u for ur code it is really helpful and comments of the people as well !

        • Thanks for your interest in my work! Not sure what can be done to solve the PortInUseException. Might have to look deeper into what Windows is doing to see what device really is using that port. I think now it’s to find what’s hogging the port and to turn it off. Other than that, I’m not sure what to tell you. This issue is very specific to your computer and its configuration.

  20. Hello…would you please tell me…how to select the baudrate or how to make the baudrate =2400…plz help…I am not as genius as you desperately need your kind help…

  21. Hello…*; works fine when i run it on netbeans but when i build a .jar file and try to run the .jar file it deos’nt work, why?? plz help…
    u ppl r genius ..plz help a novice like me….thanks in advance..

  22. Hi I am new to java, how to compile this code?
    thank you

  23. In order to have the log text auto-scrolled, you can add (at the end of serialEvent in
    try {
    window.txtLog.scrollRectToVisible(window.txtLog.modelToView(window.txtLog.getDocument().getLength ()));
    catch (javax.swing.text.BadLocationException err) {}

  24. Thank you for this code. Simple clear well explained code.

  25. Very nice. I would like to integrate just the com port part into my own project but dont know how. I have eclipse and netbeans. I am new to java and think i am making it harder than it really is. Can you tell me how to integrate just that part?

    • I think you’re looking for the section that is labeled “Connecting to the Serial Port”. It’s really hard for me to show you how to integrate just the one part because I don’t know how much Java you know and what I’ve written here kind of assumes the reader knows Java. If you’re new to Java, it will be really be hard to follow the code.

      • I am new, but have been learning quickly. I assmue the communicator classs i shoulld change the package to my own, as well as the gui class. I have been using netbeans for the gui design, but think im going to change to eclise. Basically, my gui is to control rgb lighting via jeenodes. Any help is much appreciated.

      • Also, im looking for the com port listing and keybinding.

        • Yup, that is correct, you can change communicator and the GUI classes to whatever your application needs them to be.
          For COM Port listing, there is a method that will list all of those that is mentioned in the post.
          The key binding section is there as well.
          Hope that helps!

  26. hullo, i need urgent help?when the MCU is reading data from memory,what is the system used to prevent data being read from mixing with data coming through the 1/0 ports?

    • That is a good question!
      As far as I know, all serial data sent from the MCU goes through one port (the COM port you assign), and therefore when you retrieve it, you have to have your own way of differentiating the data. I could be wrong, but that is how I understood it.

  27. I am for some reason unable to access the GUI class through the MediaFire links. Could you either send a new MediaFire link or post the code for the GUI class?

  28. Thanks for this. I will be using it for the serial transaction on a card reader my organization is developing. I got rxtx working already and I am using the Eclipse Indigo IDE.
    Keep em coming.

  29. Compliments. For developers wanting to program to serial port without a device like XBee, I think VSPE will be a good one. I am presently using it.
    My question, do you have any Session and Persistence related tutorial for a Desktop Application that occasionally will be connecting to the Server.

  30. Yours was a good read and I have increased my Java handling with the tutorial and references you gave. It really settled a lot of things for me.

    Still expecting a response to my request on Sessions and Persistence.

    Thanks all the way.

    • I just took a look at this Virtual Serial Ports Emulator. Looks like a really good tool to use actually. This is way better than me wiring up something to test with. Thanks for this!

      Regarding session and persistence, I’m afraid I’m not familiar with those topics, so I don’t think I can offer much help there. Sorry!

  31. Compliments.

    Been trying to do this for a while but not getting thro. I can send bytes using write(); but I need to send i.e. write my data in hexadecimal and Outputstream to serial port. Looking at StringBuffer but it does not have a write method. I hope this is clear.
    Thanks everyone.

    • There might be a way to send data with different encodings? Or perhaps you can convert your hex data into bytes and then convert them back into hex data on the receiving end?

  32. hi
    this might seem odd, am kinda new to COM port programming but thanks to you have managed to read data from my ardiuno. followed your link:: :::

    there is a code there that reads data from COM port but cant make it to write data please help my project is stuck.
    thanx in advance
    looking forward to your response

    • I do not know the specifics of your application, but you should take a look into the specifics in the method for writing data to the serial port. PuTTY is a good tool for testing serial ports and I highly recommend it for when you are debugging.

  33. Can you tell me, and would you recommend, the package you use to design your GUI.

  34. I have connected a weight scale bridge machine in my PC via a serial port and that gives me output like this 00001001A +00001001A +00001001A +00001001A +00001001A +00001001A by default and when i put any weight in my bridge like 60 then it gives me result like this 00006001D +00006001D +00006001D +00006001D +00006001D +00006001D. and when i put any weight in my bridge like 90 then it gives me result like this 000090012 +000090012 +000090012 +000090012 +000090012 + But i can’t stop the result buffering that generate simultaneously. Now my question is how to stop my result buffer and append that result and save data in a .text file? I want result like that

    By default: 00001001A

    When 60: 00006001D

    When 90: 000090012


    My code is as below




    public class TwoWaySerialComm
    public TwoWaySerialComm()

    void connect( String portName ) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier
    .getPortIdentifier( portName );
    if( portIdentifier.isCurrentlyOwned() ) {
    System.out.println( “Error: Port is currently in use” );
    } else {
    int timeout = 100000;
    CommPort commPort = this.getClass().getName(), timeout );

    if( commPort instanceof SerialPort ) {
    SerialPort serialPort = ( SerialPort )commPort;
    serialPort.setSerialPortParams( 9600,
    SerialPort.PARITY_NONE );

    InputStream in = serialPort.getInputStream();
    OutputStream out = serialPort.getOutputStream();

    ( new Thread( new SerialReader( in ) ) ).start();
    ( new Thread( new SerialWriter( out ) ) ).start();

    } else {
    System.out.println( “Error: Only serial ports are handled by this example.” );
    /** */
    public static class SerialReader implements Runnable
    InputStream in;

    public SerialReader ( InputStream in )
    { = in;

    public void run ()
    byte[] buffer = new byte[1];

    int len = 0;
    while ( ( len = >= 0 )
    System.out.print(new String(buffer,0,len));

    catch ( IOException e )
    /** */
    public static class SerialWriter implements Runnable
    OutputStream out;

    public SerialWriter ( OutputStream out )
    this.out = out;

    public void run ()
    int c = 0;
    while ( ( c = > 0 )
    File file = new File(“c:/data.text”);
    BufferedWriter dataOut = new BufferedWriter(new FileWriter(file));

    // try {
    // if (dataOut != null) {
    // dataOut.close();
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // }

    catch ( IOException e )

    /**for data write in a text file*/
    // public static class WriteData
    // {
    // void main(String args[])
    // {
    // try
    // {
    // DataOutputStream out = new DataOutputStream(new FileOutputStream(“data.txt”));
    // out.writeInt(100);
    // out.writeChar(‘n’);
    // out.writeDouble(9.8);
    // out.writeChar(‘n’);
    // out.writeUTF(“Bert Wachsmuth”);
    // out.close();
    // }
    // catch(IOException e)
    // {
    // System.out.println(“Problem creating file”);
    // }
    // }
    // }

    public static void main ( String[] args )
    (new TwoWaySerialComm()).connect(“COM2”);
    catch ( Exception e)
    // TODO Auto-generated catch block


    Please help me.

  35. HI, I wanted to send and receive packets to wireless device that acts as a virtual comport. Is your code helpful in achieving my goal

  36. Hello 😀 good tutorials
    I am new in Serial Port programming in Java. I have problem, to read event from Foot Pedal that use Serial Port (Foot Pedal) – RS232 Usb (Connector) – Computer

    Can you explain what step to get event from that Foot Pedal?
    Thank yout before 🙂

    • You would have to look at the datasheets or product information for the foot pedal to see how it sends its serial data so you know how to interpret it. I don’t know the specifics to your hardware, so I can’t really offer much help.

  37. Hello, thanks for the tutorial, pretty much informative, I’d just like to know more about you hardware configuration, how did you connect the motors to the arduino and where in the code does it state the pins declarations.
    your time is appreciated

    • Hi there, I believe this post can help you with that. As well there is a lot of literature online on how to use an Arduino to control motors, which will also teach you how to do the pin declarations.

      • Thanks again for your reply, I’ve be searching for 2 days trying to figure out how to connect the motors to that once i hit the left or right button on your GUI, it responds, there’s something I’m missing here! my project sounds the same as yours!
        and I was also referring to your hardware config. re the XBEEs and the Arduino!
        I’m sorry I might sound a little naive but I’m really skeptical about how should it work together at the very end!

        • This probably means that your hardware isn’t interpreting the packets that you’ve sent. If you are learning this to start, I highly recommend doing this without an XBee. You can still sent the data to an Arduino and there are plenty of tutorials out there that explain that very well.

  38. For those who are still struggling with getting this application to work, here is my command sequence, on Mint13 (with Arduino package previously installed) :
    cp myDownloadArea/serialcomm.rar .
    mkdir TigerControlPanel
    cd TigerControlPanel
    unrar e ../serialcomm.rar
    cd ..
    javac -cp /usr/share/arduino/lib/RXTXcomm.jar TigerControlPanel/*.java
    java -cp :/usr/share/arduino/lib/RXTXcomm.jar -Djava.library.path=”/usr/lib/jni/” TigerControlPanel/GUI (all on one line)
    Good luck.

    • What is usr/lib/jni? is that your personal directory or everyone should should have this on their computer after running the previous line.

  39. Thank you! Your tutorial was really helpful. But I’m having troubles when I try to insert delays between some data that is sent to the Ports. Can you help me with that? Is it done with wait() ?

  40. hi sir.. i really like your post, but his post is related to my thesis .. I could not ask for the source code? because once this deadline..

  41. Hello, i get this error :
    Error 0x16 at /home/bob/foo/rxtx-devel/build/../src/termios.c(2714): The device
    does not recognize the command.

    How to handle it? Thank you

  42. Thanks, Not even using adruino but I needed a serial java connection and Bam… Still have to test it though.

  43. hi in my arduino, all sate of the house like lite on or off , fan on or off is working well but i dont know how to save all this state in in eclipse that will be further use from the server. please let me know if you have any idea or code. thanks.

  44. thank you for this code ,which libraries we have to add???
    and how to add GUI.FORM IN ECLIPSE

  45. serialPort.notifyOnDataAvailable(true);

    You solved my issue! Thanks.

  46. Thx hp, very helpful and complete! Nice job

  47. Hello, I like what you have done here. Nice work! I have a question. I am looking to do the same sort of read and write to and from the ports, but my project is different. At work, I have a tool connected to my laptop. I am only looking to simply listen to the ports for certain “objects’ or ‘strings’ that I define and flag them when they become available. Can you give a suggestion on what I may need to do as far as modifying your codes? Secondly, I don’t think I should use Xbee and arduino, should I?

    I am now excited to work on this project because of your website. i will be doing this on windows by the way.

    Thanks for your help.

    • Hi Karin,

      It sounds like the same thing as what I’ve done except that you don’t have to send any commands – all you’re doing is waiting for specific strings/objects. So when the Java side receives data from the hardware, you just check to see what you’ve got.

      You certainly have lots of options for communicating with hardware. I used an XBee and Arduino because I specifically wanted to learn a little bit more about those when I dove into the electrical design side of things. As far as other alternatives, I don’t know much (electrical design is not my field), but I’m sure Google can give you some nice alternatives.

  48. Wow. Very fast response from you. thank you. am thinking, It doesn’t seem like I will be needing another hardware. Am I wrong? Is there a need for a hardware?

    My set up is set up like this in my project.

    1.I have a hardware, let’s call it ‘B’ connected to my computer ‘A’ and another hardware ‘C’. With this hardware ‘B’, data is constantly streaming from ‘C’ and logged by my computer and I can query ‘C’ or write to it using the GUI on my computer. So, I am already logging the data just fine as it is. The problem is that the data collected takes a lot to be manually analyzed and pain in the neck.

    So, what am really looking to accomplish is to write a code that will listen to the same port as in my setup above and listen for specific words or string and simply flag them on a GUI if I choose to. This way, I get to do a 4 hr work in 10 minutes.

    With his more info, do you suppose I need more hardware still?

    • Before you dive into it further, I think you need to figure out what communication protocol you will be using (e.g. serial, or some other means) and if you are using serial communication, you should play around with Arduino first and see how it all works before diving in further. Then once you have a better understanding of a simpler implementation, you could then move on to the more complex one.

  49. I could not find setConnected(boolean b) and getConnected() methods. What am I missing, pls!

  50. hello,
    i have tried the code written by shamol roy but ii got this error. please help me out.

    Stable Library
    Native lib Version = RXTX-2.1-7pre16
    Java lib Version = RXTX-2.1-7
    WARNING: RXTX Version mismatch
    Jar version = RXTX-2.1-7
    native lib Version = RXTX-2.1-7pre16

  51. Thank you for this detailed tutorial. (Thumbs Up)

  52. Thanks, awesome tutorial! Greetings from Brazil 🙂

  53. Hiii great tuto thanks
    but i have a little problemes with my RF embedded Reader
    i try to send into my Carte some String Data is it a same like your Writedata’s method 0 (int , int ) ?
    Greeting from Paris

  54. Finally a good tutorial!!!
    Greeting from Morocco 🙂

    Unfortunately I have a problem with the baud I can not change the rate.!!!!

  55. Very useful tutorial!
    Greeting from Romania.

  56. thanks it helped me a lotttttttttt…

  57. This tutorial is great ! Thank you for sharing the code. cheers

  58. Thank you so much…Very useful tutorial!

  59. Very nice blog .thanks…… for your post

  60. Thank you very much for the stuff.. It is really very helpful.. 🙂

  61. I am using the serial communication progrm. My question is how can I see hex numbers in the Log window instead of ASCII. or what part of the code do I need to change to see hex numbers. I am just reading no writing

  62. Hi,
    i need to connect my PC to Micro controller through Bluetooth,to make it simple my PC will continuously send string to Micro controller depending upon string micro controller performs task ,can this post will be useful to my problem else can u please guide me?
    Thanks in advance

  63. hello , sir , so i use your code to read and display 2 data but the probleme is that thous 2 data display in the same text area and i want to display them in 2 diffrent text area , i can’t figure out how to do that i use the substring function but it dosn’t work and i don’t know why since the logtext is a string can you help me plz

  64. Hello,
    First of all thanks for providing such a detailed tutorial on this subject.I have a few doubts could you please help me with this ?.I am trying to build a IVR system ,I want to auto answer the call upon ringing (I have done that using at commands).I use a sim900a gsm modem I have successfully send message and called a number .But I have the following problem there is timing issue some times my when executing your code to send message previous commands written is also present in the message recieved why is that ?.Secondly when call is made to gsm modem from Data Available Event is triggered RING RING… text is received .My doubt if if ringEvent is set true( serialPort.notifyOnRingIndicator(true);).But it is not triggering.Even when call is dialled to gsm modem and DataAvailable_Event is triggered With Data RING …Or when Call is made to a Number and starts Ringing.What i wanted to do is when a call is recieved and after call auto answered an audio have to played for navigation of the menu.I have noticed that many code inside switch is not executed except .And weird thing is I tried to send auto ATA command upon finding RING Indicator in data Available handler and its not working Can u help me with this

  65. Hi,

    I have a requirement. My machine “A” connects to a machine “B” . “B” has ‘n’ number of serial ports where ‘n’ devices are connected. How I would retrive the information of ‘n’ device in machine “A”.


    • henrypoon

      November 7, 2015 at 20:19

      How does “A” connect to machine “B”? If you’re using Ethernet, you could use sockets to pass information between machines A and B. For reading serial information with machine B, then this post should have you.

  66. Hello, you have helped me a lot. I am doing a biometric project and had a lot of problem reading from the COM PORT.
    I only have one problem, the serialPort.close makes my java application hang on close, what do I do?
    Please help, I will really appreciate

  67. Thanks for sharing this blog post. I switched to another library for serial port communication as it provides me with hotplug functionality.

  68. venkatesh Nelli

    April 19, 2016 at 02:27

    Your code is use full but when i suddenly removing usb while it connected the jvm closing how to resolve it.

  69. venkatesh Nelli

    May 3, 2016 at 05:30

    Your source code is really useful and I have a small problem in this code. When I suddenly removed xbee cable while it is in connected state. it forcefully closing JVM with an java result 255 error how can I minimize this error.

  70. venkatesh Nelli

    May 3, 2016 at 06:21

    Is there any way to catch that error

  71. Really I nedded this thanks very much to the author.

  72. Sir your article is most knowledgeable, and very nice written.
    but i need little bit help, i need to download documentation of rxtxcomm jar can you please help to search it i can’t able to search it.
    Thanks in Advance

  73. Hi,

    Thank you very much for sharing such a thorough guide for serial communication with Java – it has helped me understand the usage of RXTX a lot!!

    I am pretty new to Java – I have used Serial communication in Python before, but for various reasons, I am having to switch over to Java – and so I just wanted to confirm my understanding of some details about your code: so all of the methods (the public void methodName) code blocks are inside the overall class of Communicator and since you declared the variables (such as serialPort, input, output) inside the class but outside of the functions, you can access them from inside any of the functions? (Also, I think they’re called methods, which I usually call functions, so apologies if I’m using the wrong name.)

    Also, in the code, it looks like the values you’re wanting to write are intergers (leftThrottle, rightThrottle) but you say that serial communication is in bytes – how are you dealing with this or does serial just take care of this issue? I’m mostly wanting to send info as hexidecimal – to make it easy to send characters and integers. Basically is output.write(0x33) the same thing as output.write(‘3’) the same as output.write(51)? (where 51 is an interger and ‘3’ is a character).

    Thanks in advance for any help you can give me!

    • henrypoon

      November 1, 2016 at 01:00

      Regarding the variable scope, yes by declaring them in the class I can access them inside the methods. It would be good for you to read about public/private variables. The explanation is long and lots of articles do a better job of explaining it than me.

      The method to write to the serial port takes an int (max 255 if I’m not mistaken), so if you convert your hex value to an int you should be okay. 51 sounds right.

    • henrypoon

      November 1, 2016 at 01:01

      Good luck with the project!

      • Thank you for your response!

        So if the write to serial takes an int, then you can not send characters (such as a, b, c)? I have been using characters as an initialization byte to ensure that the program is starting with the right information. Is this a property of the output method for RXTX? And do you know of any documentation of RXTX that I can use to see these sort of requirements (or do you just know this from experience?) The wikibook page for Java serial communication ( appears to be sending strings with the output method – it is using JavaComms, but I was under the impression that the way you used RXTX and Javacomms was the same…

      • Actually, apologies, I found a more detailed description of javax.comm – and after a little looking, I think that the write method is instead a property of Java – instead of the java comm library – is that correct? If so, I am unsure as to why only integers can be sent?

  74. The code is not available to download… please add a new link..

Leave a Reply

© 2017 Henry Poon's Blog

Theme by Anders NorénUp ↑

%d bloggers like this: