hardware_delay.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "st_sys.h"
  2. /*
  3. *********************************************************************************************************
  4. * 寄存器
  5. *********************************************************************************************************
  6. */
  7. #define DWT_CYCCNT *(volatile unsigned int *)0xE0001004
  8. #define DWT_CR *(volatile unsigned int *)0xE0001000
  9. #define DEM_CR *(volatile unsigned int *)0xE000EDFC
  10. #define DBGMCU_CR *(volatile unsigned int *)0xE0042004
  11. #define DEM_CR_TRCENA (1 << 24)
  12. #define DWT_CR_CYCCNTENA (1 << 0)
  13. static volatile int system_core_clock = 400; //系统时钟
  14. /**
  15. * 初始化软件延时
  16. *
  17. * @author lxz
  18. *
  19. * @param clk 设备硬件时钟
  20. */
  21. void hw_delay_init(int clk)
  22. {
  23. system_core_clock = clk * 1000000;
  24. DEM_CR |= (unsigned int)DEM_CR_TRCENA; /* Enable Cortex-M4's DWT CYCCNT reg. */
  25. DWT_CYCCNT = (unsigned int)0u;
  26. DWT_CR |= (unsigned int)DWT_CR_CYCCNTENA;
  27. }
  28. /**
  29. * 微妙级延时
  30. *
  31. * @author LXZ (2018/8/16)
  32. *
  33. * @param usec
  34. */
  35. void hw_delay_us(int usec)
  36. {
  37. uint32_t tCnt, tDelayCnt;
  38. uint32_t tStart;
  39. tStart = DWT_CYCCNT; /* 刚进入时的计数器值 */
  40. tCnt = 0;
  41. tDelayCnt = usec * (system_core_clock / 1000000); /* 需要的节拍数 */
  42. while (tCnt < tDelayCnt)
  43. {
  44. tCnt = DWT_CYCCNT - tStart; /* 求减过程中,如果发生第一次32位计数器重新计数,依然可以正确计算 */
  45. }
  46. }
  47. /**
  48. * 获取当前的微秒值,该值只是近似值,偏差一个us
  49. *
  50. * @author lxz (2019/5/30/周四)
  51. *
  52. * @param void
  53. *
  54. * @return int
  55. */
  56. int hw_read_us(void)
  57. {
  58. uint32_t usec = system_core_clock / 1000000;
  59. return (DWT_CYCCNT + (usec >> 1)) / usec;
  60. }