【FreeRTOS】小白进阶之如何使用FreeRTOS中断回调函数

介绍如何使用中断回调函数。

1、头文件声明

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

#define mainINTERRUPT_NUMBER	3

static void vPeriodicTask( void *pvParameters );

// 中断回调函数,运行在 daemon 任务,该任务优先级 configTIMER_TASK_PRIORITY
static void vDeferredHandlingFunction( void *pvParameter1, uint32_t ulParameter2 );

// 中断处理函数
static uint32_t ulExampleInterruptHandler( void );

2、启动任务

int main( void )
{
    const UBaseType_t ulPeriodicTaskPriority = configTIMER_TASK_PRIORITY - 1;

    xTaskCreate( vPeriodicTask, "Periodic", 1000, NULL, ulPeriodicTaskPriority, NULL );

    // 中断处理函数
    vPortSetInterruptHandler( mainINTERRUPT_NUMBER, ulExampleInterruptHandler );

    vTaskStartScheduler();

    for( ;; );
    return 0;
}

3、定义任务

static void vPeriodicTask( void *pvParameters )
{
	const TickType_t xDelay500ms = pdMS_TO_TICKS( 500UL );

	for( ;; )
	{
		vTaskDelay( xDelay500ms );

		vPrintString( "Periodic task - About to generate an interrupt.\r\n" );
        // 用于启动模拟中断函数
		vPortGenerateSimulatedInterrupt( mainINTERRUPT_NUMBER );
		vPrintString( "Periodic task - Interrupt generated.\r\n\r\n\r\n" );
	}
}

static uint32_t ulExampleInterruptHandler( void )
{
	static uint32_t ulParameterValue = 0;
	BaseType_t xHigherPriorityTaskWoken;

	xHigherPriorityTaskWoken = pdFALSE;

	// 中断处理回调函数
	xTimerPendFunctionCallFromISR( vDeferredHandlingFunction, NULL, ulParameterValue, &xHigherPriorityTaskWoken );
	ulParameterValue++;

	portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}

static void vDeferredHandlingFunction( void *pvParameter1, uint32_t ulParameter2 )
{
	( void ) pvParameter1;

	// 执行回调事件
	vPrintStringAndNumber( "Handler function - Processing event ", ulParameter2 );
}

 

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