Mutex test program crashes the ESP32
Posted: Wed Feb 12, 2025 1:07 pm
Hello.
I have written a program to test my understanding of FreeRTOS mutext behaviour, but I'm having a problem. When running the following code, I have two observations:
If anyone could provide some insight I'd be very grateful. I'm using the Arduino platform via PlatformIO.
Many thanks
I have written a program to test my understanding of FreeRTOS mutext behaviour, but I'm having a problem. When running the following code, I have two observations:
- The code randomly crashes, causing the ESP32 to reboot
- The frequency of change from display AAAAAAAAA to BBBBBBBBBB is much lower than I was expecting, implying that the tasks are swapping very very slowly.
If anyone could provide some insight I'd be very grateful. I'm using the Arduino platform via PlatformIO.
Many thanks
Code: Select all
#include <Arduino.h>
SemaphoreHandle_t myMutex = NULL;
char str[] = "0123456789";
void taskA(void *pvParameters)
{
while (1)
{
if (xSemaphoreTake(myMutex, pdMS_TO_TICKS(1000)) == pdTRUE)
{
for (auto i = 0; i < 10; i++)
str[i] = 'a';
xSemaphoreGive(myMutex);
}
else
vTaskDelay(pdMS_TO_TICKS(20));
}
}
void taskB(void *pvParameters)
{
while (1)
{
if (xSemaphoreTake(myMutex, pdMS_TO_TICKS(1000)) == pdTRUE)
{
for (auto i = 0; i < 10; i++)
str[i] = 'b';
xSemaphoreGive(myMutex);
}
else
vTaskDelay(pdMS_TO_TICKS(20));
}
}
void setup()
{
Serial.begin(9600);
while (!Serial)
;
myMutex = xSemaphoreCreateMutex();
xTaskCreate(
taskA, /* Function that implements the task. */
"tA", /* Text name for the task. */
2048, /* Stack size in words, not bytes. */
(void *)1, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
NULL); /* Used to pass out the created task's handle. */
xTaskCreate(
taskB, /* Function that implements the task. */
"tB", /* Text name for the task. */
2048, /* Stack size in words, not bytes. */
(void *)1, /* Parameter passed into the task. */
1, /* Priority at which the task is created. */
NULL); /* Used to pass out the created task's handle. */
}
void loop()
{
Serial.println(str);
}