FreeRTOS mutex minimal example

This is how you create and use a mutex in FreeRTOS:

Includes:

freertos_includes.h
#include <freertos/semphr.h>

 

Global declaration

freertos_globals.cpp
SemaphoreHandle_t myMutex;

Initialization code

Call this once, before using it:

freertos_init.cpp
myMutex = xSemaphoreCreateMutex();

How to lock & unlock the mutex

freertos_mutex_usage.cpp
// Wait a maximum of 10ms to lock the mutex
if(xSemaphoreTake(myMutex, 10 / portTICK_PERIOD_MS) == pdTRUE) {
    // Success locking the mutex
    // TODO: Your code goes here!
    // Unlock the mutex!
    xSemaphoreGive(myMutex);
} else {
    // Failed to lock the mutex within timeout
    // DO NOT use the resource protected by the mutex
    // DO NOT unlock (xSemaphoreGive) !
}

 


Check out similar posts by category: Embedded, FreeRTOS, PlatformIO