Programming Tutorials

Comment on Tutorial - Sample Java program shows how to write to COM port using Java. By Johanes



Comment Added by : Anonymous

Comment Added at : 2013-03-29 02:39:00

Comment on Tutorial : Sample Java program shows how to write to COM port using Java. By Johanes
import gnu.io.*;
import java.io.*;


public class ListPortClass implements SerialPortEventListener
{

public static void main(String[] s)
{
try
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(\"/dev/ttyS0\");
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(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
serialPort.notifyOnCarrierDetect(true);

serialPort.setOutputBufferSize(100);
serialPort.setInputBufferSize(1000);
serialPort.addEventListener(new ListPortClass());
OutputStream mOutputToPort = serialPort.getOutputStream();

InputStream mInputFromPort = serialPort.getInputStream();
PrintWriter pr=new PrintWriter(mOutputToPort);
FileReader fr=new FileReader(\"/root/Desktop/satya/input.txt\");
BufferedReader br =new BufferedReader(fr);
String st=br.readLine();
System.out.print(st);
mOutputToPort.flush();
mOutputToPort.flush();
System.out.println(\"beginning to Write . \\r\\n\");
mOutputToPort.write((\"$B\").getBytes());

System.out.println(\" Written to Port. \\r\\n\");
mOutputToPort.flush();
System.out.println(\"Waiting for Reply \\r\\n\");

//Thread.sleep(50);
System.out.println(mInputFromPort.available());
byte mBytesIn [] = new byte[20];
int n=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());
}

}


@Override
public void serialEvent(SerialPortEvent spe) {
System.out.println(\"data available\");
}
}


This is my java code for Communicate with ETIM machine....
whenever the machine gets the data of input.txt file, it gives the output as its version .

But while excecuting this code, machine not giving any response back...please solve my problem...

my OS:LINUX


View Tutorial