FreeRTOS任务的创建

1. 需要引用的头文件

1
2
#include <freertos/FreeRTOS.h>	//这里面大小写都可以
#include <freertos/task.h>

2. 使用函数 xTaskCreate()

函数的具体参数如下:

1
2
3
4
5
6
7
BaseType_t xTaskCreate( TaskFunction_t pvTaskCode,	//创建任务的任务函数名称
const char * const pcName, //你要给任务起的名字
unsigned short usStackDepth, //任务所占堆栈空间的大小
void *pvParameters, //给任务传递的参数
UBaseType_t uxPriority, //任务优先级,数字越小越低
TaskHandle_t *pxCreatedTask //任务句柄
); //记得加分号

3. 函数xTaskCreate()用法简介

若传入参数为: xTaskCreate(Task1,"Task1",2048,NULL,1,NULL);
第一个参数是你创建任务的任务函数名为Task1
第二个参数是你要给你的任务起的名字Task1,一般都是和任务函数同名
第三个参数是这个任务所占的堆栈空间大小
第四个参数是给这任务传递的参数,你可以给这个任务传递一个(void *) 型的指针,没有参数就用NULL
第五个参数是任务优先级,数字越小优先级越低
第六个参数是创建任务的一个句柄,不创建的话就填NULL

例程

例程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>

//任务函数
void Task1(void *pvParam)
{
while(1)
{
printf("This is Task1\n");
vTaskDelay(1000/portTICK_RATE_MS);
}
}
//主函数
void app_main(void)
{
xTaskCreate(Task1,"Task1",2048,NULL,1,NULL);//创建任务
//这里加上while(1)的话会出现问题
// while(1);
}

也可以使用另外一种方法在创建任务是指定某个核心运行该任务,前面的参数和之前的函数都是一样的,只有最后加了一个核心数的参数。

1
2
3
4
5
6
7
8
BaseType_t xTaskCreatePinnedToCore(	TaskFunction_t pvTaskCode,	//创建任务的任务函数名称
const char *const pcName, //你要给任务起的名字
const uint32_t usStackDepth, //任务所占堆栈空间的大小
void *const pvParameters, //给任务传递的参数
UBaseType_t uxPriority, //任务优先级
TaskHandle_t *const pvCreatedTask, //任务句柄
const BaswType_t xCoreID //指定运行该任务的核心
); //记得加分号