Skip to content

Commit d2db949

Browse files
committed
[Time] delayMicroseconds() accuracy
delayMicroseconds() should not rely to getCurrentMicros() and should only compute required ticks for the delay requested. This allow to use it even if interrupts are disabled. Example for OneWire library. Fixes #412 Signed-off-by: Frederic Pillon <[email protected]>
1 parent dfaace5 commit d2db949

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

cores/arduino/wiring_time.h

+14-2
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,20 @@ static inline void delayMicroseconds(uint32_t us)
6969

7070
while ((int32_t)dwt_getCycles() - start < cycles);
7171
#else
72-
uint32_t start = getCurrentMicros();
73-
while (getCurrentMicros() - start < us);
72+
__IO uint32_t currentTicks = SysTick->VAL;
73+
/* Number of ticks per millisecond */
74+
const uint32_t tickPerMs = SysTick->LOAD + 1;
75+
/* Number of ticks to count */
76+
const uint32_t nbTicks = ((us - ((us > 0) ? 1 : 0)) * tickPerMs) / 1000;
77+
/* Number of elapsed ticks */
78+
uint32_t elapsedTicks = 0;
79+
__IO uint32_t oldTicks = currentTicks;
80+
do {
81+
currentTicks = SysTick->VAL;
82+
elapsedTicks += (oldTicks < currentTicks) ? tickPerMs + oldTicks - currentTicks :
83+
oldTicks - currentTicks;
84+
oldTicks = currentTicks;
85+
} while (nbTicks > elapsedTicks);
7486
#endif
7587
}
7688

0 commit comments

Comments
 (0)