【FreeRTOS】小白进阶之任务如何共用FreeRTOS软件定时器回调函数(二)

介绍两个定时器任务如何通过定时器 handle 共用一个回调函数。

1、头文件声明和函数定义

#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "supporting_functions.h"

#define mainONE_SHOT_TIMER_PERIOD		( pdMS_TO_TICKS( 3333UL ) )
#define mainAUTO_RELOAD_TIMER_PERIOD	( pdMS_TO_TICKS( 500UL ) )

// 定时器共用回调函数
static void prvTimerCallback( TimerHandle_t xTimer );

// 定时器 handle 定义
static TimerHandle_t xAutoReloadTimer, xOneShotTimer;

2、启动定时任务

int main( void )
{
	BaseType_t xTimer1Started, xTimer2Started;

	// 定义 one-shot 定时任务
	xOneShotTimer = xTimerCreate( "OneShot",				
								  mainONE_SHOT_TIMER_PERIOD,	
								  pdFALSE,					
								  0,							
								  prvTimerCallback );		

	// 定义自动重载定时任务
	xAutoReloadTimer = xTimerCreate( "AutoReload",		
									 mainAUTO_RELOAD_TIMER_PERIOD,	
									 pdTRUE,					
									 0,								
									 prvTimerCallback );	

	if( ( xOneShotTimer != NULL ) && ( xAutoReloadTimer != NULL ) )
	{
		// 启动定时任务
		xTimer1Started = xTimerStart( xOneShotTimer, 0 );
		xTimer2Started = xTimerStart( xAutoReloadTimer, 0 );

		if( ( xTimer1Started == pdPASS ) && ( xTimer2Started == pdPASS ) )
		{
			/* Start the scheduler. */
			vTaskStartScheduler();
		}
	}

	for( ;; );
	return 0;
}

3、软件定时器回调函数

static void prvTimerCallback( TimerHandle_t xTimer )
{
	TickType_t xTimeNow;
	uint32_t ulExecutionCount;
	
	ulExecutionCount = ( uint32_t ) pvTimerGetTimerID( xTimer );
	ulExecutionCount++;
	vTimerSetTimerID( xTimer, ( void * ) ulExecutionCount );

	xTimeNow = xTaskGetTickCount();

	if( xTimer == xOneShotTimer )
	{
		vPrintStringAndNumber( "One-shot timer callback executing", xTimeNow );
	}
	else
	{
		vPrintStringAndNumber( "Auto-reload timer callback executing", xTimeNow );

		if( ulExecutionCount == 5 )
		{
			xTimerStop( xTimer, 0 );
		}
	}
}

 

你可能感兴趣的:(FreeRTOS系统开发)