Tuesday, June 3, 2014

Access the Serial Com Port from java code

Although serial com ports are a very old legacy technology, they are still used in many applications, for example to control some production machines or to access GSM gateways to send sms. The support of the serial port in java was always very weak. In the JDK 1.1 days we had the Java Communication API, and i have used it in some projects with success. But this API was not updated for newer Java versions and i can not get it to run on a new JDK and Windows 64 bit.

So i have to find a new solution and after some googling i have found the "Java simple serial Connector" project which is an excellent solution to access the serial com port from java. The library consists of one jar (jssc.jar) which contains some java classes and the native libraries for Windows (32bit and 64bit) Mac OS X and Linux. To use the library in your project you have to add the jssc.jar to your class path.

Example how to write to the serial com Port in Java

public class TestComPort {
 public static void main(String[] args) {
  SerialPort serialPort = new SerialPort("COM5");
  try {
   serialPort.openPort();// Open serial port
   serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, 
     SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   serialPort.writeBytes("Hello World".getBytes());
   System.out.println(new String(serialPort.readBytes(10)));
  } catch (SerialPortException e) {

No comments:

Post a Comment