开发者

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. 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.nextEl开发者_运维问答ement();
        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:

serialPort.close();

The close() method comes from the SerialPort super class CommPort.


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. In windows something similar I presume. This file has to be deleted before reopening the port. Otherwise a nullPointerException will occur. Closing the port deletes this file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜