软件定时器类似于单片机的定时中断,但是精度和优先级不如硬件定时器。支持单次模式(只执行一次)和周期模式。精度为x个tick
注意事项
函数接口讲解xTimerCreate() 软件定时器创建函数
xTimerStart()软件定时器启动函数
软件定时器在创建完成的时候是处于休眠状态的,需要用 FreeRTOS 的相关函数将软件定时器活动起来,而 xTimerStart()函数就是可以让处于休眠的定时器开始工作。
xTimerStop()软件定时器停止函数
xTimerStop() 用于停止一个已经启动的软件定时器, 该函数的实现也是通过“定时器命令队列”发送一个停止命令给软件定时器任务,从而唤醒软件定时器任务去将定时器停止。
xTimerDelete() 软件定时器删除函数
xTimerDelete()用于删除一个已经被创建成功的软件定时器, 删除之后就无法使用该定
时器, 并且定时器相应的资源也会被系统回收释放。
软件定时器实验:使用软件定时器设置定时任务,当定时器到了事件就执行回调函数,回调函数相当于定时器中断函数(软件定义,事件没有硬件定时器精确),回调函数中的内容要尽可能精简,不能出现阻塞和死循环。
实验现象:每隔一秒循环执行Swtmr1_Callback() 第五秒执行Swtmr2_Callback(),只执行一次;
main.c 如下
#include "stm32f10x.h"
#include "EXC_Gpio.h"
#include "EXC_Usart.h"
#include "EXC_Led.h"
#include "EXC_Key.h"
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "event_groups.h"
static TaskHandle_t AppTaskCreate_Handle;
static TimerHandle_t Swtmr1_Handle =NULL;
static TimerHandle_t Swtmr2_Handle =NULL;
static void AppTaskCreate(void);
static void Swtmr1_Callback(void* pvParameters);
static void Swtmr2_Callback(void* pvParameters);
static void BSP_Init(void);
int main(void)
{
BaseType_t xReturn = pdPASS;
BSP_Init();
xReturn = xTaskCreate((TaskFunction_t )AppTaskCreate, //任务函数
(const char* )"AppTaskCreate", //任务名称
(uint32_t )256, //任务堆栈大小
(void* )NULL, //传递给任务函数的参数
(UBaseType_t )3, //任务优先级
(TaskHandle_t* )AppTaskCreate_Handle); //任务控制块指针
//任务控制块
if(pdPASS == xReturn)
{
vTaskStartScheduler();
}
else
{
return -1;
}
while(1)
{
}
}
static void AppTaskCreate(void)
{
taskENTER_CRITICAL(); //进入临界区
Swtmr1_Handle=xTimerCreate((const char* ) "AutoReloadTimer",
(TickType_t) 1000,
(UBaseType_t)pdTRUE,
(void*)1,
( TimerCallbackFunction_t)Swtmr1_Callback);
if(Swtmr1_Handle != NULL)
{
xTimerStart(Swtmr1_Handle,0); //开启周期定时器
}
Swtmr2_Handle=xTimerCreate((const char* ) "AutoReloadTimer",
(TickType_t) 5000,
(UBaseType_t)pdFALSE,
(void*)1,
( TimerCallbackFunction_t)Swtmr2_Callback);
if(Swtmr2_Handle != NULL)
{
xTimerStart(Swtmr2_Handle,0); //开启周期定时器
}
vTaskDelete(AppTaskCreate_Handle); //删除AppTaskCreate任务
taskEXIT_CRITICAL(); //退出临界区
}
static void Swtmr1_Callback(void* parameter)
{
static int TmrCb_Count1;
TickType_t tick_num1;
TmrCb_Count1++;
tick_num1 = xTaskGetTickCount();
LED1_TOGGLE;
printf("Swtmr1_Callback 函数执行 %d 次rn", TmrCb_Count1);
printf("滴答定时器数值=%drn", tick_num1);
}
static void Swtmr2_Callback(void* parameter)
{
static int TmrCb_Count2;
TickType_t tick_num1;
TmrCb_Count2++;
tick_num1 = xTaskGetTickCount();
LED3Color_Set(LEDRED);
printf("Swtmr2_Callback 函数执行 %d 次rn", TmrCb_Count2);
printf("滴答定时器数值=%drn", tick_num1);
}
static void BSP_Init(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
USART_init(SYSTEM_UART,115200,1);
printf("串口初始化成功rn");
LED3Color_Init(LEDBLUE);
Key_Init(K1);
Key_Init(K2);
ILI9341_Init();
LCD_SetFont(&Font8x16);
LCD_SetColors(RED,BLACK);
ILI9341_Clear(0,0,LCD_X_LENGTH,LCD_Y_LENGTH);
ILI9341_DispString_EN(50,0,"Hello world!");
}



