arduino / arduino/ArduinoCore-avr

millis() fails to increment when interrupts are disabled. [imported]

Open
#232 1 comment 0 reactions 1 assignee Claimed by @cmaglie View on GitHub
Dominant language
C
Stars
1.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

This is [Issue 187](http://code.google.com/p/arduino/issues/detail?id=187) moved from a Google Code project.
Added by 2010-01-15T23:00:14.000Z by [Michael....@gmail.com](http://code.google.com/u/116251759589842234567/).
Please review that bug for more context and additional comments, but update this bug.

Original labels: Type-Defect, Priority-Medium, Component-Core
### Original description

When IRQs are disabled at the time when timer0 overflows, micros() will
return wrong results.

**What steps will reproduce the problem?**
1. call t1=micros() just before a overflow of timer0
2. disable IRQ
3. wait after overflow of timer0 and after TCNT0 > 0
4. call t2=micros()
5. enable IRQ
6. call t3=micros()

now t2 is smaller than t1 because the ISR TIMER0_OVF_vect in wiring.c has
not been called and the overflow handling in micros() is wrong:

wrong, because it only works when t==0:
if ((TIFR0 & _BV(TOV0)) && (t == 0))
t = 256;

much better, but doesn't handle longer times with disabled IRQs:
if (TIFR0 & _BV(TOV0))
t += 256;

best: see attachment of patch

What is the expected output?
t1=2010104
t2=2010116
t3=2010124
ovl1=0 ovl2=1 novl2=0
t2-t1=12 t3-t1=20 t3-t2=8

What do you see instead?
t1=2010104
t2=2009092
t3=2010124
ovl1=0 ovl2=1 novl2=1
t2-t1=-1012 t3-t1=20 t3-t2=1032

**What version of the Arduino software are you using? On what operating**
**system? Which Arduino board are you using?**
I'm using Arduino-17 with Windows XP+SP3 and Arduino Duemilanove-328.

**Please provide any additional information below.**
The attachment "[MicrosTimerOverflowTest.pde](http://storage.googleapis.com/google-code-attachments/arduino/issue-187/comment-4/MicrosTimerOverflowTest.pde)" contains a test case which
reproduces the problem. t2 must always be greater than t1.

The patch "[wiring.patch](http://storage.googleapis.com/google-code-attachments/arduino/issue-187/comment-3/wiring3.patch)" contains a fix which corrects the problem and also
solves the missing timer overflows problem when IRQs are disabled for a
longer time, as long as micros() is called at least once between two timer
overflows (around 1 microsecond on a ATmega 16Mhz).

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.