Switch/case not working

Key is a character from a keyboard, which works ok, but the case doesnt seem to be switching the value of sp_period. (the Serial.println doesnt execute when key is 5.

switch (key) {
case 0: sp_period = 10000; break; // stop motor!
case 1: sp_period = 833; break;
case 2: sp_period = 625; break;
case 3: sp_period = 416; break;
case 4: sp_period = 294; break;
case 5: sp_period = 188; Serial.println (key); break;
case 6: sp_period = 156; break;
default: sp_period = 10000; break;
}

Hello
What datatype is used for the variable KEY?

case 0 is redundant as it's identical in action to the default case.
Unless you're trying to switch an enum or a char or something odd, this switch should work.
Can you expand your code please, the problem may be seen here but it likely happens elsewhere.

You probably need the cases to be ascii characters (encapsulated in '') and not integers:

switch (key) {
case '0': sp_period = 10000; break; // stop motor!
case '1': sp_period = 833; break;
...
default: sp_period = 10000; break;
}

@v_mad you may be confusing the 5 in your switch statement - which is a integer, with the character '5' which is actually stored as the integer 53 (see ASCII character tables).

EDIT: Or change the comparison in the case statement as @Danois90 just pointed out.

The keyboard key that has a 5 outputs the value 53 which is equivalent to '5' .

If you doubt this, put Serial.println(key); as the next line after after you get key.

I do not believe that to be true.

Why is that?

void setup() {
  uint8_t x = 0;

  Serial.begin(115200);
  delay(1000);

  switch (x) {
    case 0:
      Serial.println("Zero");
      break;

    default:
      Serial.println("Default");
      break;
  }
}

void loop() {
}

Serial Monitor Output:

Zero

EDIT:
Never mind. I think I misunderstood your meaning. Thought you were saying that using 'default:' is the same as using 'case 0:'
My bad.

1 Like

Thank you to all. You were right, the key was a char type, so I needed to use '1' rather than 1 etc. Now working fine.
I am very rusty on coding having had a 3+ year break, but I hope to be able to get back up to speed soon.
Cheers

1 Like

I was hoping that was the mistake. I now understand why you initially thought that though :smiley:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.