FreeRTOS——协同程序(Co-routine)( 三 )


void vApplicationIdleHook( void ){vCoRoutineSchedule( void );}或者 , 如果空闲任务没有执行任何其他功能 , 则从循环内调用vCoRoutineSchedule()会更有效:
void vApplicationIdleHook( void ){for( ;; ){vCoRoutineSchedule( void );}}

  • 创建协同例程并启动RTOS调度程序
可以在main()中创建协同例程 。
#include "task.h"#include "croutine.h"#define PRIORITY_0 0void main( void ){// In this case the index is not used and is passed// in as 0.xCoRoutineCreate( vFlashCoRoutine, PRIORITY_0, 0 );// NOTE:Tasks can also be created here!// Start the RTOS scheduler.vTaskStartScheduler();}
  • 扩展示例:使用index参数
现在假设我们要从同一函数创建8个这样的协例程 。每个协同例程将以不同的速率闪烁不同的LED 。index参数可用于从协同例程函数本身内部区分协同例程 。
这次 , 我们将创建8个协同例程 , 并向每个例程传递不同的索引 。
#include "task.h"#include "croutine.h"#define PRIORITY_00#define NUM_COROUTINES8void main( void ){int i;for( i = 0; i < NUM_COROUTINES; i++ ){// This time i is passed in as the index.xCoRoutineCreate( vFlashCoRoutine, PRIORITY_0, i );}// NOTE: Tasks can also be created here!// Start the RTOS scheduler.vTaskStartScheduler();}协同例程功能也得到了扩展 , 因此每个例程都使用不同的LED和闪烁速率 。
【FreeRTOS——协同程序(Co-routine)】const int iFlashRates[ NUM_COROUTINES ] = { 10, 20, 30, 40, 50, 60, 70, 80 };const int iLEDToFlash[ NUM_COROUTINES ] = { 0, 1, 2, 3, 4, 5, 6, 7 }void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ){// Co-routines must start with a call to crSTART().crSTART( xHandle );for( ;; ){// Delay for a fixed period.uxIndex is used to index into// the iFlashRates.As each co-routine was created with// a different index value each will delay for a different// period.crDELAY( xHandle, iFlashRate[ uxIndex ] );// Flash an LED.Again uxIndex is used as an array index,// this time to locate the LED that should be toggled.vParTestToggleLED( iLEDToFlash[ uxIndex ] );}// Co-routines must end with a call to crEND().crEND();}