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
Excellent work logan! I'm delighted to see that you have used Fritzing to produce a CAD layout of your circuit too.
ReplyDeleteGreat to see the ++ and -- coding being used to shorten the sketch. I've learned something!
Thanks.
Mr Jag
This comment has been removed by the author.
ReplyDeleteif 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