UC GEE
UC GEE
DIIDevHeads IoT Integration Server
Created by Sterling on 7/14/2024 in #firmware-and-baremetal
Do I need a mutex to protect 8-bit variables on STM32L476 with ARMv7E-M architecture using FreeRTOS?
Yes @Sterling , multi-byte variables like 16-bit and 32-bit types are not guaranteed to be atomic on ARM Cortex-M4. For these variables, you should use a mutex or other synchronization mechanism to protect access if they are shared between tasks. For example, you can use a FreeRTOS mutex:
uint32_t sharedVar;
SemaphoreHandle_t xMutex;

void main(void) {
xMutex = xSemaphoreCreateMutex();
if(xMutex != NULL) {
if(xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) {
sharedVar = newValue;
xSemaphoreGive(xMutex);
}
}
}

void ISR_Handler(void) {
// Ensure no preemption and data corruption
taskENTER_CRITICAL();
sharedVar = isrValue;
taskEXIT_CRITICAL();
}
uint32_t sharedVar;
SemaphoreHandle_t xMutex;

void main(void) {
xMutex = xSemaphoreCreateMutex();
if(xMutex != NULL) {
if(xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) {
sharedVar = newValue;
xSemaphoreGive(xMutex);
}
}
}

void ISR_Handler(void) {
// Ensure no preemption and data corruption
taskENTER_CRITICAL();
sharedVar = isrValue;
taskEXIT_CRITICAL();
}
In this case, the mutex ensures that only one task can access the variable at a time. For access from ISRs, you use taskENTER_CRITICAL() and taskEXIT_CRITICAL() to protect the critical section.
6 replies