Book
Input and output
Input and output
Completion requirements
View
Switches, speakers, LEDs, and flashing unicorns.
2. Add a button
2.2. if...else statements
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
Inside the loop() function we have what is called a conditional statement. Conditional statements in programming allow something to happen/executed if a condition is met.
Some conditional statements in real life:
- If the birds are flying low, it is going to rain.
- If you turn on the radio, it will play music.
- If the light is red, the cars stop.
The general structure of an if...else statement in C goes like this:
if (some_condition) {
// execute the following if the condition is TRUE
do_this;
and_this;
} else {
// execute the following if the condition is FALSE
do_that;
}
In the Button sketch, the if statement checks to see if buttonState is HIGH. If the condition is met, the
digitalWrite(ledPin, HIGH);
command is executed. If not, the code contained inside the else is executed instead: digitalWrite(ledPin, LOW);
. If statements can exist alone, or with one or more else statements.One important thing to note is that
==
is a comparison operator, not the same as =
, which is an assignment operator. Inside the if statement condition, only the following and their combinations can be used:
x == y (x is equal to y) x != y (x is not equal to y) x < y (x is less than y) x > y (x is greater than y) x <= y (x is less than or equal to y) x >= y (x is greater than or equal to y)