簡體   English   中英

打開和關閉串行端口

[英]Open and Close Serial Ports

我正在嘗試連接到串行端口 ......但是一旦我第一次打開Serial Port 我不能再打開它,我試着申請。 這是我的代碼:

public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
             if (portId.getName().equals("COM1")) {
                try {
                    serialPort = (SerialPort)
                        portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {}
                try {
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {}
                try {
                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {}
                try {
                    outputStream.write(messageString.getBytes());
                } catch (IOException e) {}
            }
        }
    }
}

我想關閉該端口,以便我可以將它用於其他任務。

根據java Communication API,你只需要關閉()你的串口對象:

serialPort.close();

close()方法來自SerialPort超類CommPort

serialPort.close(); 適合我。 在關閉端口之前,請注意不要再次使用該端口,因為鎖定文件將寫入/ var / lock Linux目錄。 在Windows中我認為類似的東西。 在重新打開端口之前必須刪除此文件。 否則將發生nullPointerException。 關閉端口會刪除此文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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