If I have 5 LEDs and I use GPIOs 5-9, I can turn them on and off just like a Blink sketch, but with five of them. Or I can use for loop such as:
for(int i=5; i<10; i++){
digitalWrite(i, HIGH);
}
But what if I use pins 4, 5, 9, 10, 13, or 10, 6, 7, 13, 2? My guess is it must be in an array. Not sure how to achieve it.
PaulRB
2
const byte ledPins[5] = {4, 5, 9, 10, 13};
...
for(int i=0; i<sizeof(ledPins)/sizeof(ledPins[0]); i++){
digitalWrite(ledPins[i], HIGH);
}
Hello who_took_my_nick
either
constexpr byte LedPins[] {4,5,9,10,13};
or
constexpr byte LedPins[] {10,6,7,13,2};
You can access the array by using an index from 0 to 4.
Or using the range based loop
for (auto Led:LedPins) digitalWrite(Led,HIGH);
PaulRB
6
I'm embarrassed. If I had scrolled to the right I would have seen the list of pin numbers, which is different!
I just tried this:
const byte rlyPins[8] = {2, 3, 4, 5, 13, 8, 7, 6};
void setup() {
for(int i=0; i<sizeof(rlyPins)/sizeof(rlyPins[0]); i++){
pinMode(rlyPins[i], OUTPUT);
digitalWrite(rlyPins[i], LOW);
}
}
void loop() {
for(int i=0; i<sizeof(rlyPins)/sizeof(rlyPins[0]); i++){
digitalWrite(rlyPins[i], HIGH);
delay(100);
}
for(int i=0; i<sizeof(rlyPins)/sizeof(rlyPins[0]); i++){
digitalWrite(rlyPins[i], LOW);
delay(100);
}
}
and it worked just fine.
Another one.
Say, I want to limit the first 6 LEDs to blink. I should add -2 in for loop?
for(int i=0; i<sizeof(rlyPins)/sizeof(rlyPins[0])-2; i++){
digitalWrite(rlyPins[i], LOW);
delay(100);
}
Actually, it is:
for(int i=0; i<(sizeof(rlyPins)/sizeof(rlyPins[0]))-2; i++){
digitalWrite(rlyPins[i], LOW);
delay(100);
}
And it works.
Thank you, guys.
Have a nice day and enjoy.