123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- #include "st_sys.h"
- //1秒换算成1us的倍数
- #define US_PER_SECOND 1000000
- //当前的时间
- static volatile int cur_second = 0;
- static volatile int cur_ms = 0;
- static int reload_valve = 0;
- unsigned long dwTickCount = 0;
- static volatile int system_core_clock = 400; //系统时钟
- void SysTick_Handler(void)
- {
- dwTickCount++;
-
- if (++cur_ms >= 1000) {
- cur_ms = 0;
- cur_second++;
- }
- }
- /**
- * 初始化定时器
- *
- * @author lxz
- *
- * @param void
- */
- void sw_timer_init(int clk)
- {
- //clk = clk * 1000000;
- /*
- SysTick->CTRL &= ~(1 << 2); //SYSTICK 时钟跟系统同步
- SysTick->CTRL |= 1 << 1; //中断使能
- SysTick->LOAD = (clk / 8000) - 1; //1ms中断
- SysTick->CTRL |= 1 << 0; //使能systick
- Sys_NVIC_Init(1,1,SysTick_IRQn,1);
- */
- reload_valve = clk * 1000 - 1;
- SysTick_Config(clk * 1000);
-
- //__NVIC_EnableIRQ(SysTick_IRQn);
- }
- /**
- * 获取当前的定时器时间
- *
- * @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_valve - us) * 1000 / reload_valve;
- }
- /**
- * 初始化一个定时器实体用于时间比较
- *
- * @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;
- }
|