software_timer.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include "st_sys.h"
  2. //1秒换算成1us的倍数
  3. #define US_PER_SECOND 1000000
  4. //当前的时间
  5. static volatile int cur_second = 0;
  6. static volatile int cur_ms = 0;
  7. static int reload_valve = 0;
  8. unsigned long dwTickCount = 0;
  9. static volatile int system_core_clock = 400; //系统时钟
  10. void SysTick_Handler(void)
  11. {
  12. dwTickCount++;
  13. if (++cur_ms >= 1000) {
  14. cur_ms = 0;
  15. cur_second++;
  16. }
  17. }
  18. /**
  19. * 初始化定时器
  20. *
  21. * @author lxz
  22. *
  23. * @param void
  24. */
  25. void sw_timer_init(int clk)
  26. {
  27. //clk = clk * 1000000;
  28. /*
  29. SysTick->CTRL &= ~(1 << 2); //SYSTICK 时钟跟系统同步
  30. SysTick->CTRL |= 1 << 1; //中断使能
  31. SysTick->LOAD = (clk / 8000) - 1; //1ms中断
  32. SysTick->CTRL |= 1 << 0; //使能systick
  33. Sys_NVIC_Init(1,1,SysTick_IRQn,1);
  34. */
  35. reload_valve = clk * 1000 - 1;
  36. SysTick_Config(clk * 1000);
  37. //__NVIC_EnableIRQ(SysTick_IRQn);
  38. }
  39. /**
  40. * 获取当前的定时器时间
  41. *
  42. * @author lxz
  43. *
  44. * @param timer
  45. */
  46. void sw_timer_now(sw_timer_t *timer)
  47. {
  48. int second;
  49. int us;
  50. int ms;
  51. do
  52. {
  53. ms = cur_ms;
  54. second = cur_second;
  55. us = SysTick->VAL;
  56. }while (ms != cur_ms);
  57. timer->second = second;
  58. timer->usec = (ms * 1000) + (reload_valve - us) * 1000 / reload_valve;
  59. }
  60. /**
  61. * 初始化一个定时器实体用于时间比较
  62. *
  63. * @author lxz
  64. *
  65. * @param timer object 定时实体
  66. * @param second 要延时的秒单位
  67. * @param usec 要延时的毫秒单位
  68. */
  69. void sw_timer_start(sw_timer_t *timer, int sec, int usec)
  70. {
  71. sw_timer_now(timer);
  72. sw_timer_delay(timer, sec, usec);
  73. }
  74. /**
  75. * 返回定时器是否已经计时到了
  76. *
  77. * @author lxz
  78. *
  79. * @param timer 定时器实体
  80. *
  81. * @return int
  82. */
  83. int sw_timer_expire(sw_timer_t *timer)
  84. {
  85. sw_timer_t now;
  86. sw_timer_now(&now);
  87. if (timer->second < now.second ||
  88. (timer->second == now.second && timer->usec <= now.usec)) return 1;
  89. return 0;
  90. }
  91. /**
  92. * 对当关定时器进行时间延后
  93. *
  94. * @author lxz
  95. *
  96. * @param timer 定时器实体
  97. * @param sec 要延后的秒数
  98. * @param usec 要延后的微秒数
  99. *
  100. * @return int
  101. */
  102. void sw_timer_delay(sw_timer_t *timer, int sec, int usec)
  103. {
  104. timer->usec += usec;
  105. timer->second += sec + timer->usec / US_PER_SECOND;
  106. timer->usec %= US_PER_SECOND;
  107. }