Counting Up
Part of the First Circuits section of Coddy's Arduino journey. Lesson 11 of 22.
A variable can change while the sketch runs. This line adds 1 to count:
count = count + 1;Read it right to left: take what is in count, add 1, and store the result back in count. In C++, = means "store", not "is equal to". count++; is a short way to write the same thing.
Writing count + 1; on its own works out the sum and throws it away: nothing is stored.
Where you make the variable matters. Made at the top, it keeps its value from one loop() to the next. Made inside loop(), it is made again, starting from 0, every time loop() starts.
int count = 0; // at the top: made once
void loop() {
count = count + 1;
Serial.println(count); // 1, then 2, then 3...
}Challenge
EasyMake the board count:
- at the top, make
int count = 0; - in
loop(), add 1 tocount, print it, then wait 500 ms
The Serial monitor should show 1, 2, 3 and so on, two numbers a second. Press Run, then Check.
Try it yourself
// make count here
void setup() {
Serial.begin(9600);
}
void loop() {
// add 1 to count, print it, wait 500 ms
}
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