To blink LEDs in stack form using for loop we first know about “Stack (click) and basic program of LEDs stack pattern (previous topic)“.
Required hardware or components for Lighting up LED in Stack form using Arduino
S.N. | Component | Quantity |
---|---|---|
1. | Arduino Uno | 1 |
2. | Breadboard | 1 |
3. | LED | 4 |
4. | Resistor 220 or 280 ohm | 4 |
CIRCUIT DIAGRAM : BLINK LEDS IN STACK FORM USING FOR LOOP

CONNECTION TABLE
S.N. | Arduino | LED |
---|---|---|
1. | GND | Cathode (-) |
2. | 2 | LED 1 - Anode (+) |
3. | 3 | LED 2 - Anode (+) |
4. | 4 | LED 3 - Anode (+) |
5. | 5 | LED 4 - Anode (+) |
ARDUINO PROGRAMMING CODE : BLINK LEDS IN STACK FORM USING FOR LOOP
int i; void setup() { Â for (i = 2 ; i <= 5; i++) { Â Â Â pinMode(i, OUTPUT); Â } } void loop() { Â for (i = 2; i <= 5 ; i++) { Â Â Â digitalWrite(i, HIGH); Â Â Â delay(500); Â } Â for (i = 5; i >= 2 ; i--) { Â Â Â digitalWrite(i, LOW); Â Â Â delay(500); Â } }
CODE EXPLANATIONÂ
Step-1: We define an integer variable i.
int i;
Step-2: In this block we use a for-loop because we want to do the same work again and again i.e. We want to set the mode of the pin number as output in an order from number 2 to 5. Loop will run 4 times as the loop runs in the first cycle it assigns pin 2 as an output then in the second cycle it assigns pin 3 as an output and same in third cycle pin 4 and in forth cycle pin 5.
void setup() { Â for (i = 2 ; i <= 5; i++) { Â Â Â pinMode(i, OUTPUT); Â } }
Step-3:
In first for-loop we want to set the state of pin number 2, 3, 4 & 5 as HIGH after a delay of 0.5 second next to each other to turn ON led connected on pin number 2, 3, 4 & 5.
In the second for-loop we want to set the state of pin number 5, 4, 3, & 2 as LOW after a delay of 0.5 second next to each other to turn OFF led connected on pin number 5, 4, 3 & 2.
void loop() { Â for (i = 2; i <= 5 ; i++) { Â Â Â digitalWrite(i, HIGH); Â Â Â delay(500); Â } Â for (i = 5; i >= 2 ; i--) { Â Â Â digitalWrite(i, LOW); Â Â Â delay(500); Â } }
And the void loop() gets executed continuously and follows the same pattern.
Now let’s try a new pattern
READ NEXT : BLINK LEDS IN AN ORDER USING ARDUINO
Â