Sub topic 7
Making Decisions with `if`, `else`, and `switch`
Assume you can open, verify, and upload an Arduino sketch, and that you understand pins, variables, and basic C++ syntax. This chapter uses the built-in LED and the Serial Monitor, so no extra circuit is required.
A conditional lets a sketch choose which statements to run. The if statement tests a condition. A condition is an expression that evaluates to true or false.
Using `if` and `else`
The basic structure is:
if (condition) {
// Runs when condition is true.
} else {
// Runs when condition is false.
}Comparison operators produce Boolean results:
| Operator | Meaning |
|---|---|
| `==` | equal to |
| `!=` | not equal to |
| `<`, `>` | less than, greater than |
| `<=`, `>=` | less than or equal to, greater than or equal to |
The following sketch reads a value from a potentiometer or another analog input. It turns the built-in LED on when the reading reaches the middle of the input range.
const byte ledPin = LED_BUILTIN;
const byte sensorPin = A0;
const int threshold = 512;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(sensorPin);
if (reading >= threshold) {
digitalWrite(ledPin, HIGH);
Serial.println("Bright enough");
} else {
digitalWrite(ledPin, LOW);
Serial.println("Too dark");
}
delay(200);
}An if can be followed by several else if branches. The Arduino runs the first branch whose condition is true. If none is true, it runs the final else, when one exists.
if (reading < 300) {
Serial.println("Low");
} else if (reading < 700) {
Serial.println("Medium");
} else {
Serial.println("High");
}The order matters. A reading of 250 matches the first branch, so later branches are skipped.
Combining conditions
Use && for “and,” || for “or,” and ! for “not.”
if (temperature >= 18 && temperature <= 25) {
Serial.println("Comfortable");
}Parentheses make a complex expression easier to read and prevent ambiguity:
if ((mode == 1 || mode == 2) && enabled) {
Serial.println("Allowed");
}A common error is using = instead of ==. The first assigns a value; the second compares values.
Another common error is writing:
if (reading = 512) {
// Incorrect: assigns 512 to reading.
}Use this instead:
if (reading == 512) {
// Correct: tests whether reading equals 512.
}Choosing among fixed values with `switch`
Use switch when one expression must be compared with several fixed integer or character values.
switch (command) {
case 1:
Serial.println("Start");
break;
case 2:
Serial.println("Stop");
break;
default:
Serial.println("Unknown command");
break;
}break exits the switch. Without it, execution continues into the next case. This behavior is called fall-through and is sometimes useful, but accidental fall-through is usually a bug. default handles every value that has no matching case.
Conditions inside `loop()`
Because loop() runs repeatedly, a condition is tested repeatedly too. If a button remains pressed, its “pressed” branch runs on every pass. To react only once when a button changes state, you need edge detection, which stores the previous state and compares it with the current state.
Exercise
What does this code print when value is 80? if (value < 50) Serial.println("Low"); else if (value < 100) Serial.println("Medium"); else Serial.println("High");
Show answer
It prints Medium, because 80 is not less than 50 but is less than 100.