RTX之——时间管理

时间管理

As well as running your application code as threads, the RTOS also provides some timing services which can be accessed through RTOS system calls.

RTX提供了一些时间服务,用户可以通过系统调用来使用它们。

延时函数

最常见、最基本的时间服务当然是延时函数了。RTX有两种延时函数:相对延时绝对延时

相对延时

void osDelay(uint32_t ticks);  // 相对延时

This call will place the calling thread into the WAIT_DELAY state for the specified number of milliseconds. The timeout value specifies the number of timer ticks until the time delay elapses. The value is an upper bound and depends on the actual time elapsed since the last timer tick.

为什么是相对延时呢?这是相对于绝对时间而言的,也就是说我们传递给osDelay的参数ticks是一个最大值,看下面这个图。

在这里插入图片描述

我们通过调用osDelay(2),设置从此刻开始,延时2个SysTicks。理论上来讲,将会延时2个SysTicks。但实际上不是的,这个2本质上表示的是接下来延时直到发生两个时钟中断。所以,如果系统调用的时刻处于一个时钟周期之内,那么实际延时是达不到2个时钟周期的。这也是我们为什么说2个时钟周期是最大的延时时间的原因。

绝对延时

In addition to the osDelay() function which gives a relative time delay starting from the instant it is called, there is also a delay function which halts a thread until a specific point in time:

osStatus osDelayUntil (uint32_t ticks);

在这里插入图片描述

具体使用如下:

 void redLight(void* arg)
{
	while(1){
		    uint64_t ticks = osKernelGetTickCount();  // obtain current Tick count
			LED1(ON); 
			osDelayUntil(ticks + 100);
			LED1(OFF);
			osDelayUntil(ticks + 200);
	}    
 }

虚拟定时器

The CMSIS-RTOS API can be used to define any number of virtual timers which act as count down timers. When they expire, they will run a user call-back function to perform a specific action. Each timer can be configured as a one shot or repeat timer.

RTX允许用户创建任何多个虚拟定时器,该定时器是一个向下计数器,且可以设置为一次性或者周期性。简单地说就是我们给该虚拟定时器一个 ticks count和回调函数,每经过一个时钟周期,该数减一。当ticks count 变为0时,就会执行该回调函数。就这么简单~,下面来看一下具体步骤。

1.创建虚拟定时器属性结构体

static const osTimerAttr_t timer0_attr = {
    .name = "timer0",
};

2.设置回调函数

这里还是以LED灯闪烁为例。

 void redLight(void* arg)
{
	while(1){
	    LED1(ON); 
        osDelay(100);
        LED1(OFF);
        osDelay(100);
	}    
 } 

3.创建虚拟定时器

函数原型:osTimerNew(&callback,osTimerPeriodic,(void*)<parameter>,&timerAttr_timer0);

osTimerId_t timer0;
// 设置周期性,可用 osTimerPeriodic
timer0 = osTimerNew(&redLight,osTimerOnce,NULL,&timer0_attr);  
osTimerStart(timer0,0x1000);

至此,OK啦~,暂时就这么多。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rob月初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值