简体   繁体   English

打开和关闭串行端口

[英]Open and Close Serial Ports

I am trying to connect to a Serial Port ... but once I open the Serial Port in the first time. 我正在尝试连接到串行端口 ......但是一旦我第一次打开Serial Port I can't open it again, I've tried to apply. 我不能再打开它,我试着申请。 Here is my code: 这是我的代码:

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

I want to close that port so I can use it for another task. 我想关闭该端口,以便我可以将它用于其他任务。

According to the java Communication API you just have to close() your serial port object: 根据java Communication API,你只需要关闭()你的串口对象:

serialPort.close();

The close() method comes from the SerialPort super class CommPort . close()方法来自SerialPort超类CommPort

serialPort.close(); serialPort.close(); works for me. 适合我。 Be careful not to use the port again before closing it, as a lock file is written to the /var/lock Linux directory. 在关闭端口之前,请注意不要再次使用该端口,因为锁定文件将写入/ var / lock Linux目录。 In windows something similar I presume. 在Windows中我认为类似的东西。 This file has to be deleted before reopening the port. 在重新打开端口之前必须删除此文件。 Otherwise a nullPointerException will occur. 否则将发生nullPointerException。 Closing the port deletes this file. 关闭端口会删除此文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM