[英]How to find a COM port via CommPortIdentifier
我是整个modbus和串行通信概念的新手,所以即使这是一个真正的noob问题,请耐心等待!
好吧我正在尝试使用modbus协议和RS 232端口读取存储在寄存器中的值。 我写了这段代码,但它找不到串口"COM 4"
。 我究竟做错了什么?
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);
}
看起来不错,在wantedPortName中尝试没有空白:
String wantedPortName = "COM4" ;
[EDITED]
你能试试这个:
final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
System.err.println(portId.getName());
?
在这种情况下,“equals()”仅在引用相同时才返回true。 由于您正在测试两个不同的字符串对象,因此它总是会失败。 您必须使用“compareTo()”代替:
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
&& (pid.getName().compareTO(wantedPortName)==0) ) {
portId = pid;
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.