一、概述
内核提供了一个模拟定时器的机制,类似于任务,但是占用资源少,只能做一些简单的定时控制,如可以定时的喂狗、控灯。在软件定时器,不能添加时间管理函数、阻塞等待函数(等待互斥锁/信号量/事件标志组/消息队列)。1.创建软件定时器
void OSTmrCreate (OS_TMR *p_tmr, CPU_CHAR *p_name, OS_TICK dly, OS_TICK period, OS_OPT opt, OS_TMR_CALLBACK_PTR p_callback, void *p_callback_arg, OS_ERR *p_err)参数:
- p_tmr:软件定时器对象
- p_name:软件定时器的名字
- dly:启动定时器后,延迟多长时间执行,默认隐含dly*10ms
- period:定时周期,默认隐含period*10ms
- opt:
- p_callback:软件定时器执行的回调函数 void MyCallback (OS_TMR *p_tmr, void *p_arg);
- p_callback_arg:传递参数给软件定时器的回调函数
- p_err:返回错误码,没有错误的就返回OS_ERR_NONE
- 单次触发
- 重复单次触发
- 周期性执行
2.启动软件定时器
CPU_BOOLEAN OSTmrStart (OS_TMR *p_tmr, OS_ERR *p_err)参数:
- p_tmr:软件定时器对象
- p_err:返回错误码,没有错误的就返回OS_ERR_NONE
- DEF_TRUE is the timer was started
- DEF_FALSE if not or upon an error
3.停止软件定时器
CPU_BOOLEAN OSTmrStop (OS_TMR *p_tmr, OS_OPT opt, void *p_callback_arg, OS_ERR *p_err)参数:
- p_tmr:软件定时器对象
- os_opt:默认参数,OS_OPT_TMR_NONE
- p_callback_arg:填写OSTmrCreate创建时传递给软件定时器arg的参数
- p_err:返回错误码,没有错误的就返回OS_ERR_NONE
- DEF_TRUE is the timer was started
- DEF_FALSE if not or upon an error
4.删除软件定时器
CPU_BOOLEAN OSTmrDel (OS_TMR *p_tmr, OS_ERR *p_err)参数:
- p_tmr:软件定时器对象
- p_err:返回错误码,没有错误的就返回OS_ERR_NONE
- DEF_TRUE is the timer was started
- DEF_FALSE if not or upon an error
二、示例
1、创建1个软件定时器。
OS_TMR g_tmr; void mytimer_Callback (OS_TMR *p_tmr, void *p_arg) { printf("mytimer_Callback\r\n"); } OSTmrCreate(&g_tmr,"g_tmr",0,100,OS_OPT_TMR_PERIODIC,(OS_TMR_CALLBACK_PTR)mytimer_Callback,NULL,&err);
2、创建2个软件定时器。
OS_TMR g_tmr1; OS_TMR g_tmr2; void mytimer_Callback (OS_TMR *p_tmr1, void *p_arg) { if(p_tmr1 == &g_tmr1) printf("gtmr1 mytimer_Callback\r\n"); if(p_tmr2 == &g_tmr2) printf("gtmr2 mytimer_Callback\r\n"); } OSTmrCreate(&g_tmr1,"g_tmr1",0,100,OS_OPT_TMR_PERIODIC,(OS_TMR_CALLBACK_PTR)mytimer_Callback,NULL,&err); OSTmrCreate(&g_tmr2,"g_tmr2",0,100,OS_OPT_TMR_PERIODIC,(OS_TMR_CALLBACK_PTR)mytimer_Callback,NULL,&err); OSTmrStart (&g_tmr1,&err); OSTmrStart (&g_tmr2,&err);
注意:
void timer_callback (OS_TMR *p_tmr, void *p_arg) { OS_ERR err; OS_FLAGS flags; printf("timer_callback ...\r\n"); OSFlagPend(&g_flag_grp, 0x03, 0, OS_OPT_PEND_FLAG_SET_ANY +OS_OPT_PEND_FLAG_CONSUME +OS_OPT_PEND_BLOCKING,NULL, &err); delay_ms(2000); }
当前timer_callback会1秒执行一遍,当调用睡眠2秒和等待事件标志组,该函数还是1秒被调用一次。