Sub topic 7
Making decisions with if, else, and switch
A sketch that only runs the same steps in the same order can't react to anything. Conditionals let it choose a path based on a value. This chapter covers if, else, else if, the logical operators, and switch, including the mistakes that cause most bugs.
Prerequisites
This chapter assumes you can do the following:
- Declare variables such as
int,byte,bool, andchar. - Write a sketch with
setup()andloop(). - Use
Serial.begin()andSerial.println()to print values. - Use the comparison operators (
==,!=,<,>,<=,>=) from the operators chapter.
How a condition works
An if statement evaluates an expression. If the result is true, the block that follows runs. Otherwise, the block is skipped. In C++ (the language Arduino sketches use), any nonzero value counts as true and zero counts as false. A comparison such as level > 500 produces a bool value, true or false.
if and else
The simplest decision turns an LED on when a sensor reading passes a threshold. This sketch reads analog pin A0, which returns a value from 0 to 1023, and prints it so you can see what the board sees.
const byte ledPin = LED_BUILTIN;
const int threshold = 500;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int level = analogRead(A0);
if (level > threshold) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
Serial.println(level);
delay(200);
}The else block runs when the if condition is false. It has no condition of its own. You can omit it when you only need to act in one case.
Always use braces
C++ allows an if without braces, in which case only the next single statement belongs to it. This is legal but fragile:
if (level > threshold)
digitalWrite(ledPin, HIGH);
Serial.println("High"); // runs every time, despite the indentationThe Serial.println line is not part of the if. Indentation means nothing to the compiler. Using braces every time prevents this bug, and it also means you won't forget them when you add a second statement later.
The = versus == mistake
A single = assigns a value. A double == compares two values. Writing the wrong one compiles without an error in most cases:
int mode = 0;
if (mode = 1) { // assigns 1 to mode, then tests 1 (true)
// always runs, and mode is now 1
}The expression mode = 1 evaluates to the assigned value, 1, which counts as true. The branch always runs and the variable is silently changed. Enabling compiler warnings (File > Preferences > Compiler warnings) makes the compiler flag this. Another habit is to put the constant on the left, as in if (1 == mode). A typo there (1 = mode) is a compile error.
Chaining with else if
When there are more than two outcomes, chain conditions. The chain is checked from top to bottom, and the first true condition wins. The rest are skipped.
void setup() {
Serial.begin(9600);
}
void loop() {
int level = analogRead(A0);
if (level < 200) {
Serial.println("Dark");
} else if (level < 600) {
Serial.println("Dim");
} else if (level < 900) {
Serial.println("Bright");
} else {
Serial.println("Very bright");
}
delay(500);
}Because evaluation stops at the first match, the second test does not need to say level >= 200 && level < 600. Reaching that line already means level < 200 was false. Order matters, though. If you put level < 900 first, every reading below 900 would print "Bright" and the other branches would never run.
Combining conditions with logical operators
Three operators combine boolean expressions:
| Operator | Meaning | Example | True when | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|
| `&&` | AND | `a > 10 && a < 20` | both sides are true | ||||
| `\ | \ | ` | OR | `a < 10 \ | \ | a > 20` | at least one side is true |
| `!` | NOT | `!ledOn` | the operand is false |
Use && to test that a value lies inside a range, and || to test that it lies outside one. Beginners often write 10 < a < 20. That compiles, but it does not do what it looks like. It evaluates 10 < a first, which gives 0 or 1, and then compares that result with 20, which is always true.
Short-circuit evaluation
&& and || stop as soon as the result is known. In a && b, if a is false then b is never evaluated. In a || b, if a is true then b is skipped. This matters when the right side has a side effect or could be unsafe:
if (count > 0 && total / count > 100) {
// The division only happens when count is not zero.
}Integer division by zero is undefined behavior in C++. The short-circuit guard prevents it.
Be careful with floating-point equality
Comparing float values with == is unreliable because most decimal fractions can't be stored exactly in binary. After arithmetic, 0.1 + 0.2 == 0.3 is not guaranteed to be true. Compare with a tolerance instead, or use < and >. For sensor values, use integers where you can.
Stopping the flicker: hysteresis
A threshold test has an edge case. If a reading hovers around 500, noise pushes it back and forth across the line, and the output flickers on and off. The fix is to use two thresholds, one to switch on and a lower one to switch off. The state is remembered in a variable between passes through loop().
const byte ledPin = LED_BUILTIN;
const int onAbove = 520;
const int offBelow = 480;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
int level = analogRead(A0);
if (!ledOn && level > onAbove) {
ledOn = true;
} else if (ledOn && level < offBelow) {
ledOn = false;
}
digitalWrite(ledPin, ledOn ? HIGH : LOW);
delay(50);
}Readings between 480 and 520 change nothing. The LED keeps whatever state it already had. The last line uses the conditional operator condition ? a : b, which picks a when the condition is true and b otherwise. It is handy for choosing between two values, but a plain if reads better when each branch does real work.
The variable ledOn is declared at the top of the file, outside any function. This is what lets it keep its value between calls to loop(). The scope chapter covers why in detail.
switch for many fixed choices
When you compare one integer-valued expression against many specific values, switch is cleaner than a long else if chain. This sketch reads single characters from the Serial Monitor and acts on them.
const byte ledPin = LED_BUILTIN;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Send 1 (on), 0 (off), or t (toggle)");
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
switch (command) {
case '1':
ledOn = true;
Serial.println("LED on");
break;
case '0':
ledOn = false;
Serial.println("LED off");
break;
case 't':
case 'T':
ledOn = !ledOn;
Serial.println("LED toggled");
break;
case '\n':
case '\r':
break;
default:
Serial.print("Unknown command: ");
Serial.println(command);
break;
}
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}To try it, open the Serial Monitor at 9600 baud, type a character, and press Enter. The Serial.available() check makes sure a byte is waiting before Serial.read() is called.
How switch works
switch (command)evaluates the expression once and jumps to the matchingcaselabel.breakleaves theswitch. Without it, execution falls through into the next case.defaultruns when no case matches. It is optional, but it is good practice because it catches unexpected input.- The Serial Monitor may append a newline (
'\n') or carriage return ('\r') after each message. The empty'\n'and'\r'cases swallow those characters so they don't trigger thedefaultmessage.
Fall-through, on purpose and by accident
Stacking case 't': directly above case 'T': is intentional fall-through. Both labels share one block of code. Forgetting a break is the common accident. The code of the next case runs as well, and the compiler stays silent. Always check each case for a break. If you do want fall-through with code in between, add a comment saying so.
Limits of switch
- It works only with integer types and
char. You can'tswitchon afloator aString. - Case labels must be constants known at compile time.
case threshold:works ifthresholdis declaredconst int. It does not work with an ordinary variable. - It tests equality only. It can't express ranges such as
level < 200, so useifandelse iffor those. - Declaring a variable inside a case without braces can cause a "jump to case label crosses initialization" error. Wrap the case body in
{ }when you need local variables there.
Choosing between if chains and switch
| Situation | Better choice | Column | Column |
|---|---|---|---|
| Ranges or inequalities | `if` / `else if` | ||
| Two outcomes | `if` / `else` | ||
| One value matched against many constants | `switch` | ||
| Several conditions combined with `&&` or `\ | \ | ` | `if` |
| Value is a `float` or `String` | `if` |
Common errors
- Using
=where==was intended. - Putting a semicolon right after the condition, as in
if (x > 5);. This makes theifcontrol an empty statement, so the following block always runs. - Leaving out
breakin aswitch. - Putting
else ifbranches in the wrong order so that a broad condition hides narrower ones. - Testing floating-point values for exact equality.
- Forgetting that a threshold with noisy input needs hysteresis.
Exercises
Exercise
A sketch reads int temp = analogRead(A0); and must print "OK" when temp is from 300 to 700 inclusive, and "Out of range" otherwise. Write the condition for the if. Then explain why 300 <= temp <= 700 is wrong.
Show answer
Use if (temp >= 300 && temp <= 700) { Serial.println("OK"); } else { Serial.println("Out of range"); }. The expression 300 <= temp <= 700 evaluates 300 <= temp first, which gives 0 or 1, and then compares that result with 700. That comparison is always true, so every reading would print "OK".
Exercise
In this switch, what is printed when value is 2? switch (value) { case 1: Serial.println("A"); case 2: Serial.println("B"); case 3: Serial.println("C"); break; default: Serial.println("D"); } How do you fix it so only "B" prints?
Show answer
It prints "B" and then "C". Case 2 has no break, so execution falls through into case 3, where the break stops it. To print only "B", add break; after Serial.println("B");.