1,概述
我们在写代码的时候往往会设置定时器进行一个定时任务,在使用的时候又分为硬件定时器和软件定时器两种,一般情况下在项目工程中不怎么使用硬件定时器、大部分都是使用软件定时器。
2,API参考
2.1 软件定时器部分
-
2.1.1 软件定时器定义
函数原型:
#define osTimerDef(name, function) \
extern const osTimerDef_t os_timer_def_##name
函数功能:定义一个定时器与其处理函数
函数参数:
函数原型:
osTimerId osTimerCreate (const osTimerDef_t *timer_def,
os_timer_type type, void *argument)
函数功能:创建软件定时器
- 函数参数:
- *timer_def:以定义的Timer
- type:软件定时器工作模式
- *argument:默认为NULL
返回值:
函数原型:
osStatus_t osTimerStart (osTimerId_t timer_id, uint32_t ticks)
函数功能:开启已设置的软件定时器
- 函数参数:
- timer_id:定时器id
- ticks:定时器周期
返回值:
函数原型:
osStatus_t osTimerStop (osTimerId_t timer_id)
函数功能:停止软件定时器
- 函数参数:
- timer_id:定时器id
返回值:
函数原型:
void hwtimer_init(void);
-
2.2.2 创建硬件定时器
函数原型:
HWTIMER_ID hwtimer_alloc(HWTIMER_CALLBACK_T callback, void *param);
函数功能:创建硬件定时器
- 函数参数:
- callback:硬件定时器回调函数
- *param:默认为NULL
返回值:
函数原型:
enum E_HWTIMER_T hwtimer_start(HWTIMER_ID id, unsigned int ticks);
函数功能:开启已创建的硬件定时器
- 函数参数:
- id:定时器ID
- ticks:定时器周期
返回值:
函数原型:
enum E_HWTIMER_T hwtimer_update(HWTIMER_ID id, HWTIMER_CALLBACK_T callback,
void *param);
函数功能:更新已有定时器的回调函数与参数
- 函数参数:
- id:定时器ID
- callback:硬件定时器回调函数
- *param:默认为NULL
返回值:
函数原型:
enum E_HWTIMER_T hwtimer_stop(HWTIMER_ID id);
函数功能:关闭硬件定时器
- 函数参数:
- id:定时器ID
返回值:
函数原型:
enum E_HWTIMER_T hwtimer_free(HWTIMER_ID id);
函数功能:删除指定定时器并释放内存
- 函数参数:
- id:定时器ID
- 返回值:
- 定时器状态
3,使用教程
3.1软件定时器使用
```c void app_timer_test_handle(void const *param); // timer timedefine APP_TEST_TIMER_MS 1000
// 将定时器的handle 进行索引 osTimerDef (APP_SW_TIMER_TEST, app_timer_test_handle); // timer iD static osTimerId app_sw_timer_test = NULL; // sw timer hanlde func void app_timer_test_handle(void const *param) { // do anything
- 定时器状态
}
// crest a SW timer task
void app_creat_sw_timer(void)
{
// If it hasn’t been created, it will be created
if (app_sw_timer_test == NULL) {
// Create a software Timer and return a Timer ID for later indexing
app_sw_timer_test = osTimerCreate(osTimer(APP_SW_TIMER_TEST), osTimerPeriodic, NULL);
}
// The following are the Stop and Start Timer tasks, which take the parameters of the created Timer ID and time
osTimerStop(app_sw_timer_test);
osTimerStart(app_sw_timer_test, APP_TEST_TIMER_MS);
}
// 测试函数 int maintest(void) { TRACE(“%s %d.”, func, _LINE); // test creat a SW timer task app_creat_sw_timer();
return 0;
}
<a name="vT6Z0"></a>
## 3.2硬件定时器使用
- 一般硬件定时器使用在需要精准时间的task上(如Key、USB host等),其余情况一般使用软件定时器
```c
static HWTIMER_ID debounce_timer = NULL;
static void hal_key_debounce_handler(void *param)
{
// you can look hal_key.c
}
// creat a hw timer task
void app_creat_hw_Timer(void)
{
if (debounce_timer == NULL)
debounce_timer = hwtimer_alloc(hal_key_debounce_handler, NULL);
}
// close hw timer task
void app_close_hw_Timer(void)
{
if (debounce_timer) {
hwtimer_stop(debounce_timer);
hwtimer_free(debounce_timer);
debounce_timer = NULL;
}
}