Lesson 22 - Using while Loop
Learn how while loops repeat code based on a condition and how to avoid infinite loop mistakes.
Progress indicator
Lesson 22 of 28
Learning Objectives
- Understand what a while loop is and when it is useful.
- Write correct while loop syntax with a clear condition.
- Explain how loop condition behavior controls repetition.
- Identify infinite while loop risks and prevent them.
- Compare while loop and for loop in practical Arduino tasks.
- Read nested while loop flow without confusion.
Concept Explanation
What is while Loop
A while loop repeats code as long as its condition remains true.
Unlike for, it is often used when you do not know exactly how many repetitions you need before starting.
while Loop Syntax
while (condition) {
// repeated code
}How while Loop Works
- Check condition before running the loop body.
- If true, execute the body.
- Update values inside the loop so condition can eventually change.
- Check condition again and repeat.
- Exit when condition becomes false.
A while loop is condition-first logic. If the condition is false at the start, the loop body will not run even once.
Loop Condition Behavior
Condition is tested before each cycle. If it starts false, loop body runs zero times.
In our example, blinkCount < 5 controls when blinking stops.
| Check | blinkCount | Condition blinkCount < 5 |
|---|---|---|
| Start | 0 | true (run) |
| After 1st update | 1 | true (run) |
| After 4th update | 4 | true (run) |
| After 5th update | 5 | false (exit) |
Infinite while Loop Risk
If you forget to update loop variables, condition may stay true forever and the loop may never exit.
while (blinkCount < 5) {
// blinkCount is never changed -> infinite loop risk
}On real hardware, an infinite loop can make your board appear frozen because code never reaches later logic.
while vs for Loop (Comparison)
- Use
forwhen count/steps are known in advance. - Use
whilewhen repetition depends on runtime condition. - Both can do similar tasks, but readability depends on context.
Nested while Loops
A while loop inside another while loop can model repeated grouped tasks.
int row = 0;
while (row < 2) {
int col = 0;
while (col < 3) {
col++;
}
row++;
}When to Use while Loop
- Wait for a condition to become true
- Read input until a stop condition is met
- Repeat actions until sensor/state reaches a target
Example Code
This example uses while loop to blink LED 5 times based on a condition.
const int ledPin = 2;
int blinkCount = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
blinkCount = 0;
while (blinkCount < 5) {
digitalWrite(ledPin, HIGH);
Serial.print("while cycle: ");
Serial.println(blinkCount);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
blinkCount = blinkCount + 1;
}
Serial.println("while loop finished");
delay(1000);
}Example Code Explanation
blinkCountstarts at 0 each timeloop()begins.while (blinkCount < 5)keeps repeating until count reaches 5.- Inside each cycle, LED turns ON then OFF with delay timing.
blinkCount = blinkCount + 1is critical to move toward exit condition.- After 5 cycles, while loop stops, prints completion message, then loop() restarts.
Real-life example
You can use a while loop to retry WiFi connection attempts until success or until a timeout counter reaches a limit.
Common Mistakes with while Loop
- Forgetting to update condition variables inside loop body.
- Using a condition that can never become false.
- Changing the wrong variable, causing logical bugs.
- Placing heavy blocking code inside loop without clear exit reasoning.
Best Practices for while Loop
- Keep condition simple and readable.
- Always ensure something in the loop moves condition toward false.
- Add Serial logs while learning to debug loop state.
- Use safety limits when testing unknown conditions.
- Prefer clear helper flags instead of overly complex while conditions.
Practice Task
- Change the condition to
blinkCount < 3and verify shorter cycle count. - Print both before and after updating
blinkCountto observe flow. - Add a safety counter variable and stop the loop when either condition fails.
- Write one nested while example that prints row and column values.
Try it now
Open simulator workspace and test condition-based repetition with while loop style logic.