furi_hal_os_timer.h 2.2 KB

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