Get Help
Switch Statements
Using a Number to Make Decisions
Switch statements work like large sets of if statements using the equals logic operator. They are useful if you need to do a lot of comparisons based on one variable. Here’s what we’ll be covering in this lesson:What a Switch Statement Looks Like
Switch statements use integers kind of like a condition, or the question they are asking. Only now it’s called a parameter. The switch statement asks for the number and compares it to a bunch of “case” statements. When the robot finds the case statement that has the same value as the parameter it runs the code inside that case statement. The switch statement will keep running code until it gets to a break; command. So make sure you put in break commands, otherwise the switch statement will move on to the next case in the code! Also, remember that in more complicated code you can even nest switch statements inside of other switch statements (or if statements, while loops or for loops) kind of like we talked about with nested if statements. Here is the generic form of a switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
switch ( parameter ) { case value1: statement1; break; case value2: statement2; statement3; break; default: statement4; break; } |
Break Commands
Break commands tell the robot that it can stop executing code inside of the switch statement. When the robot gets to a break; command it will automatically hop to the very end of the switch statement. If you don’t have a break command the robot will just keep executing whatever code comes next, even if it’s in a different case statement! You can think of the break command like telling the robot that after it finishes making the meal it can stop cooking. Otherwise the robot will just go to the next meal on the list (even though no one order it!) and cook that one too!Default Statements
You always need a default statement in your switch statements. It’s a way to say to the robot- didn’t see anything that matched the parameter? Well, do the following code instead then. You can think of the default statement as a set of instructions that tell the robot- if what the person ordered isn’t on the menu, just go ahead and make nachos. Everybody likes nachos.Try it with Sparki
A good example of code that uses switches is the remote control receiver. The remote control gives it a code, which Sparki can then use to make decisions. This code uses the bottom 3 buttons of the remote to change the RGB LED color.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <Sparki.h> void setup() { } void loop() { int code = sparki.readIR(); // look for a remote control code switch(code){ case 66: sparki.RGB(RGB_RED); // make RGB LED Red break; case 82: sparki.RGB(RGB_GREEN); // make RGB LED Green break; case 74: sparki.RGB(RGB_BLUE); // make RGB LED Blue break; default: break; } } |