简体   繁体   中英

jSerialComm: dynamically detect available serial ports (hotplug device)

I've created a Java GUI which lists all serial ports in a drop down menu from which the user selects the correct port and clicks connect. Connection to an Arduino is then established and the user is able to perform some actions. I get the available ports using Fazecast JSerialComm:

SerialPort[] ports = SerialPort.getCommPorts();

I grab the ports and put the results into the drop down. This works flawlessly BUT only when the Arduino is plugged into the Mac BEFORE launching my Java GUI. Is there a way to detect a hotplugged device in Java? I already thought of getting the com ports periodically (every second or so) but to me that does seem to be a very elegant solution.

You might do this by checking if the port is opened or not after trying to open it using:

SerialPorts[] ports = SerialPorts.getCommPorts();
Serial port;
for (port: ports) {
    if (port.isOpen) break; // and this will be the serial port
}

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