Running multiple tasks at the same time lets your program do many things together. This makes your device more efficient and responsive.
0
0
Multiple tasks running concurrently in FreeRTOS
Introduction
When you want to read sensors and control motors at the same time.
When you need to handle user input while processing data in the background.
When you want to blink an LED while also communicating over Wi-Fi.
When your program must respond quickly to different events without waiting.
Syntax
FreeRTOS
void Task1(void *pvParameters) {
for(;;) {
// Task1 code here
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void Task2(void *pvParameters) {
for(;;) {
// Task2 code here
vTaskDelay(pdMS_TO_TICKS(500));
}
}
int main(void) {
xTaskCreate(Task1, "Task 1", 1000, NULL, 1, NULL);
xTaskCreate(Task2, "Task 2", 1000, NULL, 1, NULL);
vTaskStartScheduler();
for(;;);
}Each task is a function that runs in an infinite loop.
vTaskDelay pauses the task for a set time, letting other tasks run.
Examples
Two tasks: one blinks an LED every 500ms, the other reads a sensor every 1000ms.
FreeRTOS
void BlinkLED(void *pvParameters) {
for(;;) {
// Toggle LED
vTaskDelay(pdMS_TO_TICKS(500));
}
}
void ReadSensor(void *pvParameters) {
for(;;) {
// Read sensor data
vTaskDelay(pdMS_TO_TICKS(1000));
}
}Creating tasks with different priorities: LED task has higher priority (2) than sensor task (1).
FreeRTOS
xTaskCreate(BlinkLED, "LED Task", 1000, NULL, 2, NULL); xTaskCreate(ReadSensor, "Sensor Task", 1000, NULL, 1, NULL);
Sample Program
This program creates two tasks that print messages at different intervals. Task 1 prints every 1 second, Task 2 every 0.5 seconds. They run together, showing multitasking.
FreeRTOS
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void Task1(void *pvParameters) { for(;;) { printf("Task 1 is running\n"); vTaskDelay(pdMS_TO_TICKS(1000)); } } void Task2(void *pvParameters) { for(;;) { printf("Task 2 is running\n"); vTaskDelay(pdMS_TO_TICKS(500)); } } int main(void) { xTaskCreate(Task1, "Task 1", 1000, NULL, 1, NULL); xTaskCreate(Task2, "Task 2", 1000, NULL, 1, NULL); vTaskStartScheduler(); for(;;); }
OutputSuccess
Important Notes
FreeRTOS switches between tasks quickly to make them run together.
Use vTaskDelay to let other tasks run and avoid blocking.
Task priorities help decide which task runs first if both are ready.
Summary
Multiple tasks let your program do many things at once.
Each task runs in a loop and uses vTaskDelay to pause.
FreeRTOS manages task switching automatically.