Try Embedded

FreeRTOS tasks and a shared Serial port

Three FreeRTOS tasks on an Uno: two LEDs blink at their own rates while a third reports, with a mutex guarding Serial.

RTOS · Intermediate

In a real product: Medical monitor (Medical): Tasks share a port safely under a mutex.

In a plain sketch, blinking two LEDs at different rates means juggling millis() timers in one loop(). An RTOS lets each job be its own task with its own simple loop, and a scheduler switches between them. This project runs FreeRTOS on the Uno with three tasks, and uses a mutex so two tasks can print without mixing their lines.

What you'll learn

  • Creating tasks with xTaskCreate, and giving each its stack size and priority
  • Waiting with vTaskDelay, which lets other tasks run (unlike delay() in a single loop)
  • Protecting a shared resource (here Serial) with a mutex
  • Why loop() stays empty once the scheduler is running

How it works

The FreeRTOS library (listed in libraries.txt) starts the scheduler after setup() returns. Each task is a function with an endless loop:

  • blinkRed toggles the red LED on pin 12 every 250 ms.
  • blinkGreen toggles the green LED on pin 11 every 700 ms.
  • report prints how many times each LED has changed, once a second.

vTaskDelay(pdMS_TO_TICKS(250)) puts the task to sleep for 250 ms, and the scheduler runs whichever task is ready. On the AVR port the tick comes from the watchdog timer, about every 15 ms, so delays are rounded to whole ticks: 250 ms is really 16 ticks, about 240 ms. Real-time doesn't mean exact; it means bounded and predictable.

Both blink tasks also print a line when they toggle. Serial is one resource shared by several tasks, so each takes the serialLock mutex before printing and gives it back afterwards. Without it, a task switch in the middle of a print could interleave two messages.

Stacks are small on purpose: the Uno has 2 KB of RAM in all, and every task needs its own stack. report prints numbers, which uses more stack, so it gets more.

Try this

  • Open the Tasks panel under the circuit while it runs: each task gets a row, with a bar wherever it had the CPU. How much of the time does the Uno spend in IDLE?
  • Remove the mutex calls from both blink tasks and watch the Serial Monitor for mixed-up lines.
  • Give report a higher priority than the blinkers (3) and see whether anything changes. Why not?
  • Replace vTaskDelay in blinkRed with delay(250) and watch what happens to the green LED.
  • Shrink report's stack to 64 words and see how the program fails.

sketch.ino

// Three FreeRTOS tasks: two blink LEDs at their own rates, one reports. A mutex keeps Serial lines whole.
#include <Arduino_FreeRTOS.h>
#include <semphr.h>

const int RED = 12;
const int GREEN = 11;

SemaphoreHandle_t serialLock;
volatile unsigned redToggles = 0, greenToggles = 0;

// Print one line with the mutex held, so no other task can print in the middle of it.
void say(const __FlashStringHelper *who, unsigned count) {
  if (xSemaphoreTake(serialLock, portMAX_DELAY) == pdTRUE) {
    Serial.print(who);
    Serial.println(count);
    xSemaphoreGive(serialLock);
  }
}

void blinkRed(void *) {
  pinMode(RED, OUTPUT);
  for (;;) {
    digitalWrite(RED, !digitalRead(RED));
    redToggles++;
    if (redToggles % 8 == 0) say(F("red toggled "), redToggles);
    vTaskDelay(pdMS_TO_TICKS(250));
  }
}

void blinkGreen(void *) {
  pinMode(GREEN, OUTPUT);
  for (;;) {
    digitalWrite(GREEN, !digitalRead(GREEN));
    greenToggles++;
    if (greenToggles % 4 == 0) say(F("green toggled "), greenToggles);
    vTaskDelay(pdMS_TO_TICKS(700));
  }
}

void report(void *) {
  for (;;) {
    if (xSemaphoreTake(serialLock, portMAX_DELAY) == pdTRUE) {
      Serial.print(F("uptime "));
      Serial.print(millis() / 1000);
      Serial.print(F(" s, red "));
      Serial.print(redToggles);
      Serial.print(F(", green "));
      Serial.println(greenToggles);
      xSemaphoreGive(serialLock);
    }
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

void setup() {
  Serial.begin(9600);
  serialLock = xSemaphoreCreateMutex();
  // Stack sizes are in words; priorities run from 0 (idle) upwards.
  xTaskCreate(blinkRed, "red", 128, NULL, 2, NULL);
  xTaskCreate(blinkGreen, "green", 128, NULL, 2, NULL);
  xTaskCreate(report, "report", 192, NULL, 1, NULL);
  // The scheduler starts when setup() returns.
}

void loop() {
  // Runs as the idle task. All the work is in the tasks above.
}

Lessons behind it