UCOS Learning (6) - Software Timer

create a timer

We create a timer using the function OSTmrCreate:

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)       //错误码

timer pointer

OS_TMR tmr1;//定义一个定时器结构体

It is a structure describing the timer

Time resolution

The time resolution of the timer in UCOSIII is HZ by a macro OS_CFG_TMR_TASK_RATE_HZ, and the default is 100Hz. We set the timer delay value and the unit of the repetition period, for example:

#define OS_CFG_TMR_TASK_RATE_HZ 100u

One unit is 1/100 s = 10ms,
set dly = 20, that is, the timer initialization delay is: 20*10=200ms,
set period = 100, that is, the timer period is: 100 * 10 = 1000ms

one shot timer

The one-shot timer counts down from the initial value (that is, the parameter dly in the OSTmrCreate() function) until the callback is called to 0 and stops. A one-shot timer executes only once.

cycle timer

The period timer can also be set as the operation mode with an initial delay time, use the parameter dly of the function OSTmrCreate() to determine the first period, and reset the counter value to period at the beginning of each subsequent period.

Callback

insert image description here
It doesn't have to be a loop, but be careful:一定要避免在回调函数中使用阻塞调用或者可以阻塞或删除定时器任务的函数。

void tmr1_callback(void *p_arg)
{
    
    
  ......
  
  ......
}

No need to write loops.

enable timer

We use OSTmrStart() to start the timer

CPU_BOOLEAN  OSTmrStart (OS_TMR  *p_tmr,//定时器结构体指针
                         OS_ERR  *p_err)

If it is a one-time timer, it will be started once, and the callback function will be executed after the countdown is over, and then it will end.
If it is a periodic timer, it will keep counting down in a loop, execute the callback function after the countdown is over, and then reset to the cycle to continue counting down.

other operations

insert image description here

Guess you like

Origin blog.csdn.net/qq_52608074/article/details/122426528