I am writing an application to control my robot with my Android phone via Bluetooth, everything is fine, the data is repeated and checked, but I have some problems with the protocol, in particular, I want my robot wheels to turn when I send a command, such like s,10,100 or s,-30,-10 ... (percentage values).
My problem is that when I want to parse the wheel speed command on my Arduino, I have to parse up to 4 separate bytes to int , for example s,-100,-100 makes my robot return at full speed, but how to parse this so that I could call setSpeed(left, right); with left and right equal to -100?
I know that I can separately analyze each byte and put them together to get an integer, but this is not very elegant, and probably the best solution for all this already, unfortunately, I have not yet found.
EDIT
Here is my Arduino function for parsing my commands:
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; }
You call it that when analyzing something like s,100,-100 (should be \0 completed):
char serialData[16]; void loop() { if(Serial.available() > 0) { Serial.readBytesUntil('\0', serialData, 15); switch(serialData[0]) { case 's': int speed[2]; parseCommand(serialData, speed); setSpeed(speed[0], speed[1]); break; }