hal_systick.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "hal_systick.h"
  2. #include <stdint.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. void hal_systick_init(void)
  8. {
  9. SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
  10. if (SysTick_Config(SystemCoreClock / 1000))
  11. {
  12. while (1)
  13. {
  14. }
  15. }
  16. NVIC_SetPriority(SysTick_IRQn, 0x00);
  17. }
  18. uint32_t get_systick_ms(void)
  19. {
  20. uint32_t tick, tick_ms;
  21. __disable_irq();
  22. tick = (SYSTICK_EXT_CLOCK_1MS_CNT - SysTick->VAL);
  23. tick_ms = tick / (SYSTICK_EXT_CLOCK_1MS_CNT);
  24. tick_ms = tick_ms + systick_ms;
  25. __enable_irq();
  26. return tick_ms;
  27. }
  28. uint32_t get_systick_us(void)
  29. {
  30. uint32_t tick, tick_us;
  31. __disable_irq();
  32. tick = (SYSTICK_EXT_CLOCK_1MS_CNT - SysTick->VAL);
  33. tick_us = tick / (SYSTICK_EXT_CLOCK_1MS_CNT / 1000);
  34. tick_us = tick_us + systick_us;
  35. __enable_irq();
  36. return tick_us;
  37. }
  38. void ms_delay(uint8_t ms_time)
  39. {
  40. uint32_t end_count = 0, current_count = 0;
  41. current_count = get_systick_ms();
  42. end_count = current_count + ms_time;
  43. if (end_count == current_count)
  44. {
  45. return;
  46. }
  47. else if (end_count > current_count)
  48. {
  49. while (get_systick_ms() < end_count)
  50. ;
  51. }
  52. else
  53. {
  54. while (get_systick_ms() >= current_count)
  55. ;
  56. while (get_systick_ms() < end_count)
  57. ;
  58. }
  59. }
  60. void us_delay(uint8_t us_time)
  61. {
  62. uint32_t end_count = 0, current_count = 0;
  63. current_count = get_systick_us();
  64. end_count = current_count + us_time;
  65. if (end_count == current_count)
  66. {
  67. return;
  68. }
  69. else if (end_count > current_count)
  70. {
  71. while (get_systick_us() < end_count)
  72. ;
  73. }
  74. else
  75. {
  76. while (get_systick_us() >= current_count)
  77. ;
  78. while (get_systick_us() < end_count)
  79. ;
  80. }
  81. }
  82. void systick_handler(void)
  83. {
  84. __disable_irq();
  85. systick_ms += 1;
  86. systick_us += 1000;
  87. __enable_irq();
  88. }