furi_hal_delay.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. void furi_hal_delay_us(float microseconds) {
  22. uint32_t start = DWT->CYCCNT;
  23. uint32_t time_ticks = microseconds * furi_hal_delay_instructions_per_microsecond();
  24. while((DWT->CYCCNT - start) < time_ticks) {
  25. };
  26. }
  27. // cannot be used in ISR
  28. // TODO add delay_ISR variant
  29. void furi_hal_delay_ms(float milliseconds) {
  30. if(!FURI_IS_ISR() && osKernelGetState() == osKernelRunning) {
  31. uint32_t ticks = milliseconds / (1000.0f / osKernelGetTickFreq());
  32. osStatus_t result = osDelay(ticks);
  33. (void)result;
  34. furi_assert(result == osOK);
  35. } else {
  36. furi_hal_delay_us(milliseconds * 1000);
  37. }
  38. }