1. 定时器工作机制
RT-Thread 的定时器可以分为 HARD_TIMER 模式与 SOFT_TIMER 模式
在创建时通过flag宏定义去决定
#define RT_TIMER_FLAG_HARD_TIMER 0x0 /**< hard timer,the timer's callback function will be called in tick isr. */
#define RT_TIMER_FLAG_SOFT_TIMER 0x4 /**< soft timer,the timer's callback function will be called in timer thread. */
。在 RT-Thread 定时器模块中维护着两个重要的全局变量:
(1)当前系统经过的 tick 时间 rt_tick(当硬件定时器中断来临时,它将加 1);
(2)定时器链表 rt_timer_list。系统新创建并激活的定时器都会按照以超时时间排序的方式插入到 rt_timer_list 链表中。
如下图所示,系统当前 tick 值为 20,在当前系统中已经创建并启动了三个定时器,分别是定时时间为 50 个 tick 的 Timer1、100 个 tick 的 Timer2 和 500 个 tick 的 Timer3,这三个定时器分别加上系统当前时间 rt_tick=20,从小到大排序链接在 rt_timer_list 链表中,形成如图所示的定时器链表结构。
//定时器回调函数
void timer_demo_callback(void *parameter)
{
int num ;
num = (int)parameter;
rt_kprintf("timer demo %d callback is runing...\n",num) ;
}
struct rt_timer timer2_id;
int main(void)
{
//动态创建定时器
rt_timer_t timer_id = NULL;
timer_id = rt_timer_create("timer1 demo", timer_demo_callback, (void*)1, 2000,
RT_TIMER_FLAG_SOFT_TIMER|RT_TIMER_FLAG_PERIODIC);
if(timer_id == RT_NULL){
LOG_E("rt_timer_create failed...\n",);
}else {
LOG_E("rt_timer_create successed...\n");
}
// rt_timer_start(timer_id);
//静态创建定时器
rt_timer_init(&timer2_id,"time2 demo",timer_demo_callback,(void*)2,3000,
RT_TIMER_FLAG_SOFT_TIMER|RT_TIMER_FLAG_PERIODIC);
rt_timer_start(&timer2_id);
return RT_EOK;
}
/*
rt_timer_t rt_timer_create(const char *name,
void (*timeout)(void *parameter),
void *parameter,
rt_tick_t time,
rt_uint8_t flag)
*/
参数依次为:定时器名字,定时器回调函数入口,定时器回调函数参数,定时时间。
flag:在rt_def.h中定义,主要包括是硬件定时还是软件定时,是触发一次还是周期性触发。
#define RT_TIMER_FLAG_DEACTIVATED 0x0 /**< timer is deactive */
#define RT_TIMER_FLAG_ACTIVATED 0x1 /**< timer is active */
#define RT_TIMER_FLAG_ONE_SHOT 0x0 /**< one shot timer */
#define RT_TIMER_FLAG_PERIODIC 0x2 /**< periodic timer */
#define RT_TIMER_FLAG_HARD_TIMER 0x0 /**< hard timer,the timer's callback function will be called in tick isr. */
#define RT_TIMER_FLAG_SOFT_TIMER 0x4 /**< soft timer,the timer's callback function will be called in timer thread. */
#define RT_TIMER_CTRL_SET_TIME 0x0 /**< set timer control command */
#define RT_TIMER_CTRL_GET_TIME 0x1 /**< get timer control command */
#define RT_TIMER_CTRL_SET_ONESHOT 0x2 /**< change timer to one shot */
#define RT_TIMER_CTRL_SET_PERIODIC 0x3 /**< change timer to periodic */
#define RT_TIMER_CTRL_GET_STATE 0x4 /**< get timer run state active or deactive*/