Skip to content

Commit

Permalink
Shorten critical section in micros()
Browse files Browse the repository at this point in the history
The timer registers have to be read with interrupts disabled. All other
computations can be done after interrupts have been enabled again.
  • Loading branch information
edgar-bonet committed Jan 19, 2024
1 parent 6309212 commit 7b7d61d
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions cores/arduino/wiring.c
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ unsigned long millis()

unsigned long micros() {
unsigned long m;
uint8_t oldSREG = SREG, t;
uint8_t oldSREG = SREG, t, flags;

cli();
m = timer0_overflow_count;
Expand All @@ -91,14 +91,15 @@ unsigned long micros() {
#endif

#ifdef TIFR0
if ((TIFR0 & _BV(TOV0)) && (t < 255))
m++;
flags = TIFR0;
#else
if ((TIFR & _BV(TOV0)) && (t < 255))
m++;
flags = TIFR;
#endif

SREG = oldSREG;

if ((flags & _BV(TOV0)) && (t < 255))
m++;

return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}
Expand Down

0 comments on commit 7b7d61d

Please sign in to comment.