FreeRTOS mutex minimal example

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

Includes:

#include <freertos/semphr.h>

 

Global declaration

SemaphoreHandle_t myMutex;

Initialization code

Call this once, before using it:

myMutex = xSemaphoreCreateMutex();

How to lock & unlock the mutex

// 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) !
}