Arduino Conditional Statements
Arduino Conditional Statements
Conditional statements are essential for writing complex Arduino code. Without
conditional statements, an Arduino would only be able to execute code in a linear
fashion, from beginning to end. With conditional statements, an Arduino can
make decisions and perform different actions based on the current situation.
Basic if statements
if (condition) {
// code to execute if the condition is true
}
The condition can be any expression that evaluates to a boolean value (true or
false). For example, the following if statement will turn on an LED if the value of
the potentiometer is greater than 500:
If the value of the potentiometer is less than or equal to 500, the LED will remain
off.
Else if statements
Else if statements allow you to check multiple conditions and execute different
code depending on which condition is true. The syntax for an else if statement is
as follows:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else if (condition3) {
// code to execute if condition3 is true
} else {
// code to execute if none of the conditions are true
}
For example, the following else if statement will turn on a red LED if the value of
the potentiometer is less than 250, a yellow LED if the value of the potentiometer
is between 250 and 500, and a green LED if the value of the potentiometer is
greater than 500:
Conclusion