Using loops for the LED examples
In the last example – http://www.mikroblog.net/arduino/arduino-basics/more-arduino-and-led-examples.php we showed you some examples of flashing multiple LEDs, now this code worked OK but there is a more efficient way of doing the same action. We use loops to initialize the LEDs and then again for switching the LEDs on and off. There are 3 different types of loop and we will show the same example for all 3 of them.
Parts List
1 x Arduino UNO
7 x Leds
7 x 220ohm resistors
Schematic
Example 1 : Use a for loop to initialize the pins as outputs and also cycle through the LEDs one at a time from 2 to 8
[codesyntax lang=”cpp”]
#define myDelay 500 void setup() { // initialize the digital pins as outputs: for (int i = 2; i<=8 ; i++) { pinMode(i, OUTPUT); } } void loop() { for (int i = 2; i<=8; i++) { // blink LEDs on pins 2 to 8 digitalWrite(i, HIGH); delay(myDelay); digitalWrite(i, LOW); } }
[/codesyntax]
Example 2 : reverse it, going from 8 to 2
[codesyntax lang=”cpp”]
#define myDelay 500 void setup() { // initialize the digital pins as outputs: for (int i = 2; i<=8 ; i++) { pinMode(i, OUTPUT); } } void loop() { for (int i = 8; i>=2; i--) { // blink from LEDs 8 to 2 digitalWrite(i, HIGH); delay(myDelay); digitalWrite(i, LOW); } }
[/codesyntax]
Example 3 : You can also use a Do While loop, here is the example above again. the concept again is simple we set the variable i to be 8, we then decrement this (subtract) by 1 every time. When i is equal to 2 the loop will exit and start again at 8.
[codesyntax lang=”cpp”]
#define myDelay 500 void setup() { // initialize the digital pins as outputs: for (int i = 2; i<=8 ; i++) { pinMode(i, OUTPUT); } } void loop() { int i = 8; do{ digitalWrite(i, HIGH); delay(myDelay); digitalWrite(i, LOW); i--; }while(i>=2); }
[/codesyntax]
Example 4 : A while loop this time, same concept as above.
[codesyntax lang=”cpp”]
#define myDelay 500 void setup() { // initialize the digital pins as outputs: for (int i = 2; i<=8 ; i++) { pinMode(i, OUTPUT); } } void loop() { int i = 8; while(i>=2) { digitalWrite(i, HIGH); delay(myDelay); digitalWrite(i, LOW); i--; } }
[/codesyntax]