Control Structure

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

  1. Check condition before running the loop body.
  2. If true, execute the body.
  3. Update values inside the loop so condition can eventually change.
  4. Check condition again and repeat.
  5. 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.

CheckblinkCountCondition blinkCount < 5
Start0true (run)
After 1st update1true (run)
After 4th update4true (run)
After 5th update5false (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 for when count/steps are known in advance.
  • Use while when 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

  1. blinkCount starts at 0 each time loop() begins.
  2. while (blinkCount < 5) keeps repeating until count reaches 5.
  3. Inside each cycle, LED turns ON then OFF with delay timing.
  4. blinkCount = blinkCount + 1 is critical to move toward exit condition.
  5. 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

  1. Change the condition to blinkCount < 3 and verify shorter cycle count.
  2. Print both before and after updating blinkCount to observe flow.
  3. Add a safety counter variable and stop the loop when either condition fails.
  4. 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.

Run in Simulator