Go Down

Topic: Serial Data (Read 462 times) previous topic - next topic

Hey, I'm kind of a noob at C/C++ types, but I am trying to read in a full command from the serial interface and then parse it. For example, if I send:

mv 180!

The "!" should indicate that this is the end of the command sequence, the "mv" would indicate move and the 180 would be the position of a servo. It could be any number. I have been trying for a couple of hours on adding read bytes to a char* or a string object, but I am having trouble parsing it after that. Any guidance or linking to other forms would be nice. I don't mind reading to figure anything out, just a point in the right direction would be great!

guix

#1
Dec 20, 2012, 06:01 am Last Edit: Dec 20, 2012, 06:06 am by guix Reason: 1
Hello and welcome :)

I will post an example of the method I use:
Code: [Select]

void loop()
{
 if ( Serial.available() > 0 )
 {
   static char input[64];
   static uint8_t i;
   char c = Serial.read();

   if ( c != '\r' && i < 64-1)
     input[i++] = c;

   else
   {
     input[i] = '\0';
     i = 0;
     
     Serial.println( input );
     
     if ( !strncmp( input, "mv", 2 ) )
     {
       int var1 = atoi( input+2 );
         
       if ( var1 >= 0 && var1 <= 359 )
       {
         Serial.print( "you entered parameter: " );
         Serial.println( var1 );
       }
       else
       {
         Serial.println( "Command usage: mv <0-359>" );
       }
     }
   }
 }
}


Code: [Select]

mv
Command usage: mv <0-359>

mv 12
you entered parameter: 12


Modify to suit your needs :)

(Also you need to add more error checking, this is a basic example that you need to improve)

Nick Gammon

http://www.gammon.com.au/serial
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Thanks guys! That's exactly what I was looking for! :smiley-yell:

Go Up