gpt4 book ai didi

java - 动态查找字符串以寻址串行端口

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:02 24 4
gpt4 key购买 nike

我有一个用 Java 开发的应用程序,还有一个用 Ruby on Rails 开发的应用程序,它需要通过串行通信连接到 Arduino。虽然我可以根据自己的计算机输入一个字符串来寻址正确的串行端口,但该字符串甚至会根据我使用的 USB 端口而变化,这让我认为用户最好能够选择一个有效的串行端口来自他们自己计算机上的列表扫描的一个,而不是我预先定义的一个。有谁有一种策略可以让用户扫描计算机上的所有串行端口并从数组/列表中选择正确的端口,无论是在 Java 还是 Ruby on Rails 中?

最佳答案

来自List the ports :

import java.util.Enumeration;

import javax.comm.CommPortIdentifier;

/**
* List the ports.
*
* @author Ian F. Darwin, http://www.darwinsys.com/
* @version $Id: CommPortLister.java,v 1.4 2004/02/09 03:33:51 ian Exp $
*/
public class CommPortLister {

/** Simple test program. */
public static void main(String[] ap) {
new CommPortLister().list();
}

/** Ask the Java Communications API * what ports it thinks it has. */
protected void list() {
// get list of ports available on this particular computer,
// by calling static method in CommPortIdentifier.
Enumeration pList = CommPortIdentifier.getPortIdentifiers();

// Process the list.
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);
}
}
}
}

关于java - 动态查找字符串以寻址串行端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com