0
0
FreeRTOSprogramming~5 mins

Why tasks are the building blocks in FreeRTOS

Choose your learning style9 modes available
Introduction

Tasks let your program do many things at once. They help organize work into small, easy parts.

When you want your device to read sensors and control motors at the same time.
When you need to handle user input while also sending data over the network.
When your program must keep track of time and respond quickly to events.
When you want to separate different jobs so they don't block each other.
When you want your program to be easier to understand and fix.
Syntax
FreeRTOS
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.

Examples
This creates a simple task that runs forever doing its job.
FreeRTOS
void Task1(void *pvParameters) {
  while(1) {
    // do something
  }
}

xTaskCreate(Task1, "Task One", 1000, NULL, 1, NULL);
This task blinks an LED every 500 milliseconds with higher priority.
FreeRTOS
void BlinkLED(void *pvParameters) {
  while(1) {
    // toggle LED
    vTaskDelay(500 / portTICK_PERIOD_MS);
  }
}

xTaskCreate(BlinkLED, "LED Blink", 500, NULL, 2, NULL);
Sample Program

This program creates two tasks that print messages at different speeds. It shows how tasks run independently.

FreeRTOS
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.