Category Archives: while loops

Arduino 7: While-loops

You often want to perform a set of code only while a certain condition is true. If the code is just a line or two, you can use an if-statement to handle it. However when a condition is driving most of the program, and you want a lot of code to depend on it, a while-loop is a conditional structure that’s easier to read.

while (condition) {…}

will repeat all the code in the curly braces as long as the logical condition is true. Usually this condition tests the state of a variable, so you need to update the state of the variable somewhere inside the curly braces for the condition check to work. However you also need to think about what happens when the condition fails. Then the code in the braces won’t run – but since the whole procedure keeps looping, presumably you still want to check the condition, because the condition might occur again. So remember to also update the state of the variable in the code outside the curly braces as well.

This sample program will flash LED’s on pins 8, 9 and 10 (each on a 220-ohm resistor to ground) as long as a light sensor (on analog pin 0) reads an input below some value in threshold, but turns them off when the room light is too bright. There’s also code to print out the output of the light sensor, since you need to tune the value of the variable threshold to fit your lighting conditions.

int light=0;
int sensorPin = 0;
int threshold = 100;
void setup() {
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
void loop() {
light = analogRead(sensorPin);
while (light < threshold) {
for (int n=8; n<11; n++) {
digitalWrite(n, HIGH);
digitalWrite(n, LOW);
light = analogRead(sensorPin);