Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find serial ports

Tags:

java

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?

like image 587
user3194834 Avatar asked Feb 19 '26 01:02

user3194834


1 Answers

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.

like image 109
bblincoe Avatar answered Feb 21 '26 14:02

bblincoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!