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() {
Serial.begin(9600);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop() {
light = analogRead(sensorPin);
Serial.println(light);
while (light < threshold) {
for (int n=8; n<11; n++) {
digitalWrite(n, HIGH);
delay(100);
digitalWrite(n, LOW);
}
light = analogRead(sensorPin);
}
}
About these ads

One response to “Arduino 7: While-loops

  1. in this case
    (While) change to (if) is the same

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s