itsanjan / arduino

Automatically exported from code.google.com/p/arduino
Other
0 stars 0 forks source link

Bug in micros() #592

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
The current implementation of micros() is based on the assumption that timer0 
overflows at 0. Fast PWM mode however overflows at 255 and so micros() may 
return an incorrect value. The two issues are as follows:

1: TCNT0 is at 254 and overflows when inside micros()
micros() returns a value one overflow count high

2: Overflow is processed, but TCNT0 is still at 255 when micros() is called
micros() returns a value one overflow count high

The following is a simple fix for both issues (increment t prior to testing):

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

    t++;

#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());
}

Original issue reported on code.google.com by bflag...@gmail.com on 23 Aug 2011 at 9:07

GoogleCodeExporter commented 9 years ago
I ran some additional tests on this issue and found that the current (022) 
implementation is correct. 

More detail is available in the following thread:

http://arduino.cc/forum/index.php/topic,70045.0.html

Original comment by bflag...@gmail.com on 10 Sep 2011 at 3:28

GoogleCodeExporter commented 9 years ago
Cool.  Thanks for investigating.

Original comment by dmel...@gmail.com on 10 Sep 2011 at 6:06