Friday 11 October 2013

Let there be ... Lights? (From Freetronics Project Guide Book)

Here is a sketch that makes a light "scan" along a row of LEDs, very similar to the Kitt scanner in the show Knight Rider or the red Cyclon eye in Battlestar Galaticica.

Here is the sketch:


It is basically the beginner's sketch "Blink", but with  8 LEDs.


// Project II, Controlling 8 LEDs

int ledCount = 8;
int ledPins [] = { 6, 7, 8, 9,  10,  11, 12, 13};
int ledDelay = 100
;

// the setup routine runs once when you press reset:
void setup() {                
 for (int thisLed = 0; thisLed < ledCount; thisLed++) {
   pinMode (ledPins[thisLed], OUTPUT);
 }
}

   
   void loop () {
    for (int thisLed = 0; thisLed < ledCount; thisLed++) {
      digitalWrite (ledPins [thisLed], HIGH) ;
      delay(ledDelay);
      digitalWrite (ledPins [thisLed], LOW) ;
    }
    for (int thisLed = ledCount-1; thisLed > 0; thisLed--)  {
      digitalWrite (ledPins[thisLed], HIGH) ;
      delay(ledDelay);
      digitalWrite (ledPins [thisLed], LOW) ;
      }
    }

In this code, instead of writing the instructions for each LED, we use a 'For' loop, which runs pinMode( ) eight times but with a different value each time.  

The Next part tells the Arduino when to stop the 'For' loop.  This will keep repeating until the conditions are not met, so for this example until the value of 'ledPin' is greater than the value of 'ledCount', so in this case 'ledCount' is 8 so it will keep going up until until ledPin reaches 8.  

The last part is an action that the loop will do each time it runs.  The '++' is a shorthand or quicker way to take a variable (in this case thisLed) and add one to it each time.  


Once the first loop finishes, (in this case thisLed reaches the same value ledCount), the second loop begins.  The second loop is almost identical to the first, but it goes backwards, it starts at the value of 'thisLed' and each time it runs through, it uses the '--' action to decrease the the value of the position by one each time.  

When it reaches the start of the list, the second loop finishes and the program jumps back to the first loop to do it all again.   


Thanks for Reading,

Logan Cox

12044@csc.school.nz or
loggie374@gmail.com  

3 comments:

  1. Excellent work logan! I'm delighted to see that you have used Fritzing to produce a CAD layout of your circuit too.
    Great to see the ++ and -- coding being used to shorten the sketch. I've learned something!
    Thanks.
    Mr Jag

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. if I done this project I will program each LEDS( which will take a great deal of time). You basically shorten your code by half by using arrays for loops and incremental. are you using usb minj-b in your arduino.

      Delete

Note: only a member of this blog may post a comment.