summaryrefslogtreecommitdiffstatshomepage
path: root/stmhal/systick.c
diff options
context:
space:
mode:
Diffstat (limited to 'stmhal/systick.c')
-rw-r--r--stmhal/systick.c36
1 files changed, 36 insertions, 0 deletions
diff --git a/stmhal/systick.c b/stmhal/systick.c
index 196f1fbcae..660b777fc0 100644
--- a/stmhal/systick.c
+++ b/stmhal/systick.c
@@ -27,6 +27,10 @@
#include <stm32f4xx_hal.h>
#include "mpconfig.h"
#include "misc.h"
+#include "nlr.h"
+#include "qstr.h"
+#include "obj.h"
+#include "irq.h"
#include "systick.h"
bool sys_tick_has_passed(uint32_t start_tick, uint32_t delay_ms) {
@@ -41,3 +45,35 @@ void sys_tick_wait_at_least(uint32_t start_tick, uint32_t delay_ms) {
__WFI(); // enter sleep mode, waiting for interrupt
}
}
+
+// The SysTick timer counts down at 168 MHz, so we can use that knowledge
+// to grab a microsecond counter.
+//
+// We assume that HAL_GetTickis returns milliseconds.
+uint32_t sys_tick_get_microseconds(void) {
+ mp_int_t enabled = disable_irq();
+ uint32_t counter = SysTick->VAL;
+ uint32_t milliseconds = HAL_GetTick();
+ uint32_t status = SysTick->CTRL;
+ enable_irq(enabled);
+
+ // It's still possible for the countflag bit to get set if the counter was
+ // reloaded between reading VAL and reading CTRL. With interrupts disabled
+ // it definitely takes less than 50 HCLK cycles between reading VAL and
+ // reading CTRL, so the test (counter > 50) is to cover the case where VAL
+ // is +ve and very close to zero, and the COUNTFLAG bit is also set.
+ if ((status & SysTick_CTRL_COUNTFLAG_Msk) && counter > 50) {
+ // This means that the HW reloaded VAL between the time we read VAL and the
+ // time we read CTRL, which implies that there is an interrupt pending
+ // to increment the tick counter.
+ milliseconds++;
+ }
+ uint32_t load = SysTick->LOAD;
+ counter = load - counter; // Convert from decrementing to incrementing
+
+ // ((load + 1) / 1000) is the number of counts per microsecond.
+ //
+ // counter / ((load + 1) / 1000) scales from the systick clock to microseconds
+ // and is the same thing as (counter * 1000) / (load + 1)
+ return milliseconds * 1000 + (counter * 1000) / (load + 1);
+}