title: Arduino serial data parsing
body: <p>I'm writing an app to control my robot with my Android phone over Bluetooth, everything is goes well, data is echoed and verified, but I'm having some trouble with the protocol, specifically I want my robot's wheels to turn when I send a command such as <code>s,10,100</code> or <code>s,-30,-10</code>... (values in percent).</p>
  
  <p>My problem is that when I want to parse my wheel speed command on my Arduino I must parse <em>from up to 4</em> separate <code>bytes</code> to <code>int</code>, for example <code>s,-100,-100</code> makes my robot go backwards at full speed, but how do I parse this so I can call <code>setSpeed(left, right);</code> with <code>left</code>and <code>right</code> equal to -100?</p>
  
  <p>I know I can separately analyse every byte and put them together to get an integer, but it's not very elegant and there's probably a better solution to all this already, unfortunately I haven't found it yet.</p>
  
  <h1>EDIT</h1>
  
  <p>Here's my Arduino function for parsing my commands:</p>
  
  <pre><code>void parseCommand(char* command, int* returnValues)
  {
    // parsing state machine
    byte i = 2, j = 0, sign = 0;
    int temp = 0;
    while(*(command + i) != '\0')
    {
      switch(*(command + i))
      {
        case ',':
          returnValues[j++] = sign?-temp:temp;
          sign = 0;
          temp = 0;
          break;
        case '-':
          sign = 1;
          break;
        default:
          temp = temp * 10 + *(command + i) - 48;
      }
      i++;
    }
    // set last return value
    returnValues[j] = sign?-temp:temp;
  }
  </code></pre>
  
  <p>You call it this way when parsing something like <code>s,100,-100</code> (must be <code>\0</code> terminated):</p>
  
  <pre><code>char serialData[16];
  void loop()
  {
    if(Serial.available() &gt; 0)
    {
      Serial.readBytesUntil('\0', serialData, 15);
      switch(serialData[0])
      {
        case 's':
          int speed[2];
          parseCommand(serialData, speed);
          setSpeed(speed[0], speed[1]);
          break;
      }
      // always echo
      Serial.write(serialData);
      // end of message is maked with a \0
      Serial.print('\0');
  
      // clear serialData array
      memset(serialData, 0, sizeof(serialData));
    }
  }
  </code></pre>