Real-Time Systems and RTOS

Getting Started With FreeRTOS: Your First Tasks on a Microcontroller

A beginner's FreeRTOS tutorial: create your first tasks, run them periodically, pass data with queues, wake tasks from interrupts, and avoid common mistakes.

On this page
  1. What you’ll build
  2. Choose a starting setup
  3. Five concepts to know first
  4. The FreeRTOSConfig.h settings that matter at the start
  5. Your first program: two tasks
  6. Making a task run at a fixed rate
  7. Passing data between tasks with a queue
  8. Waking a task from an interrupt
  9. Checking that it works
  10. Common beginner mistakes
  11. Where to go next
  12. Frequently asked questions

What you’ll build

By the end of this guide you’ll have a small FreeRTOS application with:

  • two tasks running independently at different rates,
  • a periodic task that runs on a steady schedule without drifting,
  • a queue that passes data from one task to another, and
  • an interrupt that wakes a task when a button is pressed.

The code is plain C using the standard FreeRTOS kernel API, so it works on most supported microcontrollers. Board-specific calls, such as toggling an LED, are left as simple placeholders like led_toggle() for you to replace with your board’s GPIO code.

If you’re still deciding whether you need an RTOS at all, read RTOS vs super loop: when do you actually need an RTOS? first.

Choose a starting setup

FreeRTOS is just a set of C source files plus a port for your processor, so there are many ways in. These are the easiest for beginners:

  • STM32 with STM32CubeIDE. STM32CubeMX (built into the IDE) can add FreeRTOS to a project for you. By default the generated code uses the CMSIS-RTOS v2 wrapper API, with calls like osThreadNew(), on top of FreeRTOS. You can call the native FreeRTOS functions used in this guide in the same project. CubeMX also recommends moving the HAL timebase off SysTick to another hardware timer when FreeRTOS is used, so accept that suggestion.
  • ESP32 with ESP-IDF. Espressif’s framework is built on FreeRTOS. The scheduler is already running when your app_main() function is called, so you don’t call vTaskStartScheduler() yourself. Note that in ESP-IDF, stack sizes are given in bytes, not words.
  • No hardware: the simulator ports. The FreeRTOS kernel includes ports that run on Linux (POSIX) and Windows. Timing isn’t real-time, but they’re a convenient way to learn the API with printf output.
  • Other boards. NXP, Microchip, Renesas, TI, Raspberry Pi (RP2040/RP2350), and others provide FreeRTOS examples or integrations. Starting from a vendor’s demo project saves you from setting up the port and interrupt configuration by hand.

Whichever you choose, start from a known working example, build it, flash it, and confirm an LED blinks before you change anything.

Five concepts to know first

  1. Task. A C function that normally never returns, usually written as an infinite loop. Each task has its own stack and a priority.
  2. Priority. A number. In FreeRTOS, higher numbers mean higher priority, and 0 is the lowest (used by the idle task). The scheduler always runs the highest-priority task that’s ready.
  3. Tick. A periodic timer interrupt, commonly set to 1000 Hz, that the kernel uses to measure time. Delays and timeouts are counted in ticks.
  4. Task states. A task is Running (on the CPU), Ready (could run, but a higher- or equal-priority task is running), Blocked (waiting for time to pass or for an event), or Suspended (explicitly paused).
  5. Blocking. When a task waits, for example in vTaskDelay() or xQueueReceive(), it uses no CPU time. That’s what lets lower-priority tasks run. A task that spins in a busy loop never blocks, and lower-priority tasks starve.

For more on how the scheduler chooses between tasks, see real-time scheduling and multitasking in embedded systems.

The FreeRTOSConfig.h settings that matter at the start

Every FreeRTOS project has a FreeRTOSConfig.h file. Vendor tools generate one, and you’ll mostly leave it alone at first. These settings are worth checking:

Setting Typical starting value Why it matters
configUSE_PREEMPTION 1 Lets a higher-priority task take over the CPU immediately
configTICK_RATE_HZ 1000 1 ms tick; makes millisecond delays easy to reason about
configMAX_PRIORITIES 5 to 8 Number of priority levels available
configMINIMAL_STACK_SIZE Port default Stack (in words) for the idle task; a reference point for small tasks
configTOTAL_HEAP_SIZE Depends on RAM Memory pool used when tasks and queues are created dynamically
configCHECK_FOR_STACK_OVERFLOW 2 Enables run-time stack overflow checks during development
configUSE_MALLOC_FAILED_HOOK 1 Calls a hook if the heap runs out
configASSERT() Defined Catches many configuration and API misuse errors early

Turning on the stack overflow check, the malloc-failed hook, and configASSERT() costs a little speed and flash. In return, they turn many mysterious crashes into clear errors while you’re learning.

Your first program: two tasks

This program creates two tasks: one blinks an LED every 500 ms, and the other prints a message every second.

#include "FreeRTOS.h"
#include "task.h"

static void vBlinkTask(void *pvParameters)
{
    (void) pvParameters;

    for (;;) {
        led_toggle();                       /* replace with your GPIO call */
        vTaskDelay(pdMS_TO_TICKS(500));     /* block for 500 ms */
    }
}

static void vHelloTask(void *pvParameters)
{
    (void) pvParameters;

    for (;;) {
        printf("Hello from FreeRTOS\r\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void)
{
    hardware_init();                        /* clocks, GPIO, UART */

    xTaskCreate(vBlinkTask, "blink", 256, NULL, tskIDLE_PRIORITY + 2, NULL);
    xTaskCreate(vHelloTask, "hello", 512, NULL, tskIDLE_PRIORITY + 1, NULL);

    vTaskStartScheduler();                  /* never returns if all is well */

    for (;;) { }                            /* only reached if the scheduler failed to start */
}

Once vTaskStartScheduler() is called, the kernel takes over and main() never continues past that line. If it does, there usually wasn’t enough heap to create the idle task or timer task.

What each xTaskCreate argument means

BaseType_t xTaskCreate(TaskFunction_t pvTaskCode,
                       const char *pcName,
                       configSTACK_DEPTH_TYPE usStackDepth,
                       void *pvParameters,
                       UBaseType_t uxPriority,
                       TaskHandle_t *pxCreatedTask);
  • pvTaskCode: the function the task runs.
  • pcName: a name for debugging. Debuggers and trace tools display it.
  • usStackDepth: the stack size in words (StackType_t units), not bytes. On a 32-bit microcontroller, 256 means 1,024 bytes. ESP-IDF is the well-known exception, where this value is in bytes. The printf task gets more stack because formatted output can use a lot of it.
  • pvParameters: a pointer passed to the task function. It lets one function serve several tasks with different settings.
  • uxPriority: the task’s priority. Using tskIDLE_PRIORITY + n keeps priorities relative to the idle task.
  • pxCreatedTask: where to store the task handle, if you need it later to notify, suspend, or delete the task. Pass NULL if you don’t.

xTaskCreate() returns pdPASS on success. Check it, because a failure almost always means the FreeRTOS heap is too small:

if (xTaskCreate(vBlinkTask, "blink", 256, NULL, 2, NULL) != pdPASS) {
    /* not enough heap: increase configTOTAL_HEAP_SIZE */
}

The stack sizes here are starting guesses. Our guide on how to size RTOS task stacks and detect stack overflow shows how to measure and tune them.

Making a task run at a fixed rate

vTaskDelay() waits for a set time from when it’s called. If the work before it takes 3 ms, a “10 ms” loop actually repeats every 13 ms, and the timing drifts as the work varies. For control loops and sampling, use vTaskDelayUntil() instead. It wakes the task at fixed points in time:

static void vControlTask(void *pvParameters)
{
    (void) pvParameters;
    TickType_t xLastWake = xTaskGetTickCount();

    for (;;) {
        vTaskDelayUntil(&xLastWake, pdMS_TO_TICKS(10));   /* every 10 ms */
        read_sensor();
        update_output();
    }
}

Newer kernel versions also provide xTaskDelayUntil(), which works the same way but returns a value telling you whether the task actually had to wait. If it didn’t, the task is running late.

Passing data between tasks with a queue

Tasks shouldn’t share global variables casually, because one may read a value while another is halfway through writing it. A queue copies data safely from one task to another and lets the receiver block until something arrives.

#include "queue.h"

static QueueHandle_t xTempQueue;

static void vSensorTask(void *pvParameters)
{
    (void) pvParameters;
    int16_t temp;

    for (;;) {
        temp = read_temperature();
        xQueueSend(xTempQueue, &temp, 0);              /* don't wait if full */
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

static void vDisplayTask(void *pvParameters)
{
    (void) pvParameters;
    int16_t temp;

    for (;;) {
        if (xQueueReceive(xTempQueue, &temp, portMAX_DELAY) == pdPASS) {
            show_temperature(temp);
        }
    }
}

/* in main(), before vTaskStartScheduler(): */
xTempQueue = xQueueCreate(8, sizeof(int16_t));        /* 8 items deep */

The display task sleeps inside xQueueReceive() until a reading arrives, so it uses no CPU while waiting. Queues are one of several tools for this. Our article on RTOS task synchronization and inter-task communication covers semaphores, mutexes, event groups, and when to use each.

Waking a task from an interrupt

Interrupt handlers should be short: note the event, wake a task, and return. Direct-to-task notifications are a lightweight way to do this. The rule is that inside an ISR you must use the API functions ending in FromISR.

static TaskHandle_t xButtonTaskHandle;

void BUTTON_IRQHandler(void)                  /* your MCU's interrupt name */
{
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;

    clear_button_interrupt_flag();
    vTaskNotifyGiveFromISR(xButtonTaskHandle, &xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);   /* switch now if needed */
}

static void vButtonTask(void *pvParameters)
{
    (void) pvParameters;

    for (;;) {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);    /* block until notified */
        handle_button_press();                      /* debounce, act, etc. */
    }
}

/* in main(): */
xTaskCreate(vButtonTask, "button", 256, NULL, 3, &xButtonTaskHandle);

portYIELD_FROM_ISR() makes the button task run as soon as the ISR returns, if it has a higher priority than whatever was interrupted.

On Arm Cortex-M, any interrupt that calls a FreeRTOS FromISR function must have a priority that is numerically equal to or greater than configMAX_SYSCALL_INTERRUPT_PRIORITY, which means logically lower or equal in urgency. Getting this wrong is one of the most common causes of random crashes. With configASSERT() defined, many ports catch it for you.

Checking that it works

  • Watch the outputs. The LED should blink steadily and the messages should arrive on time, even while other tasks are busy.
  • Use an RTOS-aware debugger view. STM32CubeIDE, SEGGER Ozone, MCUXpresso, and others can list tasks, their states, and their stack usage.
  • Check the stack high-water mark. uxTaskGetStackHighWaterMark(NULL) called inside a task returns the smallest amount of free stack that task has had, in words. If it’s close to zero, increase the stack.
  • Try a trace tool. SEGGER SystemView and Percepio Tracealyzer show exactly when each task and interrupt ran, which makes timing problems visible.

Common beginner mistakes

  • Letting a task function return. Task functions must loop forever or delete themselves with vTaskDelete(NULL). Returning normally triggers an assert or a crash.
  • Busy-waiting. Loops like while (!flag) { } or a blocking HAL delay keep the task Ready, so lower-priority tasks never run. Block on a delay, queue, or notification instead.
  • Calling normal API functions from an ISR. Use xQueueSendFromISR(), vTaskNotifyGiveFromISR(), and so on.
  • Wrong interrupt priorities on Cortex-M. See the note above about configMAX_SYSCALL_INTERRUPT_PRIORITY.
  • Stacks too small. Symptoms include hard faults, corrupted variables, and crashes that appear when you add a printf. Enable configCHECK_FOR_STACK_OVERFLOW.
  • Heap too small. xTaskCreate() or xQueueCreate() returns failure, or the scheduler doesn’t start. Check return values and enable the malloc-failed hook.
  • Code after vTaskStartScheduler(). It won’t run. Create everything you need before starting the scheduler, or from inside a task.
  • Several tasks calling printf at once. Output can interleave or the C library may not be thread-safe in your setup. Send log messages to one logging task through a queue, or protect output with a mutex.
  • Priorities all the same. Equal-priority tasks share the CPU by time slicing. That’s fine for some work, but give genuinely urgent work a higher priority.

Where to go next

Frequently asked questions

Is FreeRTOS free for commercial use?

Yes. The FreeRTOS kernel is distributed under the MIT license, which allows commercial use. Check the license of any vendor code or middleware you add alongside it.

What’s the difference between xTaskCreate() and osThreadNew()?

xTaskCreate() is the native FreeRTOS API. osThreadNew() belongs to CMSIS-RTOS v2, a standard API from Arm that STM32CubeMX and some other tools place on top of FreeRTOS. Both create a task. Note that CMSIS-RTOS v2 gives stack sizes in bytes, while native FreeRTOS uses words.

Can I use FreeRTOS with Arduino?

On ESP32 boards, the Arduino core already runs on FreeRTOS, so you can call xTaskCreate() directly. For AVR boards such as the Uno, there’s a community-maintained Arduino FreeRTOS library, though the small RAM limits you to a few tasks.

How many tasks can I create?

There’s no small fixed limit. It depends on RAM, since each task needs a stack and a control block. In practice, many microcontroller projects use somewhere between a handful and a few dozen tasks. Fewer, well-defined tasks are usually easier to get right than many tiny ones.

The complete guide to real-time systems and rtos

Real-Time Embedded Systems Explained
Read the guide

Keep exploring

Guides from other topics

All topics →