raghavendra
raghavendra

Reputation:

Serial port twoway communication in Java

I'm beginner in Java. In my project datalogger is connected to com port i have to send 15 integer value to port then other device will send back 15 as a response, now I'm writing to OutputStream but I'm not getting response. How to solve this problem? (I'm using javax.com package)

Upvotes: 1

Views: 885

Answers (2)

nithin.cv
nithin.cv

Reputation: 1

Try following sample code

public static void init(String port) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
System.out.println(portId.getName());
    if (portId.getName().equals(port)) {



try {sPort = (SerialPort) portId.open("PORT_NAME", 2000);
             reader = new sms();
             break;
            } 
        catch (Exception e) { System.out.println(e);continue;}
   }
}

}

and call init() method with com port name (like COM15,COM11,COM12 etc..) check your device com port to which it is connected.

Upvotes: 0

Liedman
Liedman

Reputation: 10339

You have to get an InputStream as well, you can't read from the OutputStream. Or am I missing something?

Also, remember to do OutputStream.flush() after writing your output, otherwise your data might be buffered to be sent later - if the responder is waiting for your data, this is most likely where things goes wrong.

Having said that: the javax.comm package is really old. Last time I worked with it, it almost seemed deprecated by Sun, or at least not maintained in any way. You might want to look at other solutions (SerialIO comes to mind).

Upvotes: 3

Related Questions