Switch Case Statement with Arduino [Guide + Code]

Using a switch case statement with Arduino has many use case’s. It might sound technical, but consider this simple analogy below…

Here is a secret about human relations a boss from long ago once told me. If you and your spouse decide to go out to dinner do not ask, “Where do you want to go?” instead, give a list of options, “Do you want to go to Mike’s Bar and Grill, The Dive, or La Pura Di Mona?”

This allows your spouse to make a quicker decision than having an endless list of local restaurants from which to choose. We both know this doesn’t work that great – but it works in programming pretty well – we call this method a switch case statement.

To get a switch case statement up and running you need to make a list of options. Your list might be something like:

  • case 0: Go to Nepal
  • case 1: Go to Norway
  • case 2: Go to Zanzibar

These options are referred to as cases. Here there are three cases. In order to switch from one case to another, we use a variable that matches the case. So if we want to go to Norway, we need a variable of ‘1’, if we want to change our destination to Zanzibar, we need our variable to change to ‘2’.

The syntax of a switch case statement is surprisingly simple:

switch (trip) {

  case 0:
    goTo(Nepal);
    break;

  case 1:
    goTo(Norway);
    break;

  case 2:
    goTo(Zanzibar);
    break;
}

It starts with the word switch(). Then in the parenthesis, you type the name of the variable that determines the case. Here we have the variable trip. If trip = 0, then the lines of code following case 0: will get executed up to the point where the keyword break is found.

The switch case statement is trying to match a case with the variable in the parenthesis, it will skip over each case until it finds a match – if it does, the code, in that case, is executed. If no match between the variable and the cases is found, the switch case statement is ignored until the next time through the loop(), when it checks for a match again.

Programming Electronics Academy members, check out the Control Structures section of the Arduino Course for Absolute Beginners to learn and practice your programming control flow.

Not a member yet?  Sign up here.

You Will Need

  1. Potentiometer (1) – Any resistance range will work.
  2. Jumper wires (3)
  3. Famous Tolstoy novel (1)

Step-by-Step Instructions

Notice that the circuit we set up is dissimilar to the one in the Arduino IDE sketch. This is because I wanted to keep the component count as low as possible to complete the exercises in this book – so instead of using a photoresistor to adjust the voltage at an analog pin, we use a potentiometer. I know, not nearly as exciting, but it gets the point across. If you have a photoresistor, use that if you like.

  1. Place the potentiometer into the breadboard.
  2. Run a jumper wire from the 5-Volt pin of the Arduino to either one of the outside pins of the potentiometer.
  3. Run another jumper wire from one of the ground pins on the Arduino (labeled GND) to the other outside pin of the potentiometer.
  4. Run the final jumper wire from pin A0 on the Arduino to the middle pin of the potentiometer.
  5. Plug the Arduino into your computer.
  6. Open up the Arduino IDE.
  7. Open the sketch for this section.
  8. Click the Verify button on the top left side of the screen. It will turn orange and then back to blue once it has finished.
  9. Click the Upload button (next to the Verify button). It will turn orange and then back to blue once it has finished.
  10. On the menu bar, go to Tools > Serial Monitor – this will open the Serial Monitor window – you should see numbers rolling down this screen.
  11. Now adjust the knob of your potentiometer and watch the serial monitor window, the output changes based on the potentiometer adjustment.
Adruino Board Set up For Switch Case

Arduino Code for Switch Case Statement

/*
  Switch statement  with serial input

 Demonstrates the use of a switch statement.  The switch
 statement allows you to choose from among a set of discrete values
 of a variable.  It's like a series of if statements.

 To see this sketch in action, open the Serial monitor and send any character.
 The characters a, b, c, d, and e, will turn on LEDs.  Any other character will turn
 the LEDs off.

 The circuit:
 * 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors

 created 1 Jul 2009
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/SwitchCase2
 */

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pins:
  for (int thisPin = 2; thisPin < 7; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // read the sensor:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    // do something different depending on the character received.
    // The switch statement expects single number values for each case;
    // in this exmaple, though, you're using single quotes to tell
    // the controller to get the ASCII value for the character.  For
    // example 'a' = 97, 'b' = 98, and so forth:

    switch (inByte) {
      case 'a':
        digitalWrite(2, HIGH);
        break;
      case 'b':
        digitalWrite(3, HIGH);
        break;
      case 'c':
        digitalWrite(4, HIGH);
        break;
      case 'd':
        digitalWrite(5, HIGH);
        break;
      case 'e':
        digitalWrite(6, HIGH);
        break;
      default:
        // turn all the LEDs off:
        for (int thisPin = 2; thisPin < 7; thisPin++) {
          digitalWrite(thisPin, LOW);
        }
    }
  }
}

Switch Case Statement code line by line

The first thing we want to take care of (as usual) is initializing and declaring variables for use throughout the program. We use two constant integers. These integers will be used to map the analog input range to a much smaller range to use with our switch case statement.

const int min = 0;      // Lowest reading at analog pin

const int max = 1023 // Highest reading at analog pin

In setup(), all we need to do is begin serial communication using the begin() function from the Serial library. Easy enough.

Moving on to loop() we want to check our sensor value right off the bat and assign it to a variable:

int sensorReading = analogRead(A0);

The analogRead() function reads the voltage at the specified analog pin. This value is assigned to an integer called sensorReading.

Every time through the loop, a new value will be assigned to this variable based on the value at analog pin A0. Recall that analogRead() returns a value in the range from 0 to 1023. That is 1024 distinct possibilities – we could make a case for each one if we were really crazed, but instead of that we will condense this range into a very small range of 0 through 3 using the map() function:

int range = map(sensorReading, min, max, 0, 3);

The map() function is used to convert a value from one range to another range. The map() function takes five arguments:

map(Variable_to_be_Mapped, Low_Initial_Range, High_Initial_Range, New_Low, New_High)

The output of the map() function converts the Variable_to_be_Mapped argument from it’s initial range, to the new range. The chart below can help you visualize this.

The initial range we pass is 0 through 1023. The range we want to convert to is 0 through 3. This results in the following output values:

Switch Case Range Output Chart
Switch Case Range Map
Switch Case Code Diagram

Using this condensed range allows us to easily match 4 different cases – which is good because up next is our switch case statement:

switch (range) {

case 0: //Potentiometer turned up to 0-25%

  Serial.println(“low”);

  break;

case 1:   //Potentiometer turned up to 26-50%

  Serial.println(“medium”);

  break;

case 2:   //Potentiometer turned up to 51-75%

  Serial.println(“high”);

  break;

case 3:   //Potentiometer turned up to 76-100%

  Serial.println(“ridiculous high”);

  break;

}

We see that we are testing our range variable against four different cases. Each case is followed by a simple println() function that will tell us where we have our potentiometer adjusted by sending text to the serial monitor window.

A quick note on sending text using the print() or println() functions – to let Arduino know you are sending text, you have to surround the text with quotation marks. Each letter has a number value assigned to it (called the ASCII coding), if you forget the quotes, then it will send the numbers and not the text.

Programming Electronics Academy members, check out the Arduino Course for Absolute Beginners to practice using the Serial Library in your code.

Not a member yet?  Sign up here.

Adjusting the potentiometer changes the voltage being applied at pin A0, this adjusts the reading captured by analogRead(). If the reading at A0 is 4, you will receive a “low”, if it is 742, you will receive “high” and so forth for the different condensed ranges.

The break statement at the end of each case tells the Arduino to finish with the switch case and move on with the rest of the program.

The final touch to this program is putting a delay at the end of the loop() – this will allow the reading at the analog pin to stabilize before taking the next sample. Once the delay is complete we sample analog pin A0 again, map the range, and check for a matching case.

The switch case statement is a great programming tool when you want several specific values to trigger separate blocks of code.

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code