Loading...
Searching...
No Matches
furi_hal_idle_timer.h
1#pragma once
2
3#include <stm32wbxx_ll_lptim.h>
4#include <stm32wbxx_ll_rcc.h>
5#include <stm32wbxx_ll_bus.h>
6
7#include <furi_hal_bus.h>
8
9// Timer used for tickless idle
10#define FURI_HAL_IDLE_TIMER_MAX 0xFFFF
11#define FURI_HAL_IDLE_TIMER LPTIM1
12#define FURI_HAL_IDLE_TIMER_IRQ LPTIM1_IRQn
13
14static inline void furi_hal_idle_timer_init() {
15 furi_hal_bus_enable(FuriHalBusLPTIM1);
16 // Configure clock source
17 LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE_LSE);
18 // There is a theoretical possibility that we need it
19 LL_APB1_GRP1_EnableClockSleep(LL_APB1_GRP1_PERIPH_LPTIM1);
20 // Set interrupt priority and enable them
21 NVIC_SetPriority(
22 FURI_HAL_IDLE_TIMER_IRQ, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 0));
23 NVIC_EnableIRQ(FURI_HAL_IDLE_TIMER_IRQ);
24}
25
26static inline void furi_hal_idle_timer_start(uint32_t count) {
27 count--;
28 // Enable timer
29 LL_LPTIM_Enable(FURI_HAL_IDLE_TIMER);
30 while(!LL_LPTIM_IsEnabled(FURI_HAL_IDLE_TIMER))
31 ;
32
33 // Enable compare match interrupt
34 LL_LPTIM_EnableIT_CMPM(FURI_HAL_IDLE_TIMER);
35
36 // Set compare, autoreload and start counter
37 // Include some marging to workaround ARRM behaviour
38 LL_LPTIM_SetCompare(FURI_HAL_IDLE_TIMER, count - 3);
39 LL_LPTIM_SetAutoReload(FURI_HAL_IDLE_TIMER, count);
40 LL_LPTIM_StartCounter(FURI_HAL_IDLE_TIMER, LL_LPTIM_OPERATING_MODE_ONESHOT);
41}
42
43static inline void furi_hal_idle_timer_reset() {
44 // Hard reset timer
45 // THE ONLY RELIABLE WAY to stop it according to errata
46 furi_hal_bus_reset(FuriHalBusLPTIM1);
47 // Prevent IRQ handler call
48 NVIC_ClearPendingIRQ(FURI_HAL_IDLE_TIMER_IRQ);
49}
50
51static inline uint32_t furi_hal_idle_timer_get_cnt() {
52 uint32_t counter = LL_LPTIM_GetCounter(FURI_HAL_IDLE_TIMER);
53 uint32_t counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_IDLE_TIMER);
54 while(counter != counter_shadow) {
55 counter = counter_shadow;
56 counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_IDLE_TIMER);
57 }
58 return counter;
59}