While Loops: Usage

Home

While Loops

Description from the Arduino reference

while loops will loop continuously, and infinitely, until the condition inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor.

Syntax

while(condition){
  // statement(s)
}

Parameters

condition - a (boolean) C statement that evaluates to true or false

Example

int pin = 2;  // initialize pin
while(pin < 16) {  // condition of while loop
  pinMode(pin, OUTPUT);
  pin = pin + 1;  // increment pin by 1
}

Important: If you have a semicolon ; after the while statement, it ignores the body of the loop and keeps checking the condition over and over forever.  This is called an infinite loop.  This also can happen if you forget to increment the loop variable (such as pin in the example) so that the condition is always true.

You may also watch Arduino: Your First While Loop

Check Your Understanding

The while loop runs forever until the in the () becomes .

Changing the loop variable (such as pin in the example) is called it.  If you forget to do this, or have a semicolon after the while statement, you may get a(n) .