2

I'm writing a program in C++, and it is required to communicate to an Arduino via USB. Each time the Arduino restarts, it is possible that the port the Arduino is connected to changes (for example, located at /dev/ttyAMC0, Arduino restart, connected at /dev/ttyAMC1).

The code I am using is

#include <fcntl.h>
...
arduino = open("/dev/ttyAMC0", O_RDWR | O_NOCTTY | O_NDELAY);
if(arduino != -1) 
    fcntl(_arduino, F_SETFL, 0);
...

Each time the Arduino changes port locations, I have to manually change this in my code and then re-compile my program.

Is there a way to determine exactly which port the Arduino connected to, and have the location returned to me as a string (that is, "/dev/ttyACM1")?

user2097314
  • 59
  • 1
  • 6

1 Answers1

1

How about:

  • Try to open /dev/ttyACM0
  • If that fails try to open /dev/ttyACM0

Something like this:

#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;
}

If you are worried that other devices will show up on /dev/ttyACM0 and /dev/ttyACM1 you can make your Arduino respond to simple command string. If it reads ID followed by LF (or CR/LF depending on your system), it can respond with some suitable string like **I AM THE MOTHERBUSTING ARDUINO**, whereupon your C/C++ program will know if it is indeed connected to an Arduino. If the expected response isn't received, the C/C++ program can open the next serial port.

angelatlarge
  • 4,012
  • 2
  • 17
  • 35