furi_hal_delay.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "furi_hal_delay.h"
  2. #include <furi.h>
  3. #include <cmsis_os2.h>
  4. #include <stm32wbxx_ll_utils.h>
  5. #define TAG "FuriHalDelay"
  6. static volatile uint32_t tick_cnt = 0;
  7. void furi_hal_delay_init() {
  8. CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
  9. DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
  10. DWT->CYCCNT = 0U;
  11. }
  12. uint32_t furi_hal_delay_instructions_per_microsecond() {
  13. return SystemCoreClock / 1000000;
  14. }
  15. void furi_hal_tick(void) {
  16. tick_cnt++;
  17. }
  18. uint32_t furi_hal_get_tick(void) {
  19. return tick_cnt;
  20. }
  21. uint32_t furi_hal_ms_to_ticks(float milliseconds) {
  22. return milliseconds / (1000.0f / osKernelGetTickFreq());
  23. }
  24. void furi_hal_delay_us(float microseconds) {
  25. uint32_t start = DWT->CYCCNT;
  26. uint32_t time_ticks = microseconds * furi_hal_delay_instructions_per_microsecond();
  27. while((DWT->CYCCNT - start) < time_ticks) {
  28. };
  29. }
  30. // cannot be used in ISR
  31. // TODO add delay_ISR variant
  32. void furi_hal_delay_ms(float milliseconds) {
  33. if(!FURI_IS_ISR() && osKernelGetState() == osKernelRunning) {
  34. uint32_t ticks = milliseconds / (1000.0f / osKernelGetTickFreq());
  35. osStatus_t result = osDelay(ticks);
  36. (void)result;
  37. furi_assert(result == osOK);
  38. } else {
  39. furi_hal_delay_us(milliseconds * 1000);
  40. }
  41. }