软件定时器
FreeRTOS提供了现成的软件定时器功能,可以一定程度上替代硬件定时器,但精度不高。
实验:创建一个任务,两个定时器,按键开启定时器,一个500ms打印一次,一个1000ms打印一次。
实现:在【STM32】FreeRTOS事件组学习基础上修改。
/* USER CODE END Variables */
osThreadId Task1Handle;
osTimerId myTimer01Handle;
osTimerId myTimer02Handle;
/* Create the timer(s) *//* definition and creation of myTimer01 */osTimerDef(myTimer01, Callback01);myTimer01Handle = osTimerCreate(osTimer(myTimer01), osTimerPeriodic, NULL);/* definition and creation of myTimer02 */osTimerDef(myTimer02, Callback02);myTimer02Handle = osTimerCreate(osTimer(myTimer02), osTimerPeriodic, NULL);/* USER CODE BEGIN RTOS_TIMERS */
上面的代码是CubeMX封装好的。
下面编写自己需要的任务代码。
第一步:修改记数周期
/* start timers, add new ones, ... */xTimerChangePeriod(myTimer01Handle,500,200);xTimerChangePeriod(myTimer02Handle,1000,200);
第二步:按键任务
void StartDefaultTask(void const * argument)
{/* USER CODE BEGIN StartDefaultTask *//* Infinite loop */for(;;){if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_2)==0){osDelay(20);if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_2)==0){ printf("KEY1\r\n");xTimerStart(myTimer01Handle,100);xTimerStart(myTimer02Handle,100);osDelay(200);}}if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_2)==0){osDelay(20);if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_2)==0){ printf("KEY2\r\n");xTimerStop(myTimer01Handle,100);xTimerStop(myTimer02Handle,100);osDelay(200);}}}/* USER CODE END StartDefaultTask */
}
第三步:定时器回调
void Callback01(void const * argument)
{/* USER CODE BEGIN Callback01 */printf("Timer1\r\n");/* USER CODE END Callback01 */
}/* Callback02 function */
void Callback02(void const * argument)
{/* USER CODE BEGIN Callback02 */printf("Timer2\r\n");/* USER CODE END Callback02 */
}