Tutorial 12: For Loop Iteration

Arduino Course for Absolute Beginners

For Loop Iteration

There are few functions so useful that you find them everywhere. The for loop is one of those functions. A for loop repeats an action for a specified number of iterations, reducing the lines of code that need to be written thus making the programmer’s life easier.

In this example, we are setting out to make a row of LEDs light up somewhat similar to Kit in Knight Rider.

If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it.

You Will Need

  1. LED (6)
  2. 220-Ohm Resistor (6)
  3. Jumper Wires (1)
  4. Red Canary (42)

Step-by-Step Instructions

  1. Connect one side of a resistor into pin 2, connect the other side into a row on the breadboard.
  2. Connect the long leg of the LED to the row in the breadboard where you attached the resistor.
  3. Connect the short leg of the LED to one of the power strip columns on your breadboard.
  4. Now connect a resistor to pin 3, and put the other leg in a row on the breadboard (a different one than your first LED).
  5. Connect an LED in the same manner – make sure the short leg goes in the SAME power strip column as the previous LED.
  6. Add LEDs and resistors in this fashion through pin 7.
  7. Using a jumper wire, connect the common power strip to a GND pin on the Arduino.
  8. Connect the Arduino to your computer.
  9. Open up the Arduino IDE.
  10. Open the sketch for this section.
  11. Click the Verify button (top left). The button will turn orange and then blue once finished.
  12. Click the Upload button. The button will turn orange and then blue when finished.
  13. Watch in awe as your LEDs turn on and off in sequence.

For LoopThis image made with Fritzing.

The Arduino Code

/*
  For Loop Iteration

 Demonstrates the use of a for() loop.
 Lights multiple LEDs in sequence, then in reverse.

 The circuit:
 * LEDs from pins 2 through 7 to ground

 created 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/ForLoop
 */

int timer = 100;           // The higher the number, the slower the timing.

void setup() {
  // use a for loop to initialize each pin as an output:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }

  // loop from the highest pin to the lowest:
  for (int thisPin = 7; thisPin >= 2; thisPin--) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }
}

Discuss the Sketch

The first executable code we find in the sketch is the declaration of the timer variable…

int timer = 100;           // The higher the number, the slower the timing.

This integer variable (note the descriptive name) sets the rate the LEDs turn on and off.

Our next friendly block of code is setup(). In this setup() function we run into our first for loop:

void setup() {

for (int thisPin = 2; thisPin < 8; thisPin++) {

pinMode(thisPin, OUTPUT);

}

}

Let’s take a close look at what is inside the parenthesis following the for loop:

void setup() {

for (int thisPin = 2; thisPin < 8; thisPin++) {

pinMode(thisPin, OUTPUT);

}

}

Let’s take a close look at what is inside the parenthesis following the for loop:

for (int thisPin = 2; thisPin < 8; thisPin++)

There are three separate statements in the parenthesis separated by a semicolon. The first statement is initialization of the counter variable used in the for loop, it looks like any other variable declaration and initialization you have seen:

int thisPin = 2;

The thisPin variable is what is used in the next statement – called the test:

thisPin < 8;

This is the test condition that tells the loop to keep going or to stop. If the condition is TRUE, the code in the curly brackets of the for loop will be executed again, if the condition is FALSE, the program will stop executing the statement in the for loop and move forward in the program.

When we first evaluate this test condition, the thisPin variable equals 2 and the test is…

2 < 8

We know that 2 is less than 8, so we execute the code in the curly brackets of the for loop. But before we look at the code in the curly brackets of the for loop let’s finish with the final statement in the parenthesis of the for loop:

thisPin++

The “++” syntax means the same thing as “Add 1 to the value of variable thisPin”. Since “adding the number one” to a value is such a common calculation to perform, the syntax ‘++’ was created to make it even easier. Otherwise you would write:

thisPin = thisPin + 1 //which is the same as thisPin++

On an aside, there is also a shorthand for decrementing a variable by 1:

thisPin- - //this shorthand subtracts the value 1 from thisPin

On yet another aside, you can increment and decrement by any amount using the following shorthand:

thisPin += 42 //the += means “add 42 to the variable on the left” – a handy syntax shortcut

thisPin -=42   //the -= means “subtract 42 to the variable on the left” – another handy syntax shortcut

In most cases for loops increment by the number 1, just keep in mind that you can increment however you choose.

Enough about incrementing! What the heck is the point already? Ok, here is the deal…if the condition of the for loop is met, then code in the curly brackets is executed and the counter variable is incremented. The next time through the for loop, if the condition is still met, then the code once again is executed and the counter variable is incremented again. Eventually your counter variable will grow large enough that the condition will no longer be satisfied and the for loop will end.

for (int thisPin = 2; thisPin < 8; thisPin++) {

pinMode(thisPin, OUTPUT);

}

In this example, when the thisPin variable gets larger than 7, the loop will stop.

For Loop Code Explained

What is awesome about the counter variable is that we usually use it inside the for loop to help do something. In this case, the code that gets executed is:

pinMode(thisPin, OUTPUT);

You are familiar with the pinMode() function – it sets the mode of a pin. Here the number of the pin is specified by the counter variable. So what happens? The first time through the for loop, the thisPin variable is equal to 2. Since 2 is less than 8 (the test condition), we go ahead and execute the code inside the curly brackets:

pinMode(thisPin, OUTPUT);

 (2)                               <<< Pin 2 is set as OUTPUT

After the for loop ends the first time, we increment thisPin (thisPin++) so it now holds the value 3.

Next we check the condition again, and since 3 is indeed less than 8, the code is executed another time:

pinMode(thisPin, OUTPUT);

 (3)                               <<< Pin 3 is set as OUTPUT

After the for loop ends the second time, we increment thisPin as before so it now holds the value 4.   We check the condition – we know 4 is less than 8, and we execute the code in the curly brackets of the for loop again:

pinMode(thisPin, OUTPUT);

 (4)                               <<< Pin 4 is set as OUTPUT

This incrementing and condition testing goes on until thisPin is equal to 8, now the test condition is not met, and the for loop ends – and all of our pins have their mode set.

Seems a bit convoluted perhaps? Consider a for loop vs. what “hard coding” would require:

pinMode(2, OUTPUT);

pinMode(3, OUTPUT);

pinMode(4, OUTPUT);

pinMode(5, OUTPUT);

pinMode(6, OUTPUT);

pinMode(7, OUTPUT);

You can see that the for loop saved us a lot of typing! With a for loop if you decide to add LEDs, all you have to do is change the test condition by simply changing a single number. In the hard coding version you have to add more pinMode() functions to get the same result. Efficiency rocks – stay away from hard coding.

That is a for loop in all its glory. How else can we use for loops?

The next block of code we encounter is the loop() function – notice that the loop() function is like an infinite for loop. In the body of our program we encounter our next for loop:

for (int thisPin = 2; thisPin < 8; thisPin++) {

digitalWrite(thisPin, HIGH);       // turn the pin on:

delay(timer);

digitalWrite(thisPin, LOW);      // turn the pin off:

}

We see that all the code in the parenthesis following the for loop is identical to the previous example. What changes is the code that is executed.   First we use the digitalWrite() function to light up the LED. Recall that digitalWrite() takes two arguments – the pin number and the type of output, either HIGH or LOW.

digitalWrite(thisPin, HIGH);

Here we apply HIGH voltage and the LED turns on. But which LED? The one specified by the counter variable, thisPin. Yes that’s right, the number 2.

Let’s enjoy the bright light for a little bit – the delay() function is handy for this. We delay the length of the timer variable which we set at the beginning of the sketch to the value 100:

delay(timer);

We pause 100 milliseconds and move to the next command:

digitalWrite(thisPin, LOW);

Now write LOW voltage to pin 2, and the LED will turn off.

What do you suspect happens now? Well, our counter variable is incremented and tested again – it will meet the condition, and the same thing will happen again, except now the specified pin will be number 3. This will continue all the way down to pin 7, at which point the condition will not be met and this for loop will end.

But don’t despair, we have another for loop! We are going to reverse the order we blink the LEDs.

for (int thisPin = 7; thisPin >= 2; thisPin--) {

// turn the pin on:

digitalWrite(thisPin, HIGH);

delay(timer);

// turn the pin off:

digitalWrite(thisPin, LOW);

}

Note that we have changed some things in the parenthesis. We initialize the thisPin variable at 7. Our test condition is now “is thisPin greater than or equal to 2?”. Finally, our incrementing subtracts 1 from the value of thisPin every time through the for loop. Now we work backwards down the row, from pin 7 to pin 2, at which point the test condition is not met and this for loop ends.

And then we start back at the top of loop() and repeat it all over. The poor life of a microcontroller – gets a little monotonous I’m afraid. Keep in mind that every time a for loop starts again, it re-declares and re-initializes the counter variable to the value you specify.

This is a good time to introduce the concept of variable scope. The scope of a variable refers to where the variable can be used within a program. The variables that we declare at the top of the program, before setup() and loop(), have global scope – they can be used anywhere in the program. But the variable declared in the parenthesis of a for loop, can only be used inside that for loop.

More discussion of variable scope can be found in the Further Reading suggestions.

Try On Your Own Challenge

  • Adjust the value of the timer variable.
    Add additional LEDs at pin 8 and 9. Adjust all three for loop statements accordingly.

Further Reading

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code