我对整个modbus和串行通信概念都是新手,所以即使这是一个非常新手的问题,请耐心等待!
好的,所以我尝试使用modbus协议和RS232端口读取寄存器中存储的值。我写了这段代码,但它找不到串口"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);
}发布于 2013-02-10 04:25:25
在这种情况下,"equals()“只有在引用相同的情况下才会返回true。由于您测试的是两个不同的string对象,因此总是会失败。您必须改用"compareTo()“:
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
&& (pid.getName().compareTO(wantedPortName)==0) ) {
portId = pid;
break;
}发布于 2013-02-09 17:10:41
看起来不错,尝试在wantedPortName中不留空格:
String wantedPortName = "COM4" ;编辑过的
你能试试这个吗:
final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
System.err.println(portId.getName());https://stackoverflow.com/questions/14786432
复制相似问题