Hi all
I have a very specific question about the Arduino micros() function.
Only purpose is to understand and learn, so I do NOT have a practical issue.
But I hope someone will be able to enlighten me.
The function (which I found on a forum):
unsigned long micros() {
unsigned long m;
uint8_t oldSREG = SREG, t;
cli();
m = timer0_overflow_count;
#if defined(TCNT0)
t = TCNT0;
#elif defined(TCNT0L)
t = TCNT0L;
#else
#error TIMER 0 not defined
#endif
#ifdef TIFR0
if ((TIFR0 & _BV(TOV0)) && (t & 255))
m++;
#else
if ((TIFR & _BV(TOV0)) && (t & 255))
m++;
#endif
SREG = oldSREG;
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}
Introduction to my question:
nearly at the end of the function, flag TOV0 is checked to see whether there is a pending overflow interrupt.
IF yes, then this indicates that the software counter 'timer0_overflow_count' has not been updated yet by the Interrupt handler (interrupts are temporarily blocked by the micros() function) and we need to take care of that by adding one to variable 'm' (pending the update of 'timer0_overflow_count' which will happen immediately upon re-enabling interrupts).
So, 'm' will correctly contain the number of Timer 0 overflows (each overflow represents 1024 micro seconds, to be added to the number of micros read directly from Timer zero).
Up to this point, all is fine.
My question:
Why does the if clause if ((TIFR0 & _BV(TOV0)) && (t & 255)) check for a non-zero value of the timer reading ? (t & 255)
As I see it (although I guess I'm missing something) this is wrong, even if 't' would be zero, the fact that TOV0 is set would still mean the last update of 'timer0_overflow_count' is pending.
Can someone explain this to me ? I would sleep a lot better ![]()
As said, it's just about understanding it. I have no practical issue.
Many thanks
