I thought the code below would toggle an LED every 500 milliseconds. But it does not work. I'm not able to catch the mistake, which must be very silly.
void setup() {
pinMode(3, OUTPUT);
}
void loop() {
unsigned long cnt=millis();
if(!(cnt % 500)) {
PORTD^= (1<<PD3);
}
}
Anyhow the code below works. But why not the previous code?
void loop() {
static unsigned long prev=0;
// Note: First time case is not handled. As soon as we want to toggle,
// we must store millis() in prev. In this case this happens after reset and may not be an issue.
unsigned long current = millis();
if((unsigned long)(current - prev) >= 500) {
PORTD^= (1<<PD3);
prev = current;
}
}
if( !(cnt % 500) )
is equivalent toif( (cnt % 500) != 0 )
, which is true for 499 values and false for only one. The "!" creates the opposite effect to what was wanted.