Arduino Program for LED Chaser with Example Code
for loop to turn on LEDs one by one with digitalWrite(pin, HIGH) and then off with digitalWrite(pin, LOW), adding delay() between steps for the LED chaser effect.Examples
How to Think About It
Algorithm
Code
const int ledPins[] = {2, 3, 4, 5, 6}; const int numLeds = 5; void setup() { for (int i = 0; i < numLeds; i++) { pinMode(ledPins[i], OUTPUT); } Serial.begin(9600); } void loop() { for (int i = 0; i < numLeds; i++) { digitalWrite(ledPins[i], HIGH); Serial.print("LED "); Serial.print(i); Serial.println(" ON"); delay(200); digitalWrite(ledPins[i], LOW); } }
Dry Run
Let's trace the LED chaser with 5 LEDs connected to pins 2 to 6.
Setup pins
Pins 2,3,4,5,6 set as OUTPUT
Loop start
Start looping over LEDs from index 0 to 4
Turn on LED 0
digitalWrite(pin 2, HIGH), print 'LED 0 ON', delay 200ms
Turn off LED 0
digitalWrite(pin 2, LOW)
Repeat for LEDs 1 to 4
Same steps for pins 3,4,5,6 with indexes 1 to 4
| LED Index | Pin | State | Serial Output |
|---|---|---|---|
| 0 | 2 | ON | LED 0 ON |
| 0 | 2 | OFF | |
| 1 | 3 | ON | LED 1 ON |
| 1 | 3 | OFF | |
| 2 | 4 | ON | LED 2 ON |
| 2 | 4 | OFF | |
| 3 | 5 | ON | LED 3 ON |
| 3 | 5 | OFF | |
| 4 | 6 | ON | LED 4 ON |
| 4 | 6 | OFF |
Why This Works
Step 1: Set pins as output
We use pinMode to tell Arduino these pins will control LEDs.
Step 2: Turn LEDs on and off in sequence
The for loop goes through each LED pin, turning it on with digitalWrite(pin, HIGH), then off with digitalWrite(pin, LOW).
Step 3: Add delay for visible effect
The delay(200) pauses the program so the LED stays lit long enough to see the chasing effect.
Alternative Approaches
const int ledPins[] = {2, 3, 4, 5, 6}; const int numLeds = 5; void setup() { for (int i = 0; i < numLeds; i++) pinMode(ledPins[i], OUTPUT); } void loop() { for (int i = 0; i < numLeds; i++) { for (int j = 0; j < numLeds; j++) { digitalWrite(ledPins[j], j == i ? HIGH : LOW); } delay(200); } }
const int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); }
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through each LED once per cycle, so time grows linearly with the number of LEDs.
Space Complexity
Uses an array to store LED pins, so space grows linearly with the number of LEDs.
Which Approach is Fastest?
Both main and alternative methods run in O(n) time; the main method is simpler and easier to read.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple for loop | O(n) | O(n) | Easy to understand and implement |
| Nested loop with conditional | O(n^2) | O(n) | Clear LED on/off control but less efficient |
| Single LED blink | O(1) | O(1) | Only one LED, no chasing effect |
pinMode causes LEDs not to light up.