IF Loop

Let's say you want to sequence LEDs, that is to say turn them on and off one at a time, but you're lazy. In your last program there was a lot of repetition. As it turns out, computers are great at repetition. They can do the same thing over and over again while each time changing one thing. Create a circuit with LEDs in pins 9-13.

Now we will let our Arduino do the hard work for us. The Arduino really is a computer, so we'll let it do some repetitive calculations.

 ledPin=ledPin-1; 

This line of code does just what it appears to say. This line of code can appear confusing if you think about it in the math sense, but this is not an algebraic expression. In plane english this says, "Set the new value of ledPin to be the old value of ledPin minus one." The Arduino is only capable of simple arithmetic. If you want it to do algebra you'll have to program it to do it.

So with "ledPin=ledPin-1" in our program the value of ledPin will decrease by one each time through the void loop(). After a few times through it will be lower than our lowest pin and in fact will eventually be a negative number unless we do something about it!

Video Links: On Blip or on YouTube

  if (ledPin<9)  
  {
    ledPin=13;  
  }

The statement above asks a question. It asks, "Is the value of ledPin less than nine?" there are two possible answers to this question, yes or no. The Arduino thinks of these as True or False. If the statement is false the program will skip whatever is in the curly brackets and continue on. However, if the statement is true it will execute the code in the brackets and then continue on. So, in our case if the value of ledPin gets too small we will re-set the value of ledPin to 13.

/*
This code demonstrates the power of repetition introducing
if statements. You'll note there is no code in our setup process the
pins are declared as needed in the loop.

The circuit should have resistor-LEDs on pins 9-13.

created 5 September 2010
by Steve Dickie
electronics.arduinoeducation.com
*/

int ledPin = 13;

void setup()
{
}

void loop()
{
  pinMode (ledPin, OUTPUT);      //Set current pin to light-up as an output
  digitalWrite (ledPin, HIGH);   //Light up the current pin
  delay(100);                    //Wait long enough for us to see it
  digitalWrite (ledPin, LOW);    //Turn the LED off
  ledPin=ledPin-1;               //Advance to the next pin
  if (ledPin<9)                  //Check to see if we went past the last LED 
  {
    ledPin=13;                   //Reset ledPin to start over
  }
}


After you complete the program above. 
  1. Add a few more LEDs and change the program to make it work.
  2. Reverse the sequence to make it go the other way.
Comments