1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

Sunday, February 15, 2009

Serial Port Communication in Java

Every one is searching on Sun Microsystems website for Java serial communication library(javax.comm) for Windows and alas! no results.

To access serial port with java use RXTX Serial port Library

Experts say:

"
If you want to access the serial (RS232) or parallel port with JAVA, you need to install a platform/operating system dependent library. Install either javax.comm from SUN (Sun no longer offer's the Windows platform binaries of javax.comm, however javax.comm 2.0.3 can be used for the Windows platform, by using it in conjunction with the Win32 implementation layer provided by the RxTx project)
or better install the rxtxSerial and/or rxtxParallel library from rxtx.org (Windows, Linux, Mac OS X)."

RXTX will support all type of platforms including Windows, Linux, Mac OS X.It can be downloaded from www.rxtx.org

All platform supported downloads are availabe here http://rxtx.qbang.org/wiki/index.php/Download

Direct Download is here

After downloading this zip file unzip it. It contains libraries for Windows, Linux, Mac OS X in respective directories.Copy dll from Windows directory in your unzipped folder and paste it into "C:\Windows\System32".

It also contains RXTXcomm.jar file, copy this in to your java applications lib directory(If doesn't exist Create the lib directory).

Add reference to this jar file in your application.
Try this sample program that communicate with AT commands(you may use a mobile phone that accepts AT command).


Sample Program (ListPortClass.java)
==============================
import gnu.io.*;
import java.io.*;

public class ListPortClass
{

public static void main(String[] s)
{
try
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");
if (portIdentifier.isCurrentlyOwned())
{
System.out.println("Port in use!");
}
else {
System.out.println(portIdentifier.getName());

SerialPort serialPort = (SerialPort) portIdentifier.open("ListPortClass", 300);
int b = serialPort.getBaudRate();
System.out.println(Integer.toString(b));
serialPort.setSerialPortParams(300, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
OutputStream mOutputToPort = serialPort.getOutputStream();
InputStream mInputFromPort = serialPort.getInputStream();
String mValue = "AT\r";
System.out.println("beginning to Write . \r\n");
mOutputToPort.write(mValue.getBytes());
System.out.println("AT Command Written to Port. \r\n");
mOutputToPort.flush();
System.out.println("Waiting for Reply \r\n");
Thread.sleep(500);
byte mBytesIn [] = new byte[20];
mInputFromPort.read(mBytesIn);
mInputFromPort.read(mBytesIn);
String value = new String(mBytesIn);
System.out.println("Response from Serial Device: "+value);
mOutputToPort.close();
mInputFromPort.close();
}
catch (Exception ex)
{
System.out.println("Exception : " + ex.getMessage());
}

}
}

by,
 software development-webhosting, cochin, kerala

14 comments:

  1. Hi there,

    Thanks for this. You're right, documentation on the subject is scant.

    2 adjustments this code needs:
    - close curly brace before catch block (doesn't compile as is)
    - close the serial port at the end, otherwise you'll only be able to run the code once and will get an "Unknown Application" exception on the second try; serialPort.close();

    Works perfectly for me after that :)

    June.

    ReplyDelete
  2. Hi there,

    Thanks for this. You're right, documentation on the subject is scant.

    2 adjustments this code needs:
    - close curly brace before catch block (doesn't compile as is)
    - close the serial port at the end, otherwise you'll only be able to run the code once and will get an "Unknown Application" exception on the second try; serialPort.close();

    Works perfectly for me after that :)

    June.

    ReplyDelete
  3. i would like to know how to read response from serial device, if it is gps tracker and it sends data all the time? i just want to get command response back...?

    ReplyDelete
  4. HI
    Thanks for the code,I had an external device connected to my pc and is on COM1 port and i had to change the output to COM4 port by java is there any way to change the port by program(Java)
    pls help me sal

    ReplyDelete
  5. Hallo can somebody tell me how i can change the baudrate? It has to be 115200

    ReplyDelete
  6. I personally did not like RXTX to much when I tried it - too tricky and overdesigned. I have used JComWin32 from http://www.caerustech.com/JCommWin32.php - its good someone made an alternative.

    Hans

    ReplyDelete
  7. where can i get documentation on this?pls reply

    ReplyDelete
  8.           I compiled above program with

    javac -classpath RXTXcomm.jar ListPortClass.java
              It compiles successfully but when I run .class file with

    java ListPortClass.class
              It gives following errors,

    java.lang.NoClassDefFoundError: ListPortClass/class
    Caused by: java.lang.ClassNotFoundException: ListPortClass.class
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Could not find the main class: ListPortClass.class. Program will exit.
    Exception in thread "main"

              Please help me resolve the problem. Is there any modification in command of 'java' for executing the file?

    ReplyDelete
  9. i used this tip for communicating with a LPC2148 education board, and for anything to start showing up i had to set DTR = false after opening input stream.

    serialPort.setSerialPortParams(38400,SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    InputStream mInputFromPort;
    try {
    mInputFromPort = serialPort.getInputStream();
    } catch (IOException e) {
    e.printStackTrace();
    return;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(mInputFromPort)); serialPort.setDTR(false);
    serialPort.setRTS(false);
    char[] cbuf = new char[128];
    for (int i = 0; i < 500; i++) {
    Thread.sleep(30);
    int read;
    try {
    read = br.read(cbuf, 0, 128);
    if(read == 0) {continue;}
    System.out.print(new String(cbuf,0,read));
    } catch (IOException e) {
    ;//sometimes an exception over zero byes on stream..
    }
    }
    try {
    br.close();
    } catch (IOException e) {
    e.printStackTrace();
    }

    ReplyDelete
  10. I've been playing with that first rxtx code example for about a month. My computer recently died. Now I can't get the code to work anymore on any machine. It compiles and runs. I don't get any errors. The problem is that I don't get any response from my phone, but I used to. This is seriously driving me nuts. I'm doing most of my programming from netbeans. I even tried running it from the windows command line. It used to work. What am I missing? Please help. I want to send AT commands to my phone again.

    ReplyDelete
  11. I know it's kind of a silly question but where You've put the "serialPort.close()"??
    Tried lots of combinations with no success. I keep getting a prompt :
    Stable Library
    =========================================
    Native lib Version = RXTX-2.1-7
    Java lib Version = RXTX-2.1-7
    COM13
    Exception : Unknown Application
    BUILD SUCCESSFUL (total time: 1 second)

    ReplyDelete
  12. Hello Don't know if my earlier post land here but I've got a silly q. Where exactly put the serialPort.close();?
    Been tryin alot of combinations but none works :S
    Keep gettine this error :
    Stable Library
    =========================================
    Native lib Version = RXTX-2.1-7
    Java lib Version = RXTX-2.1-7
    COM13
    Exception : Unknown Application
    BUILD SUCCESSFUL (total time: 1 second)

    ReplyDelete

Related Posts with Thumbnails