From f7530df974e1570a6572ceb40d1b80367fcd6bc6 Mon Sep 17 00:00:00 2001 From: Nicholas Sherlock Date: Fri, 4 Sep 2015 23:44:41 +1200 Subject: [PATCH] Fix 1 millisecond backwards time leap in time measured by micros() This race condition caused periodic flight instability when micros() was called precisely on a 1000 nanosecond boundary. --- src/main/drivers/system.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/drivers/system.c b/src/main/drivers/system.c index 0785250c2..ba4dd6b0a 100644 --- a/src/main/drivers/system.c +++ b/src/main/drivers/system.c @@ -99,6 +99,12 @@ uint32_t micros(void) do { ms = sysTickUptime; cycle_cnt = SysTick->VAL; + + /* + * If the SysTick timer expired during the previous instruction, we need to give it a little time for that + * interrupt to be delivered before we can recheck sysTickUptime: + */ + asm volatile("\tnop\n"); } while (ms != sysTickUptime); return (ms * 1000) + (usTicks * 1000 - cycle_cnt) / usTicks; }