|
29 | 29 |
|
30 | 30 | #define MIN(x, y) ((x) < (y) ? (x) : (y)) |
31 | 31 |
|
32 | | -#if MICROPY_HW_SYSTEM_TICK_USE_LPTIMER |
| 32 | +#if MICROPY_HW_SYSTEM_TICK_USE_SYSTICK |
| 33 | + |
| 34 | +#include "shared/runtime/softtimer.h" |
| 35 | +#include "pendsv.h" |
| 36 | + |
| 37 | +volatile uint32_t system_tick_ms_counter; |
| 38 | + |
| 39 | +void system_tick_init(void) { |
| 40 | + // Configure SysTick to run at 1kHz (1ms interval) |
| 41 | + SysTick_Config(SystemCoreClock / 1000); |
| 42 | + NVIC_SetPriority(SysTick_IRQn, IRQ_PRI_SYSTEM_TICK); |
| 43 | + NVIC_EnableIRQ(SysTick_IRQn); |
| 44 | +} |
| 45 | + |
| 46 | +void SysTick_Handler(void) { |
| 47 | + uint32_t uw_tick = system_tick_ms_counter + 1; |
| 48 | + system_tick_ms_counter = uw_tick; |
| 49 | + |
| 50 | + // Read the systick control register to clear the COUNTFLAG bit. |
| 51 | + SysTick->CTRL; |
| 52 | + |
| 53 | + if (soft_timer_next == uw_tick) { |
| 54 | + pendsv_schedule_dispatch(PENDSV_DISPATCH_SOFT_TIMER, soft_timer_handler); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +uint32_t system_tick_get_u32(void) { |
| 59 | + return system_tick_get_u64(); |
| 60 | +} |
| 61 | + |
| 62 | +uint64_t system_tick_get_u64(void) { |
| 63 | + mp_uint_t irq_state = disable_irq(); |
| 64 | + uint32_t counter = SysTick->VAL; |
| 65 | + uint32_t milliseconds = system_tick_ms_counter; |
| 66 | + uint32_t status = SysTick->CTRL; |
| 67 | + enable_irq(irq_state); |
| 68 | + |
| 69 | + // It's still possible for the COUNTFLAG bit to get set if the counter was |
| 70 | + // reloaded between reading VAL and reading CTRL. With interrupts disabled |
| 71 | + // it definitely takes less than 50 cycles between reading VAL and |
| 72 | + // reading CTRL, so the test (counter > 50) is to cover the case where VAL |
| 73 | + // is +ve and very close to zero, and the COUNTFLAG bit is also set. |
| 74 | + if ((status & SysTick_CTRL_COUNTFLAG_Msk) && counter > 50) { |
| 75 | + // This means that the HW reloaded VAL between the time we read VAL and the |
| 76 | + // time we read CTRL, which implies that there is an interrupt pending |
| 77 | + // to increment the tick counter. |
| 78 | + milliseconds++; |
| 79 | + } |
| 80 | + uint32_t load = SysTick->LOAD; |
| 81 | + counter = load - counter; // Convert from decrementing to incrementing |
| 82 | + |
| 83 | + // Calculate 64-bit microsecond counter. |
| 84 | + return (uint64_t)milliseconds * 1000ULL + (uint64_t)((counter * 1000) / (load + 1)); |
| 85 | +} |
| 86 | + |
| 87 | +void system_tick_wfe_with_timeout_us(uint32_t timeout_us) { |
| 88 | + if (timeout_us > 1000) { |
| 89 | + // SysTick will wake us in at most 1ms. |
| 90 | + __WFI(); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#elif MICROPY_HW_SYSTEM_TICK_USE_LPTIMER |
33 | 95 |
|
34 | 96 | #include "lptimer.h" |
35 | 97 | #include "sys_ctrl_lptimer.h" |
|
0 commit comments