jung6717 / arduino

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

Incorrect check for timer 0 overflow in micros() #55

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1247079375

"so far as i understand the code "if ((TIFR0 & _BV(TOV0)) && (t == 0))" checks 
for overflow the 
counter after disabling interrupts - if set bit TOV0 in register TIFR0 than 
occurred overflow but I 
don't understand what for second condition "t == 0" ? I see possible problem 
with it - if while 
executing code between cli() and sei() TCNT0 will be incremented after overflow 
it will have value 
more than zero, and when will be enabled interrupts firstly will run Handler(). 
In Handler() code will 
be called micros() func but it can return wrong result because TCNT0 can have 
value more than zero 
although TOV0 bit will be set. I think this problem can be solved by changing 
code of micros():"

Original issue reported on code.google.com by dmel...@gmail.com on 14 Jul 2009 at 9:25

GoogleCodeExporter commented 9 years ago
unsigned long micros() {
         unsigned long m;
         uint8_t oldSREG = SREG, t;

         cli();  
         m = timer0_overflow_count;
         t = TCNT0;

 #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 comment by dmel...@gmail.com on 15 Aug 2009 at 8:51

GoogleCodeExporter commented 9 years ago
I've hit this bug in my code when calling micros from an ISR.  Since interrupts 
have
been disabled awhile inside the ISR, it is possible that TOV0 is set and TCNT0 
has
been incremented past 0 (since interrupts have been disabled for far longer 
than the
cli() call within micros).  In this case, the micros call returns a value that 
is
~1msec less than the previous call; confusing timings from one call to the next.

I had made a similar fix that solved the problem for me.

I encourage the powers to be to include this fix in the next release.

Original comment by dangyogi@gmail.com on 18 Sep 2009 at 1:33

GoogleCodeExporter commented 9 years ago

Original comment by dmel...@gmail.com on 18 Dec 2009 at 5:44