Bench NotesUno handbook

Arrays for Pins and Patterns

Store pin numbers and timing in arrays to drive five LEDs with a few lines of code.

BeginnerLEDResistor

Overview

An array holds several values of the same type under one name, numbered from 0. Putting pin numbers in an array lets one loop handle any number of LEDs, and the seven-segment projects use a two-dimensional array as a table of patterns.

You will need

  • Arduino Uno R3
  • 5 LEDs
  • 5 × 330 Ω resistors
  • Breadboard

Wiring

Uno pinConnects toNotes
3330 Ω → LED anode
4330 Ω → LED anode
5330 Ω → LED anode
6330 Ω → LED anode
7330 Ω → LED anode
GNDAll LED cathodes
Wiring for Arrays for Pins and PatternsArduino Uno D3 to LED bar LED 1 anode through 330 Ω; Arduino Uno D4 to LED bar LED 2 anode through 330 Ω; Arduino Uno D5 to LED bar LED 3 anode through 330 Ω; Arduino Uno D6 to LED bar LED 4 anode through 330 Ω; Arduino Uno D7 to LED bar LED 5 anode through 330 Ω; Arduino Uno GND to LED bar all cathodes.Connections (each line is one wire)Arduino UnoLED barD3LED 1 anode330 ΩD4LED 2 anode330 ΩD5LED 3 anode330 ΩD6LED 4 anode330 ΩD7LED 5 anode330 ΩGNDall cathodes
Original wiring diagram. Each line is one jumper wire; boxes on a line are series resistors.

The sketch

led_chaser_arrays.ino
const int LED_PINS[] = {3, 4, 5, 6, 7};
const int LED_COUNT = sizeof(LED_PINS) / sizeof(LED_PINS[0]);
const int STEP_MS[] = {60, 90, 120, 90, 60};   // one delay per position

void setup() {
  for (int i = 0; i < LED_COUNT; i++) {
    pinMode(LED_PINS[i], OUTPUT);
  }
}

void loop() {
  // Forwards
  for (int i = 0; i < LED_COUNT; i++) {
    digitalWrite(LED_PINS[i], HIGH);
    delay(STEP_MS[i]);
    digitalWrite(LED_PINS[i], LOW);
  }
  // Backwards, skipping the two ends so they don't flash twice
  for (int i = LED_COUNT - 2; i > 0; i--) {
    digitalWrite(LED_PINS[i], HIGH);
    delay(STEP_MS[i]);
    digitalWrite(LED_PINS[i], LOW);
  }
}

How the code works

sizeof(LED_PINS) / sizeof(LED_PINS[0]) computes the number of elements, so adding a pin to the list needs no other change. C++ does not check array bounds: reading LED_PINS[5] here returns whatever happens to be in memory next, and writing past the end can corrupt other variables.

What you should observe

  • A single light runs back and forth along the five LEDs, slowing in the middle.