Parsing serial in data - a bit stuck!

Hi,

I am trying to do something very simple with serial data coming into the Arduino. For whatever reason, I am now totally stuck with parsing the data coming in.

Here is what I want to do:

Serial coming in as decimal numbers, 134, 115, 100 etc…

I want the Arduino to look at these numbers, and do something depending on if they are greater or less than a set variable.

Here is my code so far…

#include <Servo.h>

Servo myservo1; // create servo object to control a servo
Servo myservo2; // create servo object to control a servo

void setup()
{
Serial.begin(9600);
myservo1.detach();
myservo2.detach();
}

void loop()
{

if (Serial.available() > 0) {
int moveServo = Serial.read();
if (moveServo > 140)
{
myservo1.attach(9);
myservo1.write(110);
myservo2.attach(10);
myservo2.write(110);
}
else if (moveServo < 120)
{
myservo1.attach(9);
myservo1.write(50);
myservo2.attach(10);
myservo2.write(50);
}
else
{
myservo1.detach();
myservo2.detach();
}
Serial.println(moveServo);

}

}

Any help?

Thanks.

That code looks OK -- what's the trouble with it?

It does not work, if I send 110 the servos should turn one way, and eg 160, the other way?

Anything I send just starts them turning, the detach does not work either :frowning:

Serial.read() only returns the first byte available (in ascii). So, you will have to do some more work to receive a 3 digit number. There are many examples on the forum. I don't have time at the moment, but if you can't find something I will try to find a link tomorrow.

Hi,

Yup thats the exact problem I have, all I am getting is:

1 0 0

I'll have a look in the meantime for an example, but if you do find a specific one, that will be great!

Cheers.

To get that code working you need to know how the sending data is formatted. If its always 3 ascii characters (with no trailing carriage return) you can do something like this:

  if (Serial.available() >=3) {
    int moveServo = 0;
    for(int mult = 100; mult; mult /= 10){
      int digit = Serial.read() - '0' ;  // convert ascii to an integer
      moveServo += digit * mult;       
    }   
    if (moveServo > 140)     { 
      // write value to servo
    } 
  }

You would need to modify the code to ignore a terminating carriage return if your incoming string has this.

Also, why are you detaching after each write? Perhaps you can say more about what you want your sketch to do.

I have a netbook on wheels...

The netbook uses it's camera to follow targets, feeds the coords over serial to a couple of Futaba s3003 modded servos, via the Arduino.

I don't need to detach the servos, it was just for testing.

I'll check your code out, thanks :-)

Cool - looking forward to reading about how you get on :)

Have fun!

This thread should help you get going:

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1232462410/7