Tutorial 14.5: Switch Case Statement (Old Version)

Arduino Course for Absolute Beginners

Here is a secret of human relations my boss of 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 Mikes Bar and Grill, The Dive, or La Pura Di Mona?” This allows your spouse to come to a quicker solution than if you have an endless list of local restaurants from which to choose.

We both know this doesn’t work that great – but it works in programing pretty well – we call this method a Switch Case statement.

Like this Tutorial?  There are a ton more!

Check out the new remastered course, with high quality Audio and HD Video.

Enroll now in a Free 14 part Arduino Short Course

 

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 3 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 variable to be a ’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(), in the parenthesis you type the name of the variable that will be determining the case.  Here we have the variable ‘trip’.  If trip = 0, than lines of code following case 0: will get executed up to the point where the keyword break is found.

What happens is that 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 gets executed and the break keyword.  If no match between the variable and the cases are found, then the switch case statement is ignored until the next time through the loop, to check is a match can be made.

You Will Need

  1. Potentiometer (any resistance range will work)
  2. Jumper Wires - 3
  3. Solder-less Breadboard
  4. At least one famous Tolstoy novel

Want all the components you need for this training at a discounted price?

Check out the:

Arduino Course for Absolute Beginners Savings Kit

Step-by-Step Instructions

You will 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 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’d like.

  1. Place your potentiometer into your breadboard.
  2. Run a jumper wire from the 5-Volt pin of the Arduino either one of the outside pins of your potentiometer.
  3. Run another jumper wire from one of the ground pins on your Arduino (labeled GND) to the other outside pin of your potentiometer.
  4. Run the final jumper wire from pin A0 on your Arduino to the middle pin of the potentiometer.
  5. Plug your Arduino into your computer.
  6. Open up the Arduino IDE.
  7. Go to File > Examples > 05.Control > switchCase
  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 will be based on where you adjust your potentiometer.

Image composed with Fritzing.

Discuss the Sketch

/*

Switch statement

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.

created 1 Jul 2009

modified 9 Apr 2012

by Tom Igoe

modified 9 Sept 2012

by OSHjunkies

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SwitchCase

*/

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

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

void setup() {

// initialize serial communication:

Serial.begin(9600);

}

void loop() {

// read the sensor:

int sensorReading = analogRead(A0);

// map the sensor range to a range of four options:

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

// do something different depending on the

// range value:

switch (range) {

case 0:    //Potentiometer turned between 0-25%

Serial.println(“low”);

break;

case 1:    //Potentiometer turned upto 26-50%

Serial.println(“medium”);

break;

case 2:     //Potentiometer turned upto 51-75%

Serial.println(“high”);

break;

case 3:   //Potentiometer turned upto 76-100%

Serial.println(“ridiculous high”);

break;

}

delay(1);        // delay in between reads for stability

}

You might have noticed that there are differences in this sketch than the one available on your IDE – again, this is because we are using a potentiometer instead of a photoresistor to adjust the voltage at analog pin A0.  You can download the modified code at the bottom of this page, though the code onn your IDE example will run just fine, it is just that some of the comments will refer to a photoresistor instead of a potentiometer.

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

All we need to do in setup() 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 does this quite well, and we assign the reading 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 the range which analogRead() returns is from 0 to 1023.  That is 1024 discreet 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.

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

0-255 <=> 0

256-512 <=> 1

513-768 <=> 2

769-1023 <=> 3

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 upto 0-25%

Serial.println(“low”);

break;

case 1:     //Potentiometer turned upto 26-50%

Serial.println(“medium”);

break;

case 2:     //Potentiometer turned upto 51-75%

Serial.println(“high”);

break;

case 3:     //Potentiometer turned upto 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 some text to the serial monitor window.

A quick not 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.  Since each letter has a number value assigned to it, if you forget the quotes, than it will send the numbers and not the text.

So based on where you adjust your potentiometer, the different reading at the analog pin A0 will signal a different case.  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 lets the Ardunio know 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 in at the end of the loop – this will allow the reading at the analog pin to stabilize before the next sample.

Once the delay is complete, we sample analog pin A0 again, map the range and check for a matching case.

Try On Your Own

  • Add an additional case to the switch case statement.  You will have to expand the map range in order to do this.

Further Reading

 

P.S.

Did you find this page via Twitter, Search or a link from a friend?

This is one section of a 14-part Arduino course designed specifically for newcomers to programming and electronics.  Click here to subscribe to the online course - it's free.

Of course, if it's not for you, you can unsubscribe with just a couple of clicks. And we'll never rent or share your information with anyone - except the mafia.