Switch case & strings

Right, but you could try something like putting all of your possible commands into an array of Strings, and then comparing the String argument to each element in the array:

String cmd[] = {"Start", "Stop", "Run", "Hide"}; //array of possible commands

String myCommand = "Stop"; // your command

void setup()
{
  Serial.begin(9600);
  int i = -1;
  for (i = 0; i <= sizeof(cmd)/sizeof(cmd[0]); i++) // notice the less than or equal to comparison
  {
    if (myCommand.equals(cmd[i])) // compare String myCommand and Array Element
    break;
  }
  switch (i) 
  {
    case 0:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 1:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 2:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    case 3:
      Serial.print("command was: ");
      Serial.println(myCommand);
      break;
    default: 
      Serial.println("Bad Command");
  }
}

void loop()
{
  
}

I hope that gives you something to work with...

5 Likes