I need to control a rover sending to Arduino some controls via USB. I send some char characters (w: forward, a: left etc) from a BeagleBone Black with Ubuntu, from a C++ program. Everything works, but I need to run the Arduino’s IDE, on the BeagleBone BEFORE starting my program. If I don’t run the Arduino’s IDE, the rover don’t’ move. I think the IDE sends some command to Arduino to initialize the USB, and I want to do the same, without the IDE, directly from my program. Any ideas?
C++ code:
#include <serial.h>
using namespace std;
int porta;
void scrivi(int portafd, char c) // Scrive sulla porta seriale il comando indicato
{
int n = write(portafd, &c, 1);
if(n<0) // se la scrittura fallisce
fputs(“write() of 1 byte failed!\n”, stderr);
}
int apriPorta() // apre la porta seriale con i relativi settaggi
{
porta = open ("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (porta==1)
{
perror("open_port: Unable to open ");
}
else
fcntl(porta, F_SETFL, 0);
struct termios options;
tcgetattr(porta, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag &= ~CSIZE;
options.c_cflag |=CS8;
options.c_oflag &= ~OPOST;
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(porta, TCSANOW, &options);
return porta;
}
Arduino’s code:
int spe = 100; //Speed 0-255
`
int E1 = 5; //M1 Speed Control
int E2 = 6; //M2 Speed Control
int M1 = 4; //M1 Direction Control
int M2 = 7; //M1 Direction Control
char last = ‘0’;
void st() //Stop
{
digitalWrite(E1,LOW);
digitalWrite(E2,LOW);
}
void advance(char s) //Move forward
{
analogWrite (E1,s); //PWM Speed Control
digitalWrite(M1,LOW);
analogWrite (E2,s);
digitalWrite(M2,LOW);
}
void back_off(char s) //Move backward
{
analogWrite (E1,s);
digitalWrite(M1,HIGH);
analogWrite (E2,s);
digitalWrite(M2,HIGH);
}
void turn_R(char s) //Turn Right
{
analogWrite (E1,s);
digitalWrite(M1,LOW);
analogWrite (E2,s);
digitalWrite(M2,HIGH);
delay(70);
st();
delay(70);
}
void turn_L(char s) //Turn Left
{
analogWrite (E1,s);
digitalWrite(M1,HIGH);
analogWrite (E2,s);
digitalWrite(M2,LOW);
delay(70);
st();
delay(70);
}
void setup(void)
{
int i;
for(i=6;i<=9;i++)
pinMode(i, OUTPUT);
Serial.begin(9600); //Set Baud Rate
Serial.println(“Power On”);
}
void loop(void)
{
char val = Serial.read();
if(val!=-1)
{
switch(val)
{
case ‘w’: //Move Forward
last = ‘w’;
break;
case ‘s’: //Move Backward
last = ‘s’;
break;
case ‘a’: //Turn Left
last = ‘a’;
break;
case ‘d’: //Turn Right
last = ‘d’;
break;
case ‘0’: //Stop
last = ‘0’;
break;
case ‘1’: //Set speed to 100
spe = 100;
break;
case ‘2’: //Set speed to 150
spe = 150;
break;
case ‘3’: //Set speed to 200
spe = 200;
break;
case ‘4’: //Set speed to 255
spe = 255;
break;
}
}
else
{
switch(last)
{
case ‘w’: //Move Forward
advance (spe);
break;
case ‘s’: //Move Backward
back_off (spe);
break;
case ‘a’: //Turn Left
turn_L (200);
break;
case ‘d’: //Turn Right
turn_R (200);
break;
case ‘0’: //Stop
st();
break;
}
Delay(40);
}
}
`