下面我来对BES蓝牙SDK中的硬件定时器进行讲解,有什么不对的地方请指出,谢谢!
我们都知道在写代码的时候往往会设置定时器进行一个定时任务,所以在使用的时候有分为硬件定时器和软件定时器两种。
下面来说下硬件定时器和软件定时器之前有什么区别:
软件定时器:是利用指令执行的时间从而来达到定时的目的,一般是利用循环执行一段指令,来定时一段比较长的时间。优点:不需占用硬件资源,编程简单。缺点:占用CPU的时间,CPU利用率低。长时间的软件定时会让系统的实时性非常的差。适用场合:微妙级的短时间延时,系统实时性要求不高和硬件资源紧张的场合。
硬件定时:利用定时器来计算时间。优点:定时准确,不霸占CPU,系统响应速度快。缺点:占用硬件资源
PS:这是从网上摘录下来的,比我自己说的明白
好了咱们回归正题,下面开始说下BES中的软件定时器的定义和使用:
#ifndef SW_TIMER
#define SW_TIMER
#endif
#ifdef SW_TIMER
void app_timer_test_handle(void const *param);
// timer time
#define 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 main_test(void)
{
TRACE("%s %d.", __func__, __LINE__);
// test creat a SW timer task
app_creat_sw_timer();
return 0;
}
#endif
上面是软件定时器的代码部分,使用起来挺简单的。
好了软件定时器部分就讲解完了,下面开始讲解硬件定时器部分
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;
}
}
由以上代码可以看出硬件定时器比软件定时器在code上少好多,一般情况下在BES的项目工程中不怎么使用硬件定时器、大部分都是使用软件定时器。
那是需要使用硬件定时器:按键、USB host、需要精准时间的task等
BES定时器相关的就讲解完了。