简体   繁体   English

jSerialComm:动态检测可用串口(热插拔设备)

[英]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.我创建了一个 Java GUI,它在下拉菜单中列出了所有串行端口,用户可以从中选择正确的端口并单击连接。 Connection to an Arduino is then established and the user is able to perform some actions.然后建立与 Arduino 的连接,用户可以执行一些操作。 I get the available ports using Fazecast JSerialComm:我使用 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.这可以完美地工作,但只有在启动我的 Java GUI 之前将 Arduino 插入 Mac 时。 Is there a way to detect a hotplugged device in Java?有没有办法在 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.我已经考虑过定期(每隔一秒左右)获取 com 端口,但对我来说这似乎是一个非常优雅的解决方案。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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