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 pin | Connects to | Notes |
|---|---|---|
| 3 | 330 Ω → LED anode | |
| 4 | 330 Ω → LED anode | |
| 5 | 330 Ω → LED anode | |
| 6 | 330 Ω → LED anode | |
| 7 | 330 Ω → LED anode | |
| GND | All LED cathodes |
The sketch
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.