Working code: (with some things to correct but it's up to you)
#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))
uint8_t counter = 0;
const uint8_t numbits = 2;
// struct for LED
struct LED {
uint8_t pin;
uint32_t nextTick;
const uint32_t interval;
};
LED leds[] = {
{6, 0, 1000},
{4, 0, 1000},
};
void setup() {
for (uint8_t cnt = 0; cnt < NUMELEMENTS(leds); cnt++) {
pinMode(leds[cnt].pin, OUTPUT);
leds[cnt].nextTick = millis() + leds[cnt].interval;
}
}
void loop() {
for (uint8_t cnt = 0; cnt < numbits; cnt++) {
if (counter & (1 << cnt)) {
if (millis() > leds[cnt].nextTick) {
leds[cnt].nextTick += leds[cnt].interval;
digitalWrite(leds[cnt].pin, HIGH);
}
} else {
digitalWrite(leds[cnt].pin, LOW);
}
}
counter++;
if (counter == (1 << numbits)) {
counter = 0;
}
delay(100); // Optional: slow things down a bit if needed
}
You had more than one error
First of, at the entry of the for loop, you set cnt to numbits which is equal to
This means that accessing leds[cnt].nextTick is out of range this the array goes from 0 to
The counter++ instruction was in the if (counter & (1 << (cnt - 1))) which is false at the beggining, so you never increment the counter
Another error (that I only partialy corrected, I'll leave you try to solve it) it that you were turning the LED off as soon as you set it to HIGH.
Without my delay(100); you wouldn't be able (no time) to see the leds turn on
Yeah well the code works now
So you can have fun trying to add the necessary instructions to blink without delay
You ask why the counter doesn't work, I explained and gave a solution
But if I also give you the solution to the delay thing then you won't practise anything but your copy paste skill
Everytime you reach the said time saved in leds[cnt].nextTick you set the led to HIGH
You should just change the state of the LED then. If HIGH => LOW and vice versa
Suppose nextTick = 1000 and millis() is just about to approach this value:
millis()
nextTick
LED State
999
1000
LOW
1000
1000
LOW
1001
2000
HIGH
1002
2000
LOW
1003
2000
LOW
...
2000
LOW
2000
2000
LOW
2001
3000
HIGH
2002
3000
LOW
2003
3000
LOW
etc.
So the only thing that determines how long the LED stays lit is how fast the MCU can complete each loop(). When the LED has been turned on (and the value of nextTick incremented), the LED will be turned off in very the next execution of loop().