This time a different code gives me headache. I'm trying to control two DC motors from the serial. The idea is that the direction and the speed of the two motors is determined by commands starting with the character 'l' (left) or 'r' (right). The character is followed then by a numeric value. A function called 'parse' creates a string and then turns is into an int. However the console tells me otherwise... somehow I got lost.
char inData[10];
int index;
boolean started = false;
boolean ended = false;
void setup()
{
Serial.begin(9600);
Serial.println("**************READY****************");
}
void loop()
{
while(Serial.available() > 0)
{
int l=parse('l');
int r=parse('r');
drive(5,6,'l','L' );
drive(9,10,'r','R');
// Serial.println(Serial.read());
}
}
int parse(char id){
char aChar = Serial.read();
if(aChar == id)
{
started = true;
index = 0;
inData[index] = '\0';
}
else if(aChar == '\n')
{
ended = true;
}
else if(started)
{
inData[index] = aChar;
index++;
inData[index] = '\0';
}
if(started && ended)
{
int inInt = atoi(inData); // Convert the string to an integer
return inInt;
// Get ready for the next time
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
void drive(int p1,int p2, int dir, char eyed)
{
if(dir>0){
analogWrite(p1,dir);
analogWrite(p2,0);
Serial.print(eyed);
Serial.print(" ");;
Serial.println('f');
}
else if(dir<0)
{
analogWrite(p1,0);
analogWrite(p2,dir);
Serial.print(eyed);
Serial.print(" ");
Serial.println('b');
}
else if(dir==0)
{
analogWrite(p1,0);
analogWrite(p2,0);
Serial.print(eyed);
Serial.print(" ");
Serial.println('n');
}
}
Where did I go wrong?