Learning   Examples | Foundations | Hacking | Links

Examples > Control Structures

While Loop

Sometimes you want everything in the program to stop while a given condition is true. You can do this using a while loop. This example shows how to use a while loop to calibrate the value of an analog sensor.

In the main loop, the sketch below reads the value of a photoresistor on analog pin 0 and uses it to fade an LED on pin 9. But while a button attached to digital pin 2 is pressed, the program runs a method called calibrate() that looks for the highest and lowest values of the analog sensor. When you release the button, the sketch continues with the main loop.

This technique lets you update the maximum and minimum values for the photoresistor when the lighting conditions change.

Circuit

Analog sensor (e.g. potentiometer, light sensor) on analog input 2. LED on digital pin 9.

click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic:

click the image to enlarge

Code

((:div class=code :)