Hi! I am making a program that will move a specified motor in a specified direction and degrees. A command looks like this: a:+20
That is supposed to move motor A 20 degrees. I think I can do the part where it moves the motor. The command could also be b:-176
That would move motor B back 176 degrees. Does somebody know how I can get the integer and the +/-? I have done some research and can't find a good solution. Another command would be something like this: a:+20,b:145,c:-20,d:+34,e:90,f:45, 1000
That would move 6 different motors in different directions. b:145 means to just move it to that degree and not increase or decrease it. The "1000" at the end means to wait 1000 milliseconds.
Can somebody give me a script that would work? I don't know enough about Arduino to just go off random terminology. I am currently taking a class and having massive issues, which is why I want some way to accomplish that. I cannot change the commands.
I would suggest to study Serial Input Basics to handle getting the command line
then try something like this to extract and parse each token
char command[] = "a:+20,b:145,c:-20,d:+34,e:90,f:45, 1000";
bool parseCommand(char * c) {
Serial.print("Parsing ["); Serial.print(c); Serial.println("]");
char * commaPtr = strtok(c, ",");
while (commaPtr != nullptr) {
Serial.print("\tToken ["); Serial.print(commaPtr); Serial.print("] -> ");
char * colonPtr = strchr(commaPtr, ':');
if (colonPtr != nullptr) { // we have a label
*colonPtr = '\0';
Serial.print("Label is '"); Serial.print(commaPtr);
long v = strtol(colonPtr + 1, nullptr, 10); // no fancy error detection but could be done
Serial.print("' and value is "); Serial.println(v);
} else { // we don't have a label, it's a duration
long d = strtol(commaPtr, nullptr, 10); // no fancy error detection but could be done
Serial.print("duration is "); Serial.print(d);
}
commaPtr = strtok(nullptr, ","); // go to next token
}
}
void setup() {
Serial.begin(115200);
parseCommand(command); // this function call will modify the command
}
void loop() {}
you'll see
Parsing [a:+20,b:145,c:-20,d:+34,e:90,f:45, 1000]
Token [a:+20] -> Label is 'a' and value is 20
Token [b:145] -> Label is 'b' and value is 145
Token [c:-20] -> Label is 'c' and value is -20
Token [d:+34] -> Label is 'd' and value is 34
Token [e:90] -> Label is 'e' and value is 90
Token [f:45] -> Label is 'f' and value is 45
Token [ 1000] -> duration is 1000
the strtol() function does the heavy lifting of parsing your value and takes care of the + or - and leading spaces as well