Thursday, April 3, 2014

How to connect Serial Port with JAVA

Serial Port Programming
In Java , we commonly use RxTx library for serial programming..
2 Important Things to do:
·         Add RxTx jar into our project..

·         Copy RxTx serial.dll,RxTxParallel into c:\program files\java\jre\bin
To start coding import gnu.io.*…..
Steps:   1) Get Port
               2) Open it & initialize
               3) Starting i/p & o/p stream
               4) Adding event listener to listen for incoming data..
               5) Read
               6) Write
               7) Close

1 ) Get Port
Jobs
Search or specify desired port
Check Usage status
Open and Reserve it

Class javax.comm.CommPortIdentifier

public static Enumeration getPortIdentifiers();
public static CommPortIdentifier getPortIdentifier(String portName);
public boolean isCurrentlyOwned();
public String getPortName();
public int getPortType();

PORT_SERIAL or PORT_PARALLEL
Program Code:
 public void searchPort()
{int i=0;
String []r=new String(5);
Enumeration e=CommPortIdentifier.getPortIdentifiers();
  while(e.hasMoreElements())
{
CommPortIdentifier cpi=(CommPortIdentifier)e.nextElement ();
If((cpi.getPortType()==CommPortIdentifier.PORT_SERIAL)&&(cpi.isCurrentlyOwned==false))
{
   r[i]= cpi.getName();
i++;
}
 return r;}
2)Open  Port
Jobs :

Open and reserve it

Class javax.comm.CommPortIdentifier

public CommPort open(
String appName,// Reservation Name
int timeout// block waiting for port open (MS)
);

Class javax.comm.CommPort



Program Code:
 public CommPort openCommPort(String portName, String apname, int TIMEOUT){
CommPort cp=null;
try{
cpi=(CommPortIdentifier)r.get(portName);}
catch(NoSuchPortException a)
{
}
  try{
//return object of type CommPort
Cp=cpi.open(“apName”,TIMEOUT);
Sp=(SerialPort)cp ;       //cast CommPort objt to Serial Port objt}
 catch(PortInUseException s)
{
}
 open() :                          *    Main method
·         Instructs the program to open port which is stored in CommPort object
·         Then the object casted as a Serial port object for accessing methods and variables specific to serial port class.

Intialize Parameters:
·        Either we can individually set..
·        Or set them using Serialport setParams method..



Jobs

Initialization

Baud-Rate, Data Bits, Stop Bits, Parity, flow control

Class CommPort

public abstract void setSerialPortParams(
int baudrate,
int databits, // DATABITS_8, DATABITS_7,
int stopbits,// STOPBITS_1, STOPBITS_1_5,
int parity// PARITY_NONE, PARITY_ODD,
);

public abstract void setFlowControlMode(

int flowcontrol// FLOWCONTROL_NONE,
// FLOWCONTROL_RTSCTS_IN,
// FLOWCONTROL_RTSCTS_OUT,

·         Baud rate  - transmission rate of signals..
·         Start bit     - logical 0 to indicate receiver to start scanning
·         Data bit     - actual data
·         Parity bit    - for error detection
·         Stop bit      - Clock cycle needed to complete transmission
Code:

sp.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,Seria   lPort.PARITY_NONE);     

3) Starting i/p & o/p stream
Jobs

Use InputStreaming and OutputStreaming of CommPort object to do I/O

Code:
      OutputStream out=sp.getOutputStream();
      InputStream in=sp.getInputStream();

The streams are initialized by returning the input output streams of open serial port.

4)Setting up Event Listeners to Read data

·        Once the port is open,serial port must know whenever there is a data to be read .
·        In event driven approach, when the event is hit,a special block of code will run
·        Class needs to implement serialevent listener..
·        The base class have a method called serialEvent(event)that should be overridden before event code will work.
·        Overriiden defines what happens when the event is hit.
·        addEventlistener(this)-is the event that is always checking for Serial Event.
Code:
sp.addEventListener(this);

5) Reading Data
Public void serialEvent(serialPortEvent evt)
{
If(evt.getEventType()==SerialPortEvent.DATA_AVAILABLE)
{
 try{ byte[] temp;
int  length;
while(length==in.available())
{
 temp=new  byte[]length;
in.read(temp,0,length);
buffer.add(temp);
}
}
6. Write data
  public void writeData(CommPort cp,byte[]data)
{
 try {
out.write(data);
out.flush();
}
}
 Program Code Eg:
Output out=sp.getOutputStream();
String s=”ABCD”
System.out.println(“Begin to write”);
Byte[]data=s.getBytes();
 for(int i=0;i<data.length;i++)
{
 out.write(data[i]);
out.flush();
}
7)Close Connection
 public void disconnect()
{ sp.removeEventListener();
sp.close();
in.close();out.close();}








 Serial Port Programming
In Java , we commonly use RxTx library for serial programming..
2 Important Things to do:
·         Add RxTx jar into our project..

·         Copy RxTx serial.dll,RxTxParallel into c:\program files\java\jre\bin
To start coding import gnu.io.*…..
Steps:   1) Get Port
               2) Open it & initialize
               3) Starting i/p & o/p stream
               4) Adding event listener to listen for incoming data..
               5) Read
               6) Write
               7) Close

1 ) Get Port
Jobs
Search or specify desired port
Check Usage status
Open and Reserve it

Class javax.comm.CommPortIdentifier

public static Enumeration getPortIdentifiers();
public static CommPortIdentifier getPortIdentifier(String portName);
public boolean isCurrentlyOwned();
public String getPortName();
public int getPortType();

PORT_SERIAL or PORT_PARALLEL
Program Code:
 public void searchPort()
{int i=0;
String []r=new String(5);
Enumeration e=CommPortIdentifier.getPortIdentifiers();
  while(e.hasMoreElements())
{
CommPortIdentifier cpi=(CommPortIdentifier)e.nextElement ();
If((cpi.getPortType()==CommPortIdentifier.PORT_SERIAL)&&(cpi.isCurrentlyOwned==false))
{
   r[i]= cpi.getName();
i++;
}
 return r;}
2)Open  Port
Jobs :

Open and reserve it

Class javax.comm.CommPortIdentifier

public CommPort open(
String appName,// Reservation Name
int timeout// block waiting for port open (MS)
);

Class javax.comm.CommPort



Program Code:
 public CommPort openCommPort(String portName, String apname, int TIMEOUT){
CommPort cp=null;
try{
cpi=(CommPortIdentifier)r.get(portName);}
catch(NoSuchPortException a)
{
}
  try{
//return object of type CommPort
Cp=cpi.open(“apName”,TIMEOUT);
Sp=(SerialPort)cp ;       //cast CommPort objt to Serial Port objt}
 catch(PortInUseException s)
{
}
 open() :                          *    Main method
·         Instructs the program to open port which is stored in CommPort object
·         Then the object casted as a Serial port object for accessing methods and variables specific to serial port class.

Intialize Parameters:
·        Either we can individually set..
·        Or set them using Serialport setParams method..



Jobs

Initialization

Baud-Rate, Data Bits, Stop Bits, Parity, flow control

Class CommPort

public abstract void setSerialPortParams(
int baudrate,
int databits, // DATABITS_8, DATABITS_7,
int stopbits,// STOPBITS_1, STOPBITS_1_5,
int parity// PARITY_NONE, PARITY_ODD,
);

public abstract void setFlowControlMode(

int flowcontrol// FLOWCONTROL_NONE,
// FLOWCONTROL_RTSCTS_IN,
// FLOWCONTROL_RTSCTS_OUT,

·         Baud rate  - transmission rate of signals..
·         Start bit     - logical 0 to indicate receiver to start scanning
·         Data bit     - actual data
·         Parity bit    - for error detection
·         Stop bit      - Clock cycle needed to complete transmission
Code:

sp.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,Seria   lPort.PARITY_NONE);     

3) Starting i/p & o/p stream
Jobs

Use InputStreaming and OutputStreaming of CommPort object to do I/O

Code:
      OutputStream out=sp.getOutputStream();
      InputStream in=sp.getInputStream();

The streams are initialized by returning the input output streams of open serial port.

4)Setting up Event Listeners to Read data

·        Once the port is open,serial port must know whenever there is a data to be read .
·        In event driven approach, when the event is hit,a special block of code will run
·        Class needs to implement serialevent listener..
·        The base class have a method called serialEvent(event)that should be overridden before event code will work.
·        Overriiden defines what happens when the event is hit.
·        addEventlistener(this)-is the event that is always checking for Serial Event.
Code:
sp.addEventListener(this);

5) Reading Data
Public void serialEvent(serialPortEvent evt)
{
If(evt.getEventType()==SerialPortEvent.DATA_AVAILABLE)
{
 try{ byte[] temp;
int  length;
while(length==in.available())
{
 temp=new  byte[]length;
in.read(temp,0,length);
buffer.add(temp);
}
}
6. Write data
  public void writeData(CommPort cp,byte[]data)
{
 try {
out.write(data);
out.flush();
}
}
 Program Code Eg:
Output out=sp.getOutputStream();
String s=”ABCD”
System.out.println(“Begin to write”);
Byte[]data=s.getBytes();
 for(int i=0;i<data.length;i++)
{
 out.write(data[i]);
out.flush();
}
7)Close Connection
 public void disconnect()
{ sp.removeEventListener();
sp.close();
in.close();out.close();}

















                       















                       








No comments:

Post a Comment