Comparing Values
Part of the First Circuits section of Coddy's Arduino journey. Lesson 20 of 22.
A condition compares two values. C++ has six ways:
==is equal to!=is not equal to<is less than,>is more than<=is less than or equal to,>=is more than or equal to
A common mistake is writing = where you mean ==. One = stores a value; two compare.
if (count == 5) { ... } // is count 5?
if (count = 5) { ... } // stores 5 in count!The second line compiles, and it is a trap: it puts 5 into count, and since 5 is not 0, the board treats it as true. The braces run every time, and count is reset to 5 each time round.
Challenge
EasyThe starter counts up every 300 ms and prints each number. Make the LED on pin 13 light on one number only:
- if
countis equal to 5, turn the LED on - else, turn it off
The LED should light while the monitor shows 5, and stay off for every other number. Press Run, then Check.
Try it yourself
int count = 0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
count = count + 1;
Serial.println(count);
// LED on when count is 5, off otherwise
delay(300);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in First Circuits
Practice on your own: Arduino playground