0
0
FreeRTOSprogramming~5 mins

Memory usage monitoring in FreeRTOS

Choose your learning style9 modes available
Introduction

Memory usage monitoring helps you see how much memory your FreeRTOS program uses. It keeps your system running smoothly by avoiding memory problems.

When you want to check if your tasks have enough memory to run.
When your system crashes and you suspect memory is full.
When you add new features and want to make sure memory is still enough.
When debugging memory leaks or unexpected behavior.
When optimizing your program to use less memory.
Syntax
FreeRTOS
size_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask);
This function returns the minimum amount of stack space that has remained for the task since it started.
You need to pass the task handle to check its stack usage.
Examples
Check the stack space left for the current task by passing NULL.
FreeRTOS
size_t freeStack = uxTaskGetStackHighWaterMark(NULL);
Check the stack space left for a specific task using its handle.
FreeRTOS
size_t freeStack = uxTaskGetStackHighWaterMark(myTaskHandle);
Sample Program

This program creates a task that prints its free stack space every second. It helps monitor memory usage live.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

void vTaskFunction(void *pvParameters) {
    for (;;) {
        size_t freeStack = uxTaskGetStackHighWaterMark(NULL);
        printf("Free stack space: %u words\n", (unsigned int)freeStack);
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void) {
    xTaskCreate(vTaskFunction, "Task1", 100, NULL, 1, NULL);
    vTaskStartScheduler();
    return 0;
}
OutputSuccess
Important Notes

Stack space is measured in words, not bytes. One word is usually 4 bytes on many systems.

Low free stack values mean your task is close to running out of memory.

Use this monitoring to avoid stack overflow crashes.

Summary

Memory usage monitoring in FreeRTOS helps keep your system stable.

Use uxTaskGetStackHighWaterMark() to check free stack space per task.

Regular monitoring prevents crashes and helps optimize memory use.