The For Loop

In this lesson you'll be learning about the "for" command. Full details on this command can be found on page 21 of the Arduino Programming guide. The "for" command is kind of like a loop. It will keep repeating what ever is in the brackets as long as the "condition" is true. You'll need to set up your circuit so that you have an LED (with appropriate resistors) plugged into pins digital pins 8-13.
 

The "for" process above will light up each pin starting at 13 and counting down to 8 in sequence, turning it off before it lights the next one.

The basic structure of "for" is as follows:
 Initialize the Process
 Set the Condition
 Expression
 int ledPin=13
 ledPin >= 8
 ledPin = ledPin - 1

All for loops will have an integer variable associated with them. I chose to use ledPin as the variable name since we'll be lighting an LED. The process runs as a loop. Each time through, it checks to see if the condition is still true. For our loop, is ledPin greater than or equal to 8? If true the loop and Expression are completed. For our loop, the value of ledPin will be decreased by 1 each time through, which will cause the next LED to light up.

When ledPin is decreased to 7 the condition is no longer true and the process stops. Overall, this is much easier than doing a digitalWrite for each pin individually as you did in the last lesson.

The full sketch is listed below:

 /*
 * Sequence Pins
 * This skecth will sequentially set pins 8-13 digital pins to high.
 * It will then set the pin to low and continue to the next pin.
 * It serves as an introduction to the for command.
 */

void setup()               // run once, when the sketch starts
{                               // even though there's nothing in it
}                               // we still need this process

void loop()                // run over and over again
{
  for (int ledPin = 13; ledPin >= 8; ledPin = ledPin-1)   // Declares ledPin,
 {                                // tests if equal to or greater than 8
                                  // then does the following. It repeats
                                  // but decreases the value of ledPin by 1
    pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    digitalWrite(ledPin, HIGH);       // sets the LED-ledPin on
    delay(100);                             // waits for a tenth of a second
    digitalWrite(ledPin, LOW);        // sets the LED-ledPin off
 }  
}


Additional Tasks:
  1. Once you've gotten this working see if you can add a few more leds.
  2. Make it go there and back again.
One more thing
There is another, probably better way, to write the expression "ledPin = ledPin - 1"

 ledPin = ledPin - 1
 ledPin--
 ledPin = ledPin + 1
 ledPin++

Change your program with these expressions and see what happens.
Comments