furi-hal-os-timer.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_LPTIM2);
  14. // Set interrupt priority and enable them
  15. NVIC_SetPriority(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. // Enable rutoreload match interrupt
  24. LL_LPTIM_EnableIT_ARRM(FURI_HAL_OS_TIMER);
  25. // Set autoreload and start counter
  26. LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
  27. LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_CONTINUOUS);
  28. }
  29. static inline void furi_hal_os_timer_single(uint32_t count) {
  30. count--;
  31. // Enable timer
  32. LL_LPTIM_Enable(FURI_HAL_OS_TIMER);
  33. while(!LL_LPTIM_IsEnabled(FURI_HAL_OS_TIMER));
  34. // Enable compare match interrupt
  35. LL_LPTIM_EnableIT_CMPM(FURI_HAL_OS_TIMER);
  36. // Set compare, autoreload and start counter
  37. // Include some marging to workaround ARRM behaviour
  38. LL_LPTIM_SetCompare(FURI_HAL_OS_TIMER, count-3);
  39. LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
  40. LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_ONESHOT);
  41. }
  42. static inline void furi_hal_os_timer_reset() {
  43. // Hard reset timer
  44. // THE ONLY RELIABLEWAY to stop it according to errata
  45. LL_LPTIM_DeInit(FURI_HAL_OS_TIMER);
  46. }
  47. static inline uint32_t furi_hal_os_timer_get_cnt() {
  48. uint32_t counter = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  49. uint32_t counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  50. while(counter != counter_shadow) {
  51. counter = counter_shadow;
  52. counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
  53. }
  54. return counter;
  55. }