api-hal-os-timer.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 API_HAL_OS_TIMER_MAX 0xFFFF
  7. #define API_HAL_OS_TIMER_REG_LOAD_DLY 0x1
  8. #define API_HAL_OS_TIMER LPTIM2
  9. #define API_HAL_OS_TIMER_IRQ LPTIM2_IRQn
  10. static inline void api_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(API_HAL_OS_TIMER_IRQ, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 0));
  16. NVIC_EnableIRQ(API_HAL_OS_TIMER_IRQ);
  17. }
  18. static inline void api_hal_os_timer_continuous(uint32_t count) {
  19. // Enable timer
  20. LL_LPTIM_Enable(API_HAL_OS_TIMER);
  21. while(!LL_LPTIM_IsEnabled(API_HAL_OS_TIMER));
  22. // Enable rutoreload match interrupt
  23. LL_LPTIM_EnableIT_ARRM(API_HAL_OS_TIMER);
  24. // Set autoreload and start counter
  25. LL_LPTIM_SetAutoReload(API_HAL_OS_TIMER, count);
  26. LL_LPTIM_StartCounter(API_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_CONTINUOUS);
  27. }
  28. static inline void api_hal_os_timer_single(uint32_t count) {
  29. // Enable timer
  30. LL_LPTIM_Enable(API_HAL_OS_TIMER);
  31. while(!LL_LPTIM_IsEnabled(API_HAL_OS_TIMER));
  32. // Enable compare match interrupt
  33. LL_LPTIM_EnableIT_CMPM(API_HAL_OS_TIMER);
  34. // Set compare, autoreload and start counter
  35. // Include some marging to workaround ARRM behaviour
  36. LL_LPTIM_SetCompare(API_HAL_OS_TIMER, count-3);
  37. LL_LPTIM_SetAutoReload(API_HAL_OS_TIMER, count);
  38. LL_LPTIM_StartCounter(API_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_ONESHOT);
  39. }
  40. static inline void api_hal_os_timer_reset() {
  41. // Hard reset timer
  42. // THE ONLY RELIABLEWAY to stop it according to errata
  43. LL_LPTIM_DeInit(API_HAL_OS_TIMER);
  44. }
  45. static inline uint32_t api_hal_os_timer_get_cnt() {
  46. uint32_t counter = LL_LPTIM_GetCounter(API_HAL_OS_TIMER);
  47. uint32_t counter_shadow = LL_LPTIM_GetCounter(API_HAL_OS_TIMER);
  48. while(counter != counter_shadow) {
  49. counter = counter_shadow;
  50. counter_shadow = LL_LPTIM_GetCounter(API_HAL_OS_TIMER);
  51. }
  52. return counter;
  53. }