Choosing With switch
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 8 of 18.
When one variable can have several values and each value needs its own code, a chain of if and else if gets long. switch does the same job and reads like a list:
switch (zone) {
case 0:
// runs when zone is 0
break;
case 1:
// runs when zone is 1
break;
default:
// runs when no case matched (optional)
break;
}switch jumps to the case whose number matches and runs the lines below it. break leaves the switch. Forget a break and the board keeps going into the next case's lines too, which is called falling through.
Here the knob is cut into four zones. analogRead() gives 0 to 1023, and dividing by 256 gives a whole number: 0 for the bottom quarter, then 1, 2 and 3 at the top. Each zone shows its own colour on the RGB LED.
Challenge
EasyTurn the knob into a colour picker with switch:
- zone 0: red (already written)
- zone 1: green
- zone 2: blue
- zone 3: white (all three on)
Use setColor() and end each case with break;. Press Run, turn the knob, then Check.
Try it yourself
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void setColor(int red, int green, int blue) {
digitalWrite(redPin, red);
digitalWrite(greenPin, green);
digitalWrite(bluePin, blue);
}
void loop() {
int zone = analogRead(A0) / 256; // 0, 1, 2 or 3
switch (zone) {
case 0:
setColor(HIGH, LOW, LOW); // red
break;
// add zones 1, 2 and 3 here
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Timing Without Delay
Practice on your own: Arduino playground