freertos 软件定时器
时间: 2025-05-30 22:13:08 浏览: 33
### FreeRTOS 软件定时器的使用方法
FreeRTOS 的软件定时器是一种轻量级的任务替代方案,主要用于实现一次性或周期性的事件触发功能[^1]。它通过操作系统内核管理时间片分配,因此无需依赖特定硬件资源即可运行。
#### 创建和配置软件定时器
创建一个软件定时器需要调用 `xTimerCreate` 函数。该函数允许指定定时器名称、超时时间、自动重载标志以及回调函数等参数。以下是其定义:
```c
TimerHandle_t xTimerCreate(
const char *pcTimerName, // 定时器的名字(调试用途)
TickType_t xTimerPeriodInTicks, // 定时器的时间间隔(单位:ticks)
UBaseType_t uxAutoReload, // 是否自动重新加载 (pdTRUE 或 pdFALSE)
void *pvTimerID, // 用户自定义数据传递给回调函数
TimerCallbackFunction_t pxCallback// 定时器到期后的回调函数指针
);
```
- **`uxAutoReload` 参数**决定了定时器是一次性还是周期性工作模式。如果设置为 `pdTRUE`,则每次到期后会自动重启;如果是 `pdFALSE`,那么只会在第一次到期时触发回调。
#### 启动与停止定时器
一旦创建好定时器实例之后,可以利用下面两个 API 来启动或者暂停它们:
- 使用 `xTimerStart(TimerHandle_t xTimer, TickType_t xBlockTime)` 开始计时;
- 停止正在运行中的某个定时器可调用 `xTimerStop(TimerHandle_t xTimer, TickType_t xBlockTime)` 方法。
另外还有其他一些辅助操作比如改变现有活动对象属性值之类的接口可供选用。
#### 示例代码展示如何运用这些概念构建简单的应用程序逻辑结构如下所示:
```c
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
/* Callback function prototype */
void vTimerCallback( TimerHandle_t xTimer );
int main(void){
/* Create a software timer with auto-reload enabled and assign callback function */
TimerHandle_t xMyTimer = xTimerCreate("OneShot", // Name of the timer.
pdMS_TO_TICKS(500),// Period/Timespan in ticks.
pdFALSE, // One-shot mode.
NULL, // No ID used.
vTimerCallback); // Function to call when expired.
if(xMyTimer != NULL){
/* Start the created one shot timer. Block indefinitely until successful.*/
if( xTimerStart(xMyTimer, portMAX_DELAY ) == pdPASS ){
printf("Successfully started my one-time timer.\n");
}
}
/* Start scheduler after setting up all tasks & timers...*/
vTaskStartScheduler();
}
/* Implementation of user-defined callback routine invoked upon expiration event occurrence within context switching mechanism provided by OS kernel itself! */
void vTimerCallback( TimerHandle_t xTimer ){
static uint8_t counter=0;
++counter;
printf("%d times called since initialization.",counter);
}
```
此例子展示了怎样建立单发型软体计时装置及其相应的处理流程设计思路[^1].
阅读全文
相关推荐


















