user3194834
user3194834

Reputation: 31

Find serial ports

I have searched for code that can represent the serial ports I have on. I found this one:

Enumeration pList = CommPortIdentifier.getPortIdentifiers();

// Process the list.CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/tty1");
while (pList.hasMoreElements()) {
  CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();

  System.out.print("Port " + cpi.getName() + " ");
  if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    System.out.println("is a Serial Port: " + cpi);
  } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
    System.out.println("is a Parallel Port: " + cpi);
  } else {
    System.out.println("is an Unknown Port: " + cpi);
  }
}

but it isn't working, it seems that pList doesn't have any elements. Maybe my computer doesn't have any serial ports, in this case how can I check it?

Upvotes: 3

Views: 5475

Answers (2)

Hamid Fadishei
Hamid Fadishei

Reputation: 868

You can use the jSerialComm library. It's pure java and does not require extra native libs.

SerialPort[] ports = SerialPort.getCommPorts();
for (SerialPort port: ports)
    System.out.println(port.getSystemPortName());

Upvotes: 2

bblincoe
bblincoe

Reputation: 2483

If you're using the RXTX library, the following should provide a list of available COM ports on your machine:

  List<String> list = new ArrayList<>();
  Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
  while (thePorts.hasMoreElements())
  {
     CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
     switch (com.getPortType())
     {
        case CommPortIdentifier.PORT_SERIAL:
           list.add(com.getName());
     }
  }

You can check your available COM ports in Windows by using the device manager. Navigate to Ports (COM & LPT). Most desktop computers will have COM1 available. Other devices, such as USB Virtual COM ports, will also be displayed in the list, if they exist.

RXTX has pretty specific instructions for installation. Those instructions can be found here.

Typically, you must perform the following:

  1. copy the rxtxSerial.dll and rxtxParallel.dll to your JRE/bin directory. In Windows this would be C:\Program Files (x86)\Java\jre7\bin or something similar based on your computer.
  2. Then you must copy the rxtx JAR file to C:\Program Files (x86)\Java\jre7\lib\ext.

Note: If you're running in an IDE like Netbeans, you may have to place these files under your JDK/jre.

Upvotes: 2

Related Questions