Com ports are not detected with jSSC

2.6k views Asked by At

I'm trying to implement the transfering data with the help of Com ports in my java application. Firstly I decided to create SerialPort object like this.

 SerialPort serialPort = new SerialPort("COM1");

 try {
        serialPort.openPort();
 } catch (SerialPortException ex) {
        ex.printStackTrace();
 }

However there was an jssc.SerialPortException: Port name - COM1; Method name - openPort(); Exception type - Port not found.

Then I tried to determine, what com ports do I have:

 String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
        System.out.println(portNames[i]);
    }

The result was deplorable: portNames was empty.

Would you please advice me something.

2

There are 2 answers

0
Hercules dd On

There are various ways to handle this.

  1. When application is started, loop over to find what COM Ports are available than open the port only when it has been found. You can also add delay as Windows takes some time to detect and activate the COM Port for use. Windows loads driver and assign a COM port number when we plugin the USB-UART. This means if we insert same module to same physical port every time you will get COM4. So no worries.
  2. If you want to make some more robust solution than, either write your own and use some library that provide USB-UART hotplug detection. So when we insert USB-UART module, this library will tell us which port number is assigned and we open it from our application. One such library I know is SerialPundit
0
GarfieldCat On

I check this code in Windows and it is fine: My USB-to-COM adapter became COM4 in system

import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class Main {
    public static void main(String[] args) {
        SerialPort serialPort;
        serialPort = new SerialPort("COM4");

        try {
            serialPort.openPort();
        } catch (SerialPortException ex) {
            ex.printStackTrace();
        }

        String[] portNames = SerialPortList.getPortNames();
        for (int i = 0; i < portNames.length; i++) {
            System.out.println(portNames[i]);
        }
    }
}

Also I go to Device manager to check COM port. So again, if topic starter's "portNames was empty." maybe something with device driver. He should check there.