使用C/C++查找Arduino在Ubuntu中连接到的TTY端口
Find which TTY port Arduino is connected to in Ubuntu using C/C++
我正在用C++编写一个程序,它需要通过USB与Arduino通信。每次Arduino重新启动时,Arduino连接的端口都可能发生变化(例如,位于/dev/ttyAMC0
,Arduino-restart,连接在/dev/ttyAMC1
)。
我使用的代码是
#include <fcntl.h>
...
arduino = open("/dev/ttyAMC0", O_RDWR | O_NOCTTY | O_NDELAY);
if(arduino != -1)
fcntl(_arduino, F_SETFL, 0);
...
每次Arduino更改端口位置时,我都必须在代码中手动更改,然后重新编译程序。
有没有办法确切地确定Arduino连接到哪个端口,并将位置作为字符串(即"/dev/ttyACM1")返回给我?
怎么样:
- 尝试打开
/dev/ttyACM0
- 如果失败,请尝试打开
/dev/ttyACM0
类似这样的东西:
#define SERIALIDX_MIN 0
#define SERIALIDX_MAX 1
int idxSerialPortIndex = SERIALIDX_MIN;
char strSerialPort[oxFF];
while (true) {
sprintf(strSerialPort, "/dev/ttyAMC%d", idxSerialPortIndex);
arduino = open("/dev/ttyAMC0", O_RDWR | O_NOCTTY | O_NDELAY);
if(arduino != -1) {
fcntl(_arduino, F_SETFL, 0);
... // read serial port here
}
if (++idxSerialPortIndex > SERIALIDX_MAX)
idxSerialPortIndex = SERIALIDX_MIN;
}
如果你担心其他设备会出现在/dev/ttyACM0
和/dev/ttyACM1
上,你可以让你的Arduino响应简单的命令字符串。如果它读取ID
,然后是LF(或CR/LF,取决于您的系统),它可以用一些合适的字符串(如**I AM THE MOTHERBUSTING ARDUINO**
)进行响应,这样您的C/C++程序就会知道它是否真的连接到了Arduino。如果没有收到预期的响应,C/C++程序可以打开下一个串行端口。
相关文章:
- 为什么我们应该为网络连接指定一个端口?
- 串行连接正在打开所有端口?
- 如何从活动的 udp 连接获取远程 IP 地址和端口
- TCP与无效的连接块端口连接
- 如何在我的程序中检测GPS设备连接到的端口(C / C)
- 检查 TCP 端口是否可用(未侦听或未连接)
- 获取用于 TCP 连接的随机端口
- 识别与 Windows USB 虚拟 COM 端口的连接事件
- 在读取期间,非重叠串行端口连接是否会阻止写入(反之亦然)
- 无法再连接到仍在被进程侦听的本地端口
- 套接字连接到不存在的ip地址上的端口
- 线程中的套接字接受所有端口连接?C++
- 提升连接后从TCP服务器访问TCP客户端IP地址+端口
- 连接的串行端口C Qt的列表
- 有没有办法确保连接到注册表中显示的串行端口的设备可以使用
- 获取活动udp连接的目标Ip/端口
- 在C/C++中打开与COM端口的连接时出错
- 如何检查服务器端口是否打开并从MFC连接
- Getaddrinfo总是连接.即使没有被动打开的连接,也要监听该端口
- Windows Server 2012上的SNMP扩展代理无法连接到需要数据的端口