Pin arrays in Arduino
An array of pins turns repeated setup into a loop.
// An array of pins turns eight lines of setup into a loop.
const int STAGE_PINS[] = {3, 5, 6, 9};
const int STAGE_COUNT = 4;
void setup() {
for (int i = 0; i < STAGE_COUNT; i++) {
pinMode(STAGE_PINS[i], OUTPUT);
}
}
void loop() {
// Chase pattern: one stage light at a time.
for (int i = 0; i < STAGE_COUNT; i++) {
digitalWrite(STAGE_PINS[i], HIGH);
delay(150);
digitalWrite(STAGE_PINS[i], LOW);
}
}
How it works
STAGE_PINS[]lists the outputs; one for sets them all up.- The chase loop indexes the array in order.
- Adding a stage light is one number, not four lines.
Keywords and builtins used here
HIGHLOWOUTPUTconstdelaydigitalWriteforintlooppinModesetupvoid
The run, in numbers
- Lines
- 18
- Characters to type
- 402
- Tokens
- 105
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 97 seconds.
Step 2 of 3 in Functions & state, step 17 of 27 in Language basics.