Open and Close Serial Ports

17,959

Solution 1

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.

Solution 2

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.

Share:
17,959
S Gaber
Author by

S Gaber

Updated on June 04, 2022

Comments

  • S Gaber
    S Gaber almost 2 years

    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.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.