ESP32 critical zone example using FreeRTOS / PlatformIO

In order to enter a critical zone on the ESP32 using FreeRTOS, you have to do the following:

Globally declare a spinlock:

example.cpp
portMUX_TYPE mySpinlock;

In setup(), initialize the spinlock:

example.cpp
spinlock_initialize(&mySpinlock);

Now, wherever you want to enter a critical zone, run:

example.cpp
portENTER_CRITICAL(&mySpinlock);
// TODO Your critical code goes here!
portEXIT_CRITICAL(&mySpinlock);

When using this **in an interrupt handler,**use this instead:

example.cpp
portENTER_CRITICAL_ISR(&mySpinlock);
// TODO Your critical code goes here!
portEXIT_CRITICAL_ISR(&mySpinlock);

 

FreeRTOS will ensure that no two threads using mySpinlock are run at the same time.


Check out similar posts by category: Arduino, ESP8266/ESP32, FreeRTOS, PlatformIO