Chapter 9 · Arduino Practicals and Programming Projects

Practical 2Knight Rider LED Program Using 5 LEDs

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.

LEDArduino pinEach LED path
LED 12Pin → 220 Ω → LED anode; LED cathode → GND rail
LED 23same
LED 34same
LED 45same
LED 56same

Connect the breadboard GND rail to the Arduino GND.

Arduino UNOPin 2Pin 3Pin 4Pin 5Pin 6GND220 Ω eachLED 1 → 5GND rail
Practical 2 circuit (the LEDs show the scanning pattern)

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.

  1. Change delayTime to make the scan faster or slower.
  2. Add a potentiometer on A0 to control the speed with delayTime = map(analogRead(A0), 0, 1023, 20, 300);.
  3. Light two neighbouring LEDs at once to make a wider "beam".
  4. Use PWM pins only (3, 5, 6, 9, 10, 11) and fade the previous LED for a comet tail.

Viva questions

  1. Why is an array useful here?
  2. What is the index of the last LED?
  3. Can all five LEDs share one resistor? Explain.
Show viva answers
  1. One loop can handle every LED instead of repeating code.
  2. 4 (arrays start at 0).
  3. 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.