FreeRTOS的定时器设计实现

电子说

1.2w人已加入

描述

定时器的概念

定时器用于根据系统时启动特定的函数,执行相应的任务。FreeRTOS的定时器可以配置启动一次或者间隔一定时间执行。

当然,定时器的实现是基于RTOS心跳机制与任务列表的。这意味着其API可以任何RTOS托管下的程序段调用(而中断不行),包括定时器关联的的回调函数。

FreeRTOS提供了间隔执行定时器的运行时序:

串口中断

API Description ※ 定时器不能在中断中使用

**①****创建定时器 **osTimerNew()

定时器的类型分为单次(One-time )和多次执行(periodic),在创建时进行配置;其中多次执行时序见上图;单次唤起一次后自动停止,需要用户手动再次启动。而多次执行则间隔指定时间就会执行一次,直至用户停止。

osTimerId_t osTimerNew (osTimerFunc_t func, osTimerType_t type, void *argument, const osTimerAttr_t *attr);/*
创建一个定时器,并绑定相应的回调函数      @retval 定时器的ID;  创建失败返回NULL
@param    void(* osTimerFunc_t)(void *argument) //这是回调函数的格式,例:
            -void Timer1_Callback(void *arg); //arg contains various type of variables.
func        -回调函数的地址,即函数名
type        -定时器类型(单次或间隔型):  osTimerOnce -执行单次  osTimerPeriodic -多次执行
*argument   -传递给回调函数的参数;传入地址;缺省填 (void*)0即可
*/

②启动定时器 osTimerStart()

osStatus_t osTimerStart (osTimerId_t timer_id, uint32_t ticks);/*
启动定时器并指定时间间隔.  指定的回调函数在经过本函数指定的ticks后第一次被调用。
@param:
id           -定时器ID
ticks        -间隔时间 (单位心跳数)       
@retval:
osOK         -成功
osErrorISR   -在中断中调用而出错
osErrorParameter: parameter timer_id is either NULL or invalid or ticks is incorrect.
osErrorResource: the timer is in an invalid state.
*/

③停止定时器 osTimerStop()

停止定时器的效果从下一次唤醒开始(回调函数停止自己定时器的情况)

osStatus_t osTimerStop (osTimerId_t timer_id);/*
停止指定的定时器
@retval
osOK
osErrorISR
osErrorParameter: parameter timer_id is either NULL or invalid.
osErrorResource: the timer is not running (you can only stop a running timer).
*/

④查询定时器启动状态osTimerIsRunning()

uint32_t osTimerIsRunning (osTimerId_t  timer_id);/*
@retval
0 U   -未启动、中断中调用、未创建
!0    -已启动
*/

⑤删除定时器 osTimerDelete()

回调函数可以删除调用自己的定时器。

删除后定时器id值变为NULL,可以再调用 osTimerNew() 为其创建新的定时器

osStatus_t osTimerDelete (osTimerId_t timer_id);/*
删除定时器并清理其资源。
@retval: 
  osOK: the specified timer has been deleted.
  osErrorISR: osTimerDelete cannot be called from interrupt service routines.
  osErrorParameter: parameter timer_id is either NULL or invalid.
  osErrorResource: the timer is in an invalid state.
*/

示例

void Timer_Callback (void *arg);                // prototype for timer callback function
uint32_t exec;                                  // argument for the timer call back function
void TimerStop_example (void) {
  osTimerId_t id;                               // timer id
  osStatus_t  status;                           // function return status
  // Create periodic timer
  exec = 1U;
  id = osTimerNew(Timer_Callback, osTimerPeriodic, &exec, NULL);
  osTimerStart(id, 1000U);                      // start timer
  :
  status = osTimerStop(id);                     // stop timer
  if (status != osOK) {
    // Timer could not be stopped
  }
  ;
  osTimerStart(id, 1000U);                      // start timer again
  ;
}
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分