簡體   English   中英

如何通過CommPortIdentifier找到COM端口

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM