123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- #include "GD32Sys.h"
- //1秒换算成1us的倍数
- #define US_PER_SECOND 1000000
- //当前的时间
- static int cur_second = 0;
- static int cur_ms = 0;
- static int reload_value = 0;
- unsigned long dwTickCount = 0;
- static void defaut_tick_hook(void);
- static void (*systick_hook)() = defaut_tick_hook;
- /**
- * 默认的1ms周期中断
- *
- * @author lxz
- *
- * @param void
- */
- static void defaut_tick_hook(void)
- {
- }
- /**
- * 定时中断,1ms
- *
- * @author LXZ (010120)
- */
- void SysTick_Handler()
- {
- dwTickCount++;
- if (++cur_ms >= 1000)
- {
- cur_ms = 0;
- cur_second++;
- }
- systick_hook();
- }
- /**
- * 设置ms中断定时器的钩子函数
- *
- * @author lxz
- *
- * @param hook
- */
- void sw_tick_set_hook(void (*hook)())
- {
- if (hook != 0)
- {
- systick_hook = hook;
- }
- }
- /**
- * 初始化定时器
- *
- * @author lxz
- *
- * @param void
- */
- void sw_timer_init(int clk)
- {
- reload_value = clk * 1000 - 1;
- /* setup systick timer for 1000Hz interrupts */
- if (SysTick_Config(clk * 1000U)){
- /* capture error */
- while (1){
- }
- }
- /* configure the systick handler priority */
- NVIC_SetPriority(SysTick_IRQn, 0x00U);
- }
- /**
- * 获取当前的定时器时间
- *
- * @author lxz
- *
- * @param timer
- */
- void sw_timer_now(sw_timer_t *timer)
- {
- int second;
- int us;
- int ms;
- do
- {
- ms = cur_ms;
- second = cur_second;
- us = SysTick->VAL;
- } while (ms != cur_ms);
- timer->second = second;
- timer->usec = (ms * 1000) + (reload_value - us) * 1000 / reload_value;
- }
- /**
- * 初始化一个定时器实体用于时间比较
- *
- * @author lxz
- *
- * @param timer object 定时实体
- * @param second 要延时的秒单位
- * @param usec 要延时的毫秒单位
- */
- void sw_timer_start(sw_timer_t *timer, int sec, int usec)
- {
- sw_timer_now(timer);
- sw_timer_delay(timer, sec, usec);
- }
- /**
- * 返回定时器是否已经计时到了
- *
- * @author lxz
- *
- * @param timer 定时器实体
- *
- * @return int
- */
- int sw_timer_expire(sw_timer_t *timer)
- {
- sw_timer_t now;
- sw_timer_now(&now);
- if (timer->second < now.second ||
- (timer->second == now.second && timer->usec <= now.usec))
- return 1;
- return 0;
- }
- /**
- * 对当关定时器进行时间延后
- *
- * @author lxz
- *
- * @param timer 定时器实体
- * @param sec 要延后的秒数
- * @param usec 要延后的微秒数
- *
- * @return int
- */
- void sw_timer_delay(sw_timer_t *timer, int sec, int usec)
- {
- timer->usec += usec;
- timer->second += sec + timer->usec / US_PER_SECOND;
- timer->usec %= US_PER_SECOND;
- }
|