Switch Case Statement


Step 1 - Build the Project

The "switch case" statement 'picks' a code statement to run based on the value of a variable. You can create many unique conditions depending on what the variable value is without using many if-else if statements.

Note on serial monitor: first click "Upload to Maker Board", complete the upload, then click the "Monitor" button. A serial monitor will open just below the code window. This allows the data to be sent from the Maker Board to the serial monitor.

Step 2 - Upload the Code

//Learning examples: Switch //Print a message on the 3rd, 7th, and 10th steps of a cycle, //and i the rest of the time int i = 0; //Message incrementor void setup() { Serial.begin(9600); //Start the serial port //After upload, click the magnifying glass (top right) to see the // serial monitor } void loop() { switch (i){ //Checking variable i case (3): //If i is equal to 3: Serial.println("The 3rd step"); //Code to run when i == 3 //The break signals the end of code to run for this case break; //break stops the evaluation of the remaining cases case (7): //If i is equal to 7 Serial.println("The 7th step"); //Print message //The break signals the end of code to run for this case break; //break stops the evaluation of the remaining cases case (10): //if i is equal to 10 Serial.println("The 10th step");//Print message //The break signals the end of code to run for this case break; //break stops the evaluation of the remaining cases //The default case is optional default: //If i is not caught by any of the above cases Serial.println(i); //Print i //The break signals the end of code to run for this case break; //break stops the evaluation of the remaining cases } i++; //Increase i each time the code loops delay(800); //Slow it down } //Delete one of the break; statements to see what happens // (c) 2016 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

This is a useful tool when your variable will have one of a fixed set of values and you want to do something different based on each value.

Instead of using many different if- else if statements together, the switch doesn't test each condition, but jumps directly to its match and runs the code.

If you don't include a break; statement after each case, the switch case statement will run every case until it hits a break or finishes the statements.