使用C/C++查找Arduino在Ubuntu中连接到的TTY端口

Find which TTY port Arduino is connected to in Ubuntu using C/C++

本文关键字:连接 端口 TTY Ubuntu C++ 查找 Arduino 使用      更新时间:2023-10-16

我正在用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++程序可以打开下一个串行端口。