Hi!
My name is Elisa and I am newbie with Arduino. I connect with Arduino from C++, sending commands to Arduino trhough the COM port. Commands are formated as a String.
Each command string means a LED to be lighted on or a Servo to turn on.
When I just turn on a led or activate a servo everything is ok.
Here is how I send the command to Arduino from C++
Serial *serialPort1;
serialPort1 = new Serial("COM4");
. . .
//'buffer' has the information with the terminal of the arduino where the led/servo is and the voltage
//to apply to the led/servo
buffer = "05100";
if (serialPort1->WriteData(buffer, sizeof(buffer)) == false)
std::cout << "ERROR sending data\n";
But when I do everything at the same time (first I turn on a led,a wait a second (Sleep(1000)) and I activate the servo), this did not work.
To make it work I have to send the order twice so it works. If I send the order just once then it doesn't work. This makes no sense to me.
This is the code that sends two commands (to led and servo)
//led
buffer = "05100";
if (serialPort1->WriteData(buffer, sizeof(buffer)) == false)
std::cout << "ERROR sending data\n";
if (serialPort1->WriteData(buffer, sizeof(buffer)) == false)
std::cout << "ERROR sending data\n";
Sleep(1000);
//servo
buffer = "08100";
if (serialPort1->WriteData(buffer, sizeof(buffer)) == false)
std::cout << "ERROR sending data\n";
if (serialPort1->WriteData(buffer, sizeof(buffer)) == false)
std::cout << "ERROR sending data\n";
Sleep(1000);
And this is the code of the Arduino program that is listening to the COM for commandas to LED and Motor.
#include <Servo.h>
int terminal1, terminal2, tension1, tension2, tension3, pos1, pos2, pos3, max_ang;
float pos_f;
char c;
char *envio;
Servo g_servo8, g_servo9, g_servo10, g_servo11, g_servo12, g_servo13;
void setup(){
//crea el objeto serial
Serial.begin(9600);
max_ang = 180;
//leds
pinMode(5, OUTPUT);
//servos
pinMode(8, OUTPUT);
g_servo8.attach(8);
}
void loop(){
//el arduino espera a recibir algo
while (Serial.available() > 1){
//lee el terminal
terminal1 = Serial.read();
terminal1 = (terminal1 - 48)*10;
terminal2 = Serial.read();
terminal2 = terminal2 - 48 + terminal1;
delay(5); //espera para que le lleguen todos los datos antes de leerlos
if ( terminal2 == 5){
//LEDS
//lee la tension
tension1 = Serial.read();
tension1 = (tension1 - 48)*100;
tension2 = Serial.read();
tension2 = (tension2 - 48)10 + tension1;
tension3 = Serial.read();
tension3 = 2(tension3 - 48 + tension2);
analogWrite(terminal2, tension3);
}
else{
//servos
pos1 = Serial.read();
pos1 = (pos1 - 48)*100;
pos2 = Serial.read();
pos2 = (pos2 - 48)*10 + pos1;
pos3 = Serial.read();
pos3 = (pos3 - 48) + pos2;
pos_f = (float)pos3/100.0 * max_ang;
g_servo8.write(pos_f);
}
}//end while
}
Is that normal? Why does this happen?
Thank you!