furi_hal_os_timer.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <stm32wbxx_ll_lptim.h>
  3. #include <stm32wbxx_ll_bus.h>
  4. #include <stdint.h>
  5. // Timer used for system ticks
  6. #define FURI_HAL_OS_TIMER_MAX 0xFFFF
  7. #define FURI_HAL_OS_TIMER_REG_LOAD_DLY 0x1
  8. #define FURI_HAL_OS_TIMER LPTIM2
  9. #define FURI_HAL_OS_TIMER_IRQ LPTIM2_IRQn
  10. static inline void furi_hal_os_timer_init() {
  11. // Configure clock source
  12. LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM2_CLKSOURCE_LSE);
  13. // Set interrupt priority and enable them
  14. NVIC_SetPriority(
  15. FURI_HAL_OS_TIMER_IRQ, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 0));
  16. NVIC_EnableIRQ(FURI_HAL_OS_TIMER_IRQ);
  17. }
  18. static inline void furi_hal_os_timer_continuous(uint32_t count) {
  19. count--;
  20. // Enable timer
  21. LL_LPTIM_Enable(FURI_HAL_OS_TIMER);
  22. while(!LL_LPTIM_IsEnabled(FURI_HAL_OS_TIMER))
  23. ;
  24. // Enable rutoreload match interrupt
  25. LL_LPTIM_EnableIT_ARRM(FURI_HAL_OS_TIMER);
  26. // Set autoreload and start counter
  27. LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
  28. LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_CONTINUOUS);
  29. }
  30. static inline void furi_hal_os_timer_single(uint32_t count) {
  31. count--;
  32. // Enable timer
  33. LL_LPTIM_Enable(FURI_HAL_OS_TIMER);
  34. while(!LL_LPTIM_IsEnabled(FURI_HAL_OS_TIMER))
  35. ;
  36. // Enable compare match interrupt
  37. LL_LPTIM_EnableIT_CMPM(FURI_HAL_OS_TIMER);
  38. // Set compare, autoreload and start counter
  39. // Include some marging to workaround ARRM behaviour
  40. LL_LPTIM_SetCompare(FURI_HAL_OS_TIMER, count - 3);
  41. LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
  42. LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_ONESHOT);
  43. }
  44. static inline void furi_hal_os_timer_reset() {
  45. // Hard reset timer
  46. // THE ONLY RELIABLEWAY to stop it according to errata
  47. LL_LPTIM_DeInit(FURI_HAL_OS_TIMER);
  48. }
  49. static inline uint32_t furi_hal_os_timer_get_cnt() {
  50. uint32_t counter = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  51. uint32_t counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  52. while(counter != counter_shadow) {
  53. counter = counter_shadow;
  54. counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  55. }
  56. return counter;
  57. }