简体   繁体   中英

How to find a COM port via CommPortIdentifier

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);
}

Looks nice, try without blank in wantedPortName:

String wantedPortName = "COM4" ;

[EDITED]

Can you try this one:

final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
System.err.println(portId.getName());

?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM