delay.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "delay.h"
  2. static u8 fac_us=0;//us延时倍乘数
  3. static u16 fac_ms=0;//ms延时倍乘数
  4. //初始化延迟函数
  5. //SYSTICK的时钟固定为HCLK时钟的1/8
  6. //SYSCLK:系统时钟
  7. void delay_init(void)
  8. {
  9. systick_clksource_set(SYSTICK_CLKSOURCE_HCLK_DIV8);
  10. fac_us = SystemCoreClock / 8000000;
  11. fac_ms = (u16)fac_us * 1000;
  12. }
  13. void delay_us(u32 nus)
  14. {
  15. u32 ctl;
  16. SysTick->LOAD = (u32)(nus * fac_us);
  17. SysTick->VAL = 0x0000U;
  18. do {
  19. ctl = SysTick->CTRL;
  20. } while((ctl & SysTick_CTRL_ENABLE_Msk) && !(ctl & SysTick_CTRL_COUNTFLAG_Msk));
  21. SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
  22. SysTick->VAL = 0x0000U;
  23. }
  24. //延时nms
  25. //注意nms的范围
  26. //SysTick->LOAD为24位寄存器,所以,最大延时为:
  27. //nms<=0xffffff*8*1000/SYSCLK
  28. //SYSCLK单位为Hz,nms单位为ms
  29. //对72M条件下,nms<=1864
  30. void delay_ms(u16 nms)
  31. {
  32. u32 ctl;
  33. /* reload the count value */
  34. SysTick->LOAD = (u32)(nms * fac_ms);
  35. /* clear the current count value */
  36. SysTick->VAL = 0x0000U;
  37. /* enable the systick timer */
  38. SysTick->CTRL = SysTick_CTRL_ENABLE_Msk;
  39. /* wait for the COUNTFLAG flag set */
  40. do {
  41. ctl = SysTick->CTRL;
  42. } while((ctl & SysTick_CTRL_ENABLE_Msk) && !(ctl & SysTick_CTRL_COUNTFLAG_Msk));
  43. /* disable the systick timer */
  44. SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
  45. /* clear the current count value */
  46. SysTick->VAL = 0x0000U;
  47. }