Serial Port Communication in Java

Sometimes, we need to deal with hardware or external devices from a Java application. One of the options how to communicate with them is to use the COM port (also known as serial port inteface) of the PC. Serial port is not only allows you a direct cable connection via physical ports, but it can also establish a connection via virtual ports for Bluetooth, Wi-Fi devices, and etc.

Java applications are executed in Java Virtual Machine (JVM), therefore, they have not direct access to individual memory address and can not communicate directly with any hardware devices. In contrast, C/C++ programming languages allow you to directly access memory address and thereby access to the hardware. What about the use of the C feature to communication with hardware and then call created C functions from Java?

That is no problem with Java Native Interface (JNI). JNI enables Java applications to call another applications written in C/C++ languages (read more about JNI in How to call a C/C++ function from Java).

If you do not want to study how JNI works, there are several libraries that are based on that principle. One of them is jSSC (java serial port communication library), which supports Windows, Linux, Mac and Solaris on both x86 and x64 platforms.

After downloading and adding the library to a Java-project, using the serial port is very simple:

import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class MyCOM {

   public static void main(String[] args) {
      // get computer serial ports names
      String[] portNames = SerialPortList.getPortNames();
      for (String port : portNames) {
         System.out.println(port);
      }

      // inicialization with selecting port for communication
      SerialPort serialPort = new SerialPort("COM3");

      try {
         // open port for communication
         serialPort.openPort();
         // baundRate, numberOfDataBits, numberOfStopBits, parity
         serialPort.setParams(9600, 8, 1, 0);
         // byte data transfer
         serialPort.writeBytes("text to tranfer".getBytes());
         // String data transfer
         serialPort.writeString("text to tranfer");
         // close port
         serialPort.closePort();
      } catch (SerialPortException ex) {
         System.out.println(ex);
      }
   }
}

You can find more examples on the library website.

Leave a Reply