Home > Arduino, Programming, Tutorial > for Loop

for Loop

I’m going to do a quick run though the “for” loop, using a part of this guide as a foundation.

Using the Arduino.cc explanation here you can get a basic understanding of how it works.

The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.

There are three parts to the for loop header:

for (initialization; condition; increment) {
    //statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it’s true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.

So now that you have a basic understanding of the for loop, lets see how we can apply it…

I will use my own version of the original example sketch from tronixstuff to illustrate how the for loop functions.

Click here for Pastebin with syntax highlighting for the following code.

void setup(){
    pinMode(9, OUTPUT);
}
void loop(){
    for (int x = 1; x <= 5; x++){
        digitalWrite(9, HIGH);
        delay(1000);
        digitalWrite(9, LOW);
        delay(1000);
    }
    delay(10000);
}

Here’s whats actually happening in the for loop in human language:

    for (set x equal to 1; is x less than or equal to 5?; increase x by 1){
        set pin 9 high;
        wait one second;
        set pin 9 low;
        wait one second;
    }
    wait 10 seconds;

The steps taken in our loop are;

  1. a variable “x” is set to equal to 1, this is done once
  2. a test is done to check if x is equal to or less than 5
  3. if the test is passed, the statements inside the braces are acted upon
  4. x is set to equal x + 1
  5. steps 2 through 4 are done until the test fails, in which case the loop is terminated

The physical result of the sketch – if you have an LED hooked up to pin 9 of the Arduino – will be that the LED will blink 5 times, wait 10 seconds, blink 5 times… and so on, for infinity.

That’s pretty much it. You can do more complicated things with the for loop, but the fundamentals can be summarized to: initialize, test, incrament/decrement.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: