Skip to content

[Time] delayMicroseconds() accuracy + Fix ticks per ms value used to compute micros #620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cores/arduino/stm32/clock.c
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ uint32_t getCurrentMicros(void)
/* Ensure COUNTFLAG is reset by reading SysTick control and status register */
LL_SYSTICK_IsActiveCounterFlag();
uint32_t m = HAL_GetTick();
uint32_t u = SysTick->LOAD - SysTick->VAL;
const uint32_t tms = SysTick->LOAD + 1;
__IO uint32_t u = tms - SysTick->VAL;
if (LL_SYSTICK_IsActiveCounterFlag()) {
m = HAL_GetTick();
u = SysTick->LOAD - SysTick->VAL;
u = tms - SysTick->VAL;
}
return (m * 1000 + (u * 1000) / SysTick->LOAD);
return (m * 1000 + (u * 1000) / tms);
}

/**
Expand Down
16 changes: 14 additions & 2 deletions cores/arduino/wiring_time.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,20 @@ static inline void delayMicroseconds(uint32_t us)

while ((int32_t)dwt_getCycles() - start < cycles);
#else
uint32_t start = getCurrentMicros();
while (getCurrentMicros() - start < us);
__IO uint32_t currentTicks = SysTick->VAL;
/* Number of ticks per millisecond */
const uint32_t tickPerMs = SysTick->LOAD + 1;
/* Number of ticks to count */
const uint32_t nbTicks = ((us - ((us > 0) ? 1 : 0)) * tickPerMs) / 1000;
/* Number of elapsed ticks */
uint32_t elapsedTicks = 0;
__IO uint32_t oldTicks = currentTicks;
do {
currentTicks = SysTick->VAL;
elapsedTicks += (oldTicks < currentTicks) ? tickPerMs + oldTicks - currentTicks :
oldTicks - currentTicks;
oldTicks = currentTicks;
} while (nbTicks > elapsedTicks);
#endif
}

Expand Down