From 7b7d61dfbfcfbde06d60aef49e6d360e874beb1e Mon Sep 17 00:00:00 2001 From: Edgar Bonet Date: Fri, 19 Jan 2024 22:34:58 +0100 Subject: [PATCH] Shorten critical section in micros() The timer registers have to be read with interrupts disabled. All other computations can be done after interrupts have been enabled again. --- cores/arduino/wiring.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cores/arduino/wiring.c b/cores/arduino/wiring.c index 8caf45521..5d663c864 100644 --- a/cores/arduino/wiring.c +++ b/cores/arduino/wiring.c @@ -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; @@ -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()); }