定時器分為軟體定時器和硬體定時器。顧名思義,軟體定時器就是有作業系統提供的軟體定時器,硬體定時器就是用硬體晶片提供的定時器。
而在RT-Thread作業系統提供的定時器是軟體定時器,但是為了便于管理,也分了硬體定時器和軟體定時器(都屬于上面的軟體定時器)。
RT-Thread中的HARD_TIMER與SOFT_TIMER最大差別就是指向逾時函數的執行位置不同,HARD_TIMER逾時函數在中斷上下文環境中執行,SOFT_TIMER逾時函數在定時器線程上下文中執行。
下面代碼将會建立兩個靜态定時器單次觸發和周期觸發
static struct rt_timer timer1; // 加上static限定隻能在本檔案
static struct rt_timer timer2;
static int cnt = 0;
static void timer_out1(void *parameter)
{
rt_kprintf("periodic timer is timeout %d\n", cnt);
if(cnt++ >= 9)
{
rt_timer_stop(&timer1);
rt_kprintf("periodic timer was stop!\n");
}
}
static void timer_out2(void *parameter)
{
rt_kprintf("one shot timer was stop!\n");
}
static void timer_sample4(void) //加上void,養成好的代碼習慣
{
rt_timer_init(&timer1, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
rt_timer_start(&timer1);
rt_timer_init(&timer2, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
rt_timer_start(&timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
此時仿真時能夠正常執行,但是下面這個代碼會報錯。
static rt_timer_t timer1; // 加上static限定隻能在本檔案
static rt_timer_t timer2;
static int cnt = 0;
static void timer_out1(void *parameter)
{
rt_kprintf("periodic timer is timeout %d\n", cnt);
if(cnt++ >= 9)
{
rt_timer_stop(timer1);
rt_kprintf("periodic timer was stop!\n");
}
}
static void timer_out2(void *parameter)
{
rt_kprintf("one shot timer was stop!\n");
}
static void timer_sample4(void) //加上void,養成好的代碼習慣
{
rt_timer_init(timer1, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
rt_timer_start(timer1);
rt_timer_init(timer2, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
rt_timer_start(timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
我猜想是因為結構體指針不是一個對象,隻是一個能夠指向結構體對象的指針。後來用下面這段代碼進行了測試,驗證猜想正确。
static struct rt_timer timer1; // 加上static限定隻能在本檔案
static struct rt_timer timer2;
static rt_timer_t timer3; // 加上static限定隻能在本檔案
static rt_timer_t timer4;
static int cnt = 0;
static void timer_out1(void *parameter)
{
rt_kprintf("periodic timer is timeout %d\n", cnt);
if(cnt++ >= 9)
{
rt_timer_stop(&timer1);
rt_kprintf("periodic timer was stop!\n");
}
}
static void timer_out2(void *parameter)
{
rt_kprintf("one shot timer was stop!\n");
}
static void timer_sample4(void) //加上void,養成好的代碼習慣
{
timer3 = &timer1;
timer4 = &timer2;
rt_timer_init(timer3, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
rt_timer_start(&timer1);
rt_timer_init(timer4, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
rt_timer_start(&timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
如果有錯誤,歡迎在評論區指正。