Arduino switch case: Avoid Problems and Learn the Right Way to use it. Find out how to write compact code with multiple conditions and how to reduce long lines of 'if-else' statement into short code. Get it right First Time.

Arduino switch case:

  • Is your long list of if-else C code getting hard to read?...

  • ...If so, you need to use to switch-case syntax.

  • How to compact your code using switch case statements.

  • Comparison shows equivalence of switch-case and if-else constructs.

  • Exactly what does the break statement do?

It's easy to write a long string of if else statements over hundreds of lines of code - making your code impossible to follow. Using switch case syntax provides you with a compact form of multiple if-else statements.

    ...Your code will instantly be:

  • Easy to Read.
  • Much Shorter.

Arduino switch case statements let you write lots of conditional statements in a very compact way. They save you from having to write tons of chained if else statements.

The Arduino switch statement takes a single expression.
Multiple Arduino case statements act on the expression.

Here's the general idea:

switch (<expression>) {
   case 3 : <do action 1>; break;
   case 4 : <do action 2>; break;
   default : <do action 3>;
}

If the expression evaluates to 3 then an action 1 is executed.
If the expression evaluates to 4 then an action 2 is executed.
If no matches occur then action 3 is executed (the default action).

What does Arduino switch case do?

The switch statement accepts an expression and you use multiple cases statements to test an expression against the switch expression. If they match then code after the case statement is executed.

The best way to understand it is using an example first coded using Arduino if else statements and then translated into Arduino switch case statements.

The simple example chosen below decodes characters received from the serial port. Some characters have specific actions while some characters can be ignored. Here the characters 'a' and 'r' turn on an LED while the character 'z' turns off the LED. Other characters are ignored.

Arduino if else code

#define LED LED_BUILTIN

void setup(void) {

   Serial.begin(115200);
   Serial.println("Action of if else to demonstrate switch case");

   digitalWrite(LED, LOW);
   pinMode(LED,OUTPUT);
}

void loop(void) {
int command = 0;

   if (Serial.available() ) {
      char ch = Serial.read();

      if (ch=='a') {
         command = 10;

      } else if (ch == 'r') {
         command = 20;

      } else if (ch == 'z') {
         command = 30;

      } else { // Default
         command = 0;
      }
   }

   // Action from detection of command character.

   if (command == 10 || command == 20) {
      digitalWrite(LED, HIGH);
      Serial.println("LED on");

   } else if (command == 30) {
      digitalWrite(LED, LOW);
      Serial.println("LED off");
   }
}

Entering 'a' or 'r' results in turning on the LED, while entering 'z' turns it off, and entering any other character has no effect.

Arduino switch case code

#define LED LED_BUILTIN

void setup(void) {

   Serial.begin(115200);
   Serial.println("Action of Arduino switch case replacing if else");

   digitalWrite(LED, LOW);
   pinMode(LED,OUTPUT);
}

void loop(void) {
int command = 0;

   if (Serial.available() ) {
      char ch = Serial.read();

      switch(ch) {
         case 'a' : command = 10; break;
         case 'r' : command = 20; break;
         case 'z' : command = 30; break;
         default  : command = 0;
      }
   }

   // Action from detection of command character.

   switch( command ) {
      case 10 :
      case 20 :
         digitalWrite(LED, HIGH);
         Serial.println("LED on");
         break;
      case 30 :
         digitalWrite(LED, LOW);
         Serial.println("LED off");
         break;
   }
}

You can see how much more compact the code has become (Arduino switch case allows for compactness and therefore better readability). The expression being compared to the switch expression is also clearer.

Important Observations : Arduino switch case

The break statement

Unlike all other C constructs, curly braces are not used to define the actions within a block of code for an individual case statement. Rather the code to be executed for a matching case statement:

    Starts after the colon and...
    ...ends at the break statement.

Warning: 'break' - usually causes the most problems - when you forget it!

Fall through

You can legitimately miss out a break statement, on purpose, in Arduino switch case syntax (or C). The effect is to create an OR condition. Compare the if-else code (below) to its equivalent Arduino switch case code (also below). In the if-else code, the conditional OR expression '||' is used explicitly.


   if (command == 10 || command == 20) {
      digitalWrite(LED, HIGH);
      Serial.println("LED on");

   } else if (command == 30) {
      digitalWrite(LED, LOW);
      Serial.println("LED off");
   }

For the Arduino switch case code, the OR expression is implied by omission of the break statement. If you leave out the break statement, the flow of operation is for execution of  the code in the next case statement. This continues until a break statement is encountered.


   switch( command ) {
      case 10 :
      case 20 :
         digitalWrite(LED, HIGH);
         Serial.println("LED on");
         break;
      case 30 :
         digitalWrite(LED, LOW);
         Serial.println("LED off");
         break;
   }

In the code above, leaving out the break after the test for expression equal to 10, means the next case statement code is executed i.e. execution continues for code from expression equal to 20. So, if the value of the command variable is 10 or 20 then the LED is set high and the Serial message "LED on" is output.

Expressions : Arduino switch case

Only expressions can be evaluated in the switch and case statements i.e. numbers or boolean values. Here the character evaluates to a single number. So for instance you can not put strings in place of the expressions.

Warning: You can only evaulate expressions (resulting in a number or a boolean value) within Arduino switch case statements.

Default Action

A special extra statement in the Arduino switch case construct is 'default'. This takes the place of the 'tested' expression and is used to catch the condition when none of the other expressions match the switch expression. Here's the example used in the original code above.
      switch(ch) {
         case 'a' : command = 10; break;
         case 'r' : command = 20; break;
         case 'z' : command = 30; break;
         default  : command = 0;
      }
If the character ch is not 'a', or 'r', or 'z' then the variable command is set to 0. So it means that for all other characters received over the serial port, command is set to 0 and therefore all other characters are ignored by the code.

When your code gets too big

If you place a lot of code into each case block the compiler can complain as it runs out of jump address capability. It is the same problem as described in the Arduino-if-else page but you can get round it by factoring in exactly the same way (as the if-else page shows) by defining functions for each case block of code.


Comments

Have your say about what you just read! Leave me a comment in the box below.

Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.



Privacy Policy | Contact | About Me

Site Map | Terms of Use