3.4 Conditional Statements
Conditional statements allow an Arduino program to make decisions based on whether a condition is true or false.
3.4.1 if Statement
The if statement executes a block of code when a specified condition is true.
if (temperature > 30) {
digitalWrite(13, HIGH);
}
If the temperature is greater than 30, the LED is switched on.
3.4.2 if…else Statement
The if…else statement provides two possible actions.
if (temperature > 30) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
If the temperature is above 30°C, the LED turns on; otherwise, it turns off.
3.4.3 if…else if…else
This structure is useful when several conditions need to be checked.
if (temperature > 35) {
Serial.println(“High temperature”);
} else if (temperature > 25) {
Serial.println(“Normal temperature”);
} else {
Serial.println(“Low temperature”);
}
3.4.4 switch…case
The switch statement is useful when a variable can have several specific values.
int option = 2;
switch (option) {
case 1:
Serial.println(“LED”);
break;
case 2:
Serial.println(“Motor”);
break;
case 3:
Serial.println(“Buzzer”);
break;
default:
Serial.println(“Invalid option”);
}
The break statement stops the program from continuing into the next case.


