软件定时器:是基于系统Tick时钟中断且由软件来模拟的定时器,当经过设定的Tick时钟计数值后会触发用户定义的回调函数。定时精度与系统Tick时钟的周期有关。
定时器运行机制:
cmsis_os2的API软件定时器接口:
⚫ 静态裁剪:能通过宏关闭软件定时器功能。
⚫ 软件定时器创建:osTimerNew (osTimerFunc_t func, osTimerType_t type, void *argument, const osTimerAttr_t *attr);
⚫ 软件定时器启动:osTimerStart (osTimerId_t timer_id, uint32_t ticks);
⚫ 软件定时器停止:osTimerStop (osTimerId_t timer_id);
⚫ 软件定时器删除:osTimerDelete (osTimerId_t timer_id);
⚫ 软件定时器剩余Tick数获取:
#include <stdio.h> #include <string.h> #include <unistd.h> #include "ohos_init.h" #include "cmsis_os2.h" uint32_t exec1, exec2;//typedef unsigned int uint32_t;
/***** 定时器1 回调函数 *****/
////arg 是一个void的指针变量,指向一个地址
void Timer1_Callback(void *arg)
{
(void)arg;
printf("This is BearPi Harmony Timer1_Callback!
");
}
/***** 定时器2 回调函数 *****/
void Timer2_Callback(void *arg)
{
(void)arg;
printf("This is BearPi Harmony Timer2_Callback!
");
}
/***** 定时器创建 *****/
static void Timer_example(void)
{
osTimerId_t id1, id2;
uint32_t timerDelay; //延迟时间 unsigned int 类型
osStatus_t status; //状态是枚举值
exec1 = 1U;
id1 = osTimerNew(Timer1_Callback, osTimerPeriodic, &exec1, NULL);
if (id1 != NULL)
{
// Hi3861 1U=10ms,100U=1S
timerDelay = 100U;//延迟1s
status = osTimerStart(id1, timerDelay);
if (status != osOK)
{
// Timer could not be started
}
}
exec2 = 1U;
id2 = osTimerNew(Timer2_Callback, osTimerPeriodic, &exec2, NULL);
if (id2 != NULL)
{
// Hi3861 1U=10ms,300U=3S
timerDelay = 300U;
status = osTimerStart(id2, timerDelay);
if (status != osOK)
{
// Timer could not be started
}
}
}
APP_FEATURE_INIT(Timer_example);
hpm dist 编译----------->HiBurn烧录--------------------- >运行看log