Wednesday, November 18, 2009

Java Communication API - Serial Port Communication

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports) and limited access to IEEE-1284 (parallel ports), SPP mode.

How To use javax.comm


This package contains following files.
1.    comm.jar
2.    win32com.dll
3.    javax.comm.properties
Place the above files in below location.
comm.jar should be placed in:
    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib/ext

win32com.dll should be placed in:
    %JAVA_HOME%/bin
    %JAVA_HOME%/jre/bin
    %windir%System32
javax.comm.properties should be placed in:
    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib

Download Link:


How to Read data from Serial Port


import java.io.*;
import java.util.*;
import javax.comm.*;


public class ReadData implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration            portList;
    InputStream                       inputStream;
    SerialPort                serialPort;
    Thread                     readThread;


public static void main(String[] args) {
    boolean                   portFound = false;
    String                      defaultPort = "/dev/term/a";


          if (args.length > 0) {
              defaultPort = args[0];
          }
  
          portList = CommPortIdentifier.getPortIdentifiers();


          while (portList.hasMoreElements()) {
              portId = (CommPortIdentifier) portList.nextElement();
              if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                   if (portId.getName().equals(defaultPort)) {
                       System.out.println("Found port: "+defaultPort);
                       portFound = true;
                       ReadData reader = new ReadData();
                   }
              }
          }
          if (!portFound) {
              System.out.println("port " + defaultPort + " not found.");
          }
         
    }

   public ReadData() {
          try {
              serialPort = (SerialPort) portId.open("ReadApp", 2000);
          } catch (PortInUseException e) {}


          try {
              inputStream = serialPort.getInputStream();
          } catch (IOException e) {}


          try {
              serialPort.addEventListener(this);
          } catch (TooManyListenersException e) {}


          serialPort.notifyOnDataAvailable(true);


          try {
              serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                                                   SerialPort.STOPBITS_1,
                                                   SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}


          readThread = new Thread(this);


          readThread.start();
    }


 public void run() {
          try {
              Thread.sleep(20000);
          } catch (InterruptedException e) {}
    }


 public void serialEvent(SerialPortEvent event) {
          switch (event.getEventType()) {


          case SerialPortEvent.BI:


          case SerialPortEvent.OE:


          case SerialPortEvent.FE:


          case SerialPortEvent.PE:


          case SerialPortEvent.CD:


          case SerialPortEvent.CTS:


          case SerialPortEvent.DSR:


          case SerialPortEvent.RI:


          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
              break;


          case SerialPortEvent.DATA_AVAILABLE:
              byte[] readBuffer = new byte[20];


              try {
                   while (inputStream.available() > 0) {
                       int numBytes = inputStream.read(readBuffer);
                   }


                   System.out.print(new String(readBuffer));
              } catch (IOException e) {}


              break;
          }
    }


}



How to write data to serial port


import java.io.*;
import java.util.*;
import javax.comm.*;


public class WriteData {
    static Enumeration            portList;
    static CommPortIdentifier portId;
    static String             messageString = "Hello, world!";
    static SerialPort       serialPort;
    static OutputStream       outputStream;
    static boolean          outputBufferEmptyFlag = false;
  

public static void main(String[] args) {
          boolean portFound = false;
          String  defaultPort = "/dev/term/a";


          if (args.length > 0) {
              defaultPort = args[0];
          }


          portList = CommPortIdentifier.getPortIdentifiers();


          while (portList.hasMoreElements()) {
              portId = (CommPortIdentifier) portList.nextElement();


              if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {


                   if (portId.getName().equals(defaultPort)) {
                       System.out.println("Found port " + defaultPort);


                       portFound = true;


                       try {
                             serialPort =
                                 (SerialPort) portId.open("WriteData          
                             ", 2000);
                       } catch (PortInUseException e) {
                             System.out.println("Port in use.");


                             continue;
                       }


                       try {
                             outputStream = serialPort.getOutputStream();
                       } catch (IOException e) {}


                       try {
                             serialPort.setSerialPortParams(9600,
                                                                 SerialPort.DATABITS_8,
                                                                 SerialPort.STOPBITS_1,
                                                                 SerialPort.PARITY_NONE);
                       } catch (UnsupportedCommOperationException e) {}
         


                       try {
                             serialPort.notifyOnOutputEmpty(true);
                       } catch (Exception e) {
                             System.out.println("Error setting event notification");
                             System.out.println(e.toString());
                             System.exit(-1);
                       }
                      
                      
                       System.out.println(
                             "Writing \""+messageString+"\" to "
                             +serialPort.getName());


                       try {
                             outputStream.write(messageString.getBytes());
                       } catch (IOException e) {}


                       try {
                          Thread.sleep(2000);  // Be sure data is xferred before closing
                       } catch (Exception e) {}
                       serialPort.close();
                       System.exit(1);
                   }
              }
          }


          if (!portFound) {
              System.out.println("port " + defaultPort + " not found.");
          }
    }



}





0 Comments:

Post a Comment

The Link Exchange - Your ultimate resource for link exchange!

About This Blog

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP