systick.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include "systick.h"
  2. #include "misc.h"
  3. static u8 fac_us = 0; // us延时倍乘数
  4. static u16 fac_ms = 0; // ms延时倍乘数
  5. volatile uint32_t systick_ms = 0;
  6. volatile uint32_t systick_us = 0;
  7. volatile static uint32_t delay;
  8. volatile uint32_t sys_tick_u32 = 0;
  9. void dev_systick_decrement(void)
  10. {
  11. if (0u != delay)
  12. {
  13. delay--;
  14. }
  15. }
  16. void dev_systick_increase(void)
  17. {
  18. sys_tick_u32++;
  19. }
  20. void systick_init(void)
  21. {
  22. SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
  23. if (SysTick_Config(SystemCoreClock / 1000))
  24. {
  25. while (1)
  26. {
  27. }
  28. }
  29. NVIC_SetPriority(SysTick_IRQn, 0x00);
  30. }
  31. uint32_t get_systick_ms(void)
  32. {
  33. uint32_t tick, tick_ms;
  34. __disable_irq();
  35. tick = (SYSTICK_EXT_CLOCK_1MS_CNT - SysTick->VAL);
  36. tick_ms = tick / (SYSTICK_EXT_CLOCK_1MS_CNT);
  37. tick_ms = tick_ms + systick_ms;
  38. __enable_irq();
  39. return tick_ms;
  40. }
  41. uint32_t get_systick_us(void)
  42. {
  43. uint32_t tick, tick_us;
  44. __disable_irq();
  45. tick = (SYSTICK_EXT_CLOCK_1MS_CNT - SysTick->VAL);
  46. tick_us = tick / (SYSTICK_EXT_CLOCK_1MS_CNT / 1000);
  47. tick_us = tick_us + systick_us;
  48. __enable_irq();
  49. return tick_us;
  50. }
  51. void ms_delay(uint8_t ms_time)
  52. {
  53. uint32_t end_count = 0, current_count = 0;
  54. current_count = get_systick_ms();
  55. end_count = current_count + ms_time;
  56. if (end_count == current_count)
  57. {
  58. return;
  59. }
  60. else if (end_count > current_count)
  61. {
  62. while (get_systick_ms() < end_count)
  63. ;
  64. }
  65. else
  66. {
  67. while (get_systick_ms() >= current_count)
  68. ;
  69. while (get_systick_ms() < end_count)
  70. ;
  71. }
  72. }
  73. void us_delay(uint8_t us_time)
  74. {
  75. uint32_t end_count = 0, current_count = 0;
  76. current_count = get_systick_us();
  77. end_count = current_count + us_time;
  78. if (end_count == current_count)
  79. {
  80. return;
  81. }
  82. else if (end_count > current_count)
  83. {
  84. while (get_systick_us() < end_count)
  85. ;
  86. }
  87. else
  88. {
  89. while (get_systick_us() >= current_count)
  90. ;
  91. while (get_systick_us() < end_count)
  92. ;
  93. }
  94. }
  95. void systick_handler(void)
  96. {
  97. __disable_irq();
  98. systick_ms += 1;
  99. systick_us += 1000;
  100. __enable_irq();
  101. }