Sub topic 8
Repeating work with for, while, and do-while
This chapter assumes you can upload a sketch with the Arduino IDE and that you know setup(), loop(), pinMode(), digitalWrite(), variables, and comparison operators. You should also have a board such as an Uno with an LED and resistor on a breadboard. If you have used if statements, you already have what you need.
Why loops matter on a microcontroller
A sketch already repeats itself, because loop() runs forever. Inside one pass of loop(), you often need to repeat a smaller piece of work: flash five LEDs, take ten sensor readings, or wait until a button is pressed. C++ gives you three statements for this: for, while, and do-while.
Each one has a condition. The loop body runs as long as the condition is true. The difference is where the condition is checked and where the counter lives.
| Statement | Condition checked | Body runs at least once? | Typical use |
|---|---|---|---|
| `for` | Before each pass | No | A known number of repetitions |
| `while` | Before each pass | No | Repeat until something changes |
| `do-while` | After each pass | Yes | Do the work first, then decide |
The for loop
A for loop packs three parts into its header, separated by semicolons.
for (initialization; condition; update) {
// body
}- The initialization runs once, before the first pass.
- The condition is checked before every pass. If it is false, the loop ends.
- The update runs after every pass of the body.
Here is a sketch that prints the numbers 0 to 4.
void setup() {
Serial.begin(9600);
for (byte i = 0; i < 5; i++) {
Serial.println(i);
}
Serial.println("Done");
}
void loop() {
}The variable i is declared inside the header, so it exists only inside the loop. That is the scope rule from the variables chapter applied to a loop counter. After the closing brace, i no longer exists, and you can reuse the name in the next loop.
The loop runs with i equal to 0, 1, 2, 3, and 4. When i becomes 5, the condition i < 5 is false and execution continues after the loop. Starting at 0 and using < is the usual convention, because array positions also start at 0.
Counting down and stepping
The update can be any expression. You can count down or step by more than one.
void setup() {
Serial.begin(9600);
for (int i = 10; i > 0; i--) {
Serial.print(i);
Serial.print(" ");
}
Serial.println("Liftoff");
for (int i = 0; i <= 100; i += 25) {
Serial.print(i);
Serial.print(" ");
}
Serial.println();
}
void loop() {
}This prints 10 9 8 7 6 5 4 3 2 1 Liftoff and then 0 25 50 75 100.
Chasing LEDs
The topic's array example is a classic use of for. It lights four LEDs one at a time. The pin numbers live in an array, so adding an LED means changing only the array.
const byte ledPins[] = {3, 4, 5, 6};
const byte ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
void setup() {
for (byte i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (byte i = 0; i < ledCount; i++) {
digitalWrite(ledPins[i], HIGH);
delay(200);
digitalWrite(ledPins[i], LOW);
}
}The expression sizeof(ledPins) / sizeof(ledPins[0]) divides the total bytes in the array by the bytes in one element. That gives the element count without a hard-coded number. The next chapter covers arrays in more detail.
Averaging sensor readings
A for loop is also the natural way to smooth a noisy analog input. This sketch reads pin A0 ten times and prints the average.
void setup() {
Serial.begin(9600);
}
void loop() {
long total = 0;
for (byte i = 0; i < 10; i++) {
total += analogRead(A0);
delay(2);
}
Serial.println(total / 10);
delay(500);
}The total is a long. On an Uno, an int holds at most 32767, and ten readings of up to 1023 can reach 10230, which fits. But with 40 samples the sum could reach 40920 and overflow. Using long for accumulators is a safe habit.
The while loop
A while loop has only a condition. You manage any counter yourself.
while (condition) {
// body
}Use it when you do not know in advance how many passes you need. A common case is waiting for a signal. This sketch holds the program until a button wired to pin 2 is pressed. It uses INPUT_PULLUP, so the pin reads LOW when the button is pressed.
const byte buttonPin = 2;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
Serial.println("Press the button to start");
while (digitalRead(buttonPin) == HIGH) {
// Do nothing until the pin goes LOW.
}
Serial.println("Started");
}
void loop() {
}The loop checks the pin before each pass. If the button is already pressed, the body never runs.
Another common use is waiting for serial data.
void setup() {
Serial.begin(9600);
Serial.println("Type something and press Enter");
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
Serial.print("Got: ");
Serial.println(c);
}
}Serial.available() returns how many bytes are waiting. The loop reads them until the buffer is empty, then returns control to loop(). This is a good pattern: the while ends by itself because reading removes bytes from the buffer.
The do-while loop
A do-while loop checks its condition after the body. The body always runs at least once. Note the semicolon after the closing parenthesis.
do {
// body
} while (condition);This fits cases where you need the work done once before you can test anything. This sketch takes a reading and repeats until the value is inside a valid range, up to a limit of tries.
void setup() {
Serial.begin(9600);
int reading;
byte tries = 0;
do {
reading = analogRead(A0);
tries++;
delay(10);
} while (reading < 100 && tries < 20);
Serial.print("Reading: ");
Serial.println(reading);
Serial.print("Tries: ");
Serial.println(tries);
}
void loop() {
}A while version would need reading to hold a value before the first check. The do-while avoids that extra setup line. The tries counter is a safeguard so the loop cannot run forever if the sensor never reaches 100.
Controlling a loop: break and continue
Two keywords change a loop's flow from inside the body.
breakleaves the loop immediately.continueskips the rest of the current pass and goes to the next check. In aforloop, the update expression still runs.
void setup() {
Serial.begin(9600);
for (byte i = 0; i < 10; i++) {
if (i == 3) {
continue; // skip 3
}
if (i == 7) {
break; // stop at 7
}
Serial.print(i);
Serial.print(" ");
}
Serial.println();
}
void loop() {
}The output is 0 1 2 4 5 6. Use these sparingly. A loop with many break statements is harder to read than one with a clear condition.
Nested loops
A loop can contain another loop. The inner loop runs completely for every pass of the outer loop.
void setup() {
Serial.begin(9600);
for (byte row = 1; row <= 3; row++) {
for (byte col = 1; col <= 4; col++) {
Serial.print(row * col);
Serial.print('\t');
}
Serial.println();
}
}
void loop() {
}This prints a small multiplication table. The body of the inner loop runs 3 × 4 = 12 times. Nested loops multiply their counts, so keep an eye on the total, especially when each pass includes a delay().
Common errors
Off-by-one errors
The most frequent loop bug is running one pass too many or too few. For an array with 4 elements, valid positions are 0 to 3. The loop for (byte i = 0; i <= 4; i++) reads position 4, which is past the end of the array. The Arduino does not warn you. It reads whatever memory comes next, or writes over it if you assign. Use i < count for zero-based positions.
A semicolon after the header
for (byte i = 0; i < 5; i++);
{
Serial.println(i);
}The stray semicolon makes the loop body empty. The block that follows is not part of the loop, and the code does not compile because i is out of scope there. A while (cond); has the same problem, and if the condition never changes, the loop spins forever.
Unsigned counters that count down
A byte or unsigned int can never be negative. This loop never ends.
for (byte i = 3; i >= 0; i--) {
Serial.println(i);
}When i is 0 and decrements, it wraps around to 255. The condition i >= 0 is always true for an unsigned type. Use int for counters that count down past zero.
Loops that never end
A loop with a condition that never becomes false hangs the sketch. For example, while (digitalRead(buttonPin) == HIGH) waits forever if the button is wired wrong. Nothing else in your program runs while it waits, and on a board without a watchdog timer enabled, only a reset recovers it. Add a timeout when the wait depends on something outside the board.
const byte buttonPin = 2;
const unsigned long timeoutMs = 5000;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
unsigned long start = millis();
while (digitalRead(buttonPin) == HIGH && millis() - start < timeoutMs) {
// Wait, but give up after 5 seconds.
}
if (digitalRead(buttonPin) == LOW) {
Serial.println("Button pressed");
} else {
Serial.println("Timed out");
}
}
void loop() {
}Using = instead of ==
while (x = 5) assigns 5 to x, and the result, 5, counts as true. The loop never ends. Write == for comparison.
Loops and delay()
Loops that contain delay() block the whole sketch. The chase example above takes 4 × 200 ms = 800 ms per pass of loop(). A button press during that time can be missed. For short loops that finish quickly, this is fine. When the sketch must stay responsive, replace the delays with millis() checks. The last chapter in this tutorial covers that technique.
Also remember that loop() is itself a loop. If you only need something to repeat forever, you often do not need a while (true) inside it.
Summary of the decision
- Do you know how many times to repeat? Use
for. - Are you waiting for a condition or consuming input? Use
while. - Must the body run once before the first test? Use
do-while. - Could the condition fail to change? Add a counter or a
millis()timeout.
Exercise
This sketch is meant to print the values 5, 4, 3, 2, 1, 0 and then stop, but it prints forever. Why, and how do you fix it? void setup() { Serial.begin(9600); for (unsigned int i = 5; i >= 0; i--) { Serial.println(i); } } void loop() { }
Show answer
The counter i is unsigned, so it can never be below 0. After printing 0, the update i-- wraps i around to 65535 on an Uno, and the condition i >= 0 is always true. Declare the counter as a signed type, for example for (int i = 5; i >= 0; i--), so that i becomes -1 and the condition turns false.
Exercise
Write a for loop that turns on LEDs on pins 3, 4, 5, and 6 one after another, leaving each on, with 100 ms between steps. Then say which loop type you would pick to keep all of them on until a button on pin 2 (INPUT_PULLUP) is pressed.
Show answer
Use an array and a for loop inside setup() or loop(): const byte ledPins[] = {3, 4, 5, 6}; for (byte i = 0; i < 4; i++) { digitalWrite(ledPins[i], HIGH); delay(100); } To wait for the button, use a while loop, because the wait depends on a condition rather than a count: while (digitalRead(2) == HIGH) { } exits once the button pulls the pin LOW.