I am new with the whole modbus and serial communication concept so even if this is a really noob question please bear with me!
Ok so I am trying to read values stored on a register, using modbus protocol and RS 232 port. I have written this code, but it is not finding serial port "COM 4"
. What am I doing wrong?
String wantedPortName = "COM 4" ;
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
while (portIdentifiers.hasMoreElements()) {
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
&& pid.getName().equals(wantedPortName)) {
portId = pid;
break;
}
}
if (portId == null) {
System.err.println("Could not find serial port " + wantedPortName);
System.exit(1);
}
In this case, "equals()" will only return true if the references are the same. Since you are testing two different string objects, it will always fail. You must use "compareTo()" instead:
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
&& (pid.getName().compareTO(wantedPortName)==0) ) {
portId = pid;
break;
}