Aim. To make five LEDs light one after another from left to right and back, like the scanning light on the car in the TV series Knight Rider.
Components. Arduino UNO R3, 5 LEDs, 5 × 220 Ω resistors, breadboard, jumper wires.
Concepts used. Arrays, for loops, multiple outputs.
Wiring.
| LED | Arduino pin | Each LED path |
|---|---|---|
| LED 1 | 2 | Pin → 220 Ω → LED anode; LED cathode → GND rail |
| LED 2 | 3 | same |
| LED 3 | 4 | same |
| LED 4 | 5 | same |
| LED 5 | 6 | same |
Connect the breadboard GND rail to the Arduino GND.
Program.
Arduino C/C++
const int ledPins[] = {2, 3, 4, 5, 6};
const int numLeds = 5;
const int delayTime = 100; // ms
void setup() {
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
// left to right
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], HIGH);
delay(delayTime);
digitalWrite(ledPins[i], LOW);
}
// right to left (skip the two end LEDs so they are not lit twice in a row)
for (int i = numLeds - 2; i > 0; i--) {
digitalWrite(ledPins[i], HIGH);
delay(delayTime);
digitalWrite(ledPins[i], LOW);
}
}How it works. The first loop lights LED 0 to LED 4 in turn. The second loop starts at index 3 and counts down to index 1, so the end LEDs (0 and 4) are not repeated and the motion looks smooth.
Try these changes.
- Change
delayTimeto make the scan faster or slower. - Add a potentiometer on A0 to control the speed with
delayTime = map(analogRead(A0), 0, 1023, 20, 300);. - Light two neighbouring LEDs at once to make a wider "beam".
- Use PWM pins only (3, 5, 6, 9, 10, 11) and fade the previous LED for a comet tail.
Viva questions
- Why is an array useful here?
- What is the index of the last LED?
- Can all five LEDs share one resistor? Explain.
Show viva answers
- One loop can handle every LED instead of repeating code.
- 4 (arrays start at 0).
- Because only one LED is lit at a time in this program, one shared resistor on the common ground would work, but separate resistors are the safe and standard practice, and they are needed if several LEDs light together.