Introduction
Tasks let your program do many things at once. They help organize work into small, easy parts.
Tasks let your program do many things at once. They help organize work into small, easy parts.
BaseType_t xTaskCreate( TaskFunction_t pvTaskCode, const char * const pcName, configSTACK_DEPTH_TYPE usStackDepth, void *pvParameters, UBaseType_t uxPriority, TaskHandle_t *pxCreatedTask );
pvTaskCode is the function the task will run.
uxPriority sets how important the task is compared to others.
void Task1(void *pvParameters) {
while(1) {
// do something
}
}
xTaskCreate(Task1, "Task One", 1000, NULL, 1, NULL);void BlinkLED(void *pvParameters) {
while(1) {
// toggle LED
vTaskDelay(500 / portTICK_PERIOD_MS);
}
}
xTaskCreate(BlinkLED, "LED Blink", 500, NULL, 2, NULL);This program creates two tasks that print messages at different speeds. It shows how tasks run independently.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void TaskA(void *pvParameters) { for(int i = 0; i < 3; i++) { printf("Task A running %d\n", i+1); vTaskDelay(1000 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } void TaskB(void *pvParameters) { for(int i = 0; i < 3; i++) { printf("Task B running %d\n", i+1); vTaskDelay(500 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } int main(void) { xTaskCreate(TaskA, "Task A", 1000, NULL, 1, NULL); xTaskCreate(TaskB, "Task B", 1000, NULL, 1, NULL); vTaskStartScheduler(); return 0; }
Each task has its own stack to keep data safe.
Tasks run one at a time but switch fast to look like they run together.
Use priorities to decide which task runs first.
Tasks break your program into small jobs that run independently.
They help your device do many things at once smoothly.
Creating tasks correctly is key to using FreeRTOS well.
xTaskCreate with parameters: function, name, stack size, parameters, priority, and handle.xTaskCreate.void Task1(void *pvParameters) {
for (;;) {
printf("Task1 running\n");
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void Task2(void *pvParameters) {
for (;;) {
printf("Task2 running\n");
vTaskDelay(pdMS_TO_TICKS(500));
}
}void vTaskCode(void *pvParameters) {
while(1) {
// Task code
}
}
int main() {
xTaskCreate(vTaskCode, "Task", 1000, NULL, 1, NULL);
vTaskStartScheduler();
return 0;
}Pass the test and this pattern moves unknown