This is an academic question: I've been reading how the timer is implemented here.
- timer ticks every 1.024ms, and fraction handling is done in handler
- milli() disables interrupts to read timer0_millis
For bullet 1, can't we set the counter's overflow to be 250 instead of 256?
For bullet 2, can't we avoid the cli() and implement atomicity by switching between two stores for milli?
The following code would work and be atomic IF the timer_0_data array is aligned so that ONLY the low byte of the address is different. Maybe a compiler macro can enforce alignment.
The down side of this implementation is it uses 1 pointer and two longs instead of two longs and a char.
volatile long timer0_data[2];
volatile long *timer0_milli=timer0_data[0];
SIGNAL(TIMER0_OVF_vect)
{
long old_time = *timer0_milli;
// Swap pointer
timer0_milli = (timer0_milli == &timer0_data[0])? &timer0_data[1] : &timer0_data[0];
*timer0_milli = old_time+1;
}
unsigned long millis() {
return *timer0_millis;
}