software timer
FreeRTOS provides a ready-made software timer function, which can replace the hardware timer to a certain extent, but the accuracy is not high.
Experiment: Create a task, two timers, press a button to start the timer, one prints once in 500ms, and the other prints once in 1000ms.
Implementation: Modified on the basis of [STM32] FreeRTOS event group learning .
/* 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 */
The above code is packaged by CubeMX.
Write the task code you need below.
Step 1: Modify the counting period
/* start timers, add new ones, ... */
xTimerChangePeriod(myTimer01Handle,500,200);
xTimerChangePeriod(myTimer02Handle,1000,200);
Step Two: Button Tasks
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 */
}
Step 3: Timer callback
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 */
}