An Array of LED Pins
Part of the Outputs section of Coddy's Arduino journey. Lesson 16 of 24.
An array can hold pin numbers as well as notes. With five LEDs, one array names them all:
int ledPins[] = {2, 3, 4, 5, 6};A for loop then visits every pin in turn, so five pinMode() lines become one:
for (int i = 0; i < 5; i++) {
pinMode(ledPins[i], OUTPUT);
}Keep i and ledPins[i] apart. i is the position in the array, 0 to 4. ledPins[i] is the pin number stored there, 2 to 6. The pin functions need the pin number.
The order of the array is the order the loop visits the pins. To rewire an LED to another pin, change one number in the array and every loop follows.
Challenge
EasyFive LEDs are on pins 2 to 6. In setup():
- make every pin in
ledPinsan output with a for loop - with a second for loop, turn the LEDs on one after another, in the order of the array, waiting 200 ms after each
All five stay on at the end. Press Run, then Check.
Try it yourself
int ledPins[] = {2, 3, 4, 5, 6};
void setup() {
// make every pin in ledPins an output with a for loop
// then turn the LEDs on one after another, 200 ms apart
}
void loop() {
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
4Loops and Arrays
Repeat With a for LoopAn Array of LED PinsFive-LED ChaserKnob Bar GraphBinary Counter on LEDsPractice on your own: Arduino playground