Pages: [1]   Go Down
Author Topic: Serial Data  (Read 444 times)
0 Members and 1 Guest are viewing this topic.
Kentucky, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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!
Logged

France
Offline Offline
Edison Member
*
Karma: 38
Posts: 1012
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello and welcome smiley

I will post an example of the method I use:
Code:
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:
mv
Command usage: mv <0-359>

mv 12
you entered parameter: 12

Modify to suit your needs smiley

(Also you need to add more error checking, this is a basic example that you need to improve)
« Last Edit: December 20, 2012, 12:06:45 am by guix » Logged

Global Moderator
Melbourne, Australia
Offline Offline
Brattain Member
*****
Karma: 511
Posts: 19358
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

http://www.gammon.com.au/serial
Logged

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

Please post technical questions on the forum - not to me by personal message. Thanks a lot.

Kentucky, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: