I have been working on a switch case for serial char messages, But i ran in to a little problem.
I can not separate "Q" from "Qe" .. without starting 2 cases. Of course i can throw an if statement for the "Q" but i would like to know if it can be done with a switch case.
The serial commands comes from a windows driver and are quite time sensitive. I don't know if this switch case will be faster than else if statements, perhaps you can tell me ?
Here is my code:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) { // Listen for anything on the serialport
String cmd = Serial.readStringUntil('#'); // Reads string until the "#"
// Available commands: ":U#", ":GD#", ":GR#", ":Sd#", ":Sr#", ":Mn#", ":Ms#", ":Me#", ":Mw#", ":RS#", ":RM#", ":RC#", ":RG#", ":Q#", ":Qe#", ":Qw#", ":Qn#", ":Qs#"
switch (cmd.charAt(1)){ // Reads the 2. char.
case 'U': // if 2. char==U execute case 'U'
Serial.println("U#");
break;
case 'G': //if 2. char==G move on
case 'S': //if 2. char==S move on
case 'M': //if 2. char==M move on
case 'R': //if 2. char==R move on
switch (cmd.charAt(2)){ // And if 3. char==D execute case 'D'
case 'D':
Serial.println("GD#");
break;
case'd':
Serial.println("Sd#");
break;
case 'R':
Serial.println("GR#");
break;
case'r':
Serial.println("Sr#");
break;
case'n':
Serial.println("Mn#");
break;
case's':
Serial.println("Ms#");
break;
case'e':
Serial.println("Me#");
break;
case'w':
Serial.println("Mw#");
break;
case'S':
Serial.println("RS#");
break;
case'M':
Serial.println("RM#");
break;
case'C':
Serial.println("RC#");
break;
case'G':
Serial.println("RG#");
break;
}
}
switch (cmd.charAt(1)){ // Reads the 2. char.
case'Q':
Serial.println("Q#");
break;
}
switch (cmd.charAt(1)){ // Reads the 2. char.
case'Q':
switch (cmd.charAt(2)){ // Reads the 3. char.
case'e':
Serial.println("Qe#");
break;
case'w':
Serial.println("Qw#");
break;
case'n':
Serial.println("Qn#");
break;
case's':
Serial.println("Qs#");
break;
}
}
}//end serial
}// end loop