Can I use a loop variable value to turn on/off LEDs?

Using digitalWrite(led1, LOW);, can I use a variable in place of the β€œ1” to turn LEDs on/off?

Thanks

No, you can’t use a variable in place of the β€œ1”, but you can put the pin numbers into an array, and use them in a loop.

int leds[] = {D0,D1,D2,D3,D4,D5,D6,D7};

void loop() {
    for (int i=0; i<8; i++) {
        digitalWrite(leds[i], HIGH);
        delay(200);
    }
    
    for (int i=0; i<8; i++) {
        digitalWrite(leds[i], LOW);
        delay(200);
    }
}

Technically, you don’t really need the array since D0=0, D1=1 etc. (so digitalWrite(i, HIGH) would work), but I think the code is safer and more clear if you do it the way I showed with the array.

4 Likes

Ah, thanks.