How to find a COM port via CommPortIdentifier

左心房为你撑大大i 提交于 2019-12-23 03:44:27

问题


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

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



回答2:


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

?



来源:https://stackoverflow.com/questions/14786432/how-to-find-a-com-port-via-commportidentifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!