简体   繁体   中英

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?

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 .

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM