furi_hal_delay.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. void furi_hal_delay_init() {
  7. CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
  8. DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
  9. DWT->CYCCNT = 0U;
  10. }
  11. uint32_t furi_hal_delay_instructions_per_microsecond() {
  12. return SystemCoreClock / 1000000;
  13. }
  14. uint32_t furi_hal_get_tick(void) {
  15. return osKernelGetTickCount();
  16. }
  17. uint32_t furi_hal_ms_to_ticks(float milliseconds) {
  18. return milliseconds / (1000.0f / osKernelGetTickFreq());
  19. }
  20. void furi_hal_delay_us(float microseconds) {
  21. uint32_t start = DWT->CYCCNT;
  22. uint32_t time_ticks = microseconds * furi_hal_delay_instructions_per_microsecond();
  23. while((DWT->CYCCNT - start) < time_ticks) {
  24. };
  25. }
  26. // cannot be used in ISR
  27. // TODO add delay_ISR variant
  28. void furi_hal_delay_ms(float milliseconds) {
  29. if(!FURI_IS_ISR() && osKernelGetState() == osKernelRunning) {
  30. uint32_t ticks = milliseconds / (1000.0f / osKernelGetTickFreq());
  31. osStatus_t result = osDelay(ticks);
  32. (void)result;
  33. furi_assert(result == osOK);
  34. } else {
  35. furi_hal_delay_us(milliseconds * 1000);
  36. }
  37. }