Skip to content

ESP32 and RTOS Tasks

Drzony edited this page Aug 6, 2021 · 1 revision

On ESP32, when the CPU is loaded, asynchronous WiFi libraries (like ESPAsyncWebServer or async-mqtt-client) may interfere with interrupts used to control the LEDs (I2S mode is less affected by this), which causes flickering of LEDs.

One way to solve that is to create a high priority task that will take care of showing the LEDs.

The following code is an example of this approach:

xSemaphoreHandle semaphore = NULL;
TaskHandle_t commit_task;
NeoPixelBus<NeoGrbFeature, NeoEsp32RmtNWs2811Method> pixel_bus;

void commitTaskProcedure(void *arg)
{
    while (true)
    {
        while (ulTaskNotifyTake(pdTRUE, portMAX_DELAY) != 1)
            ;
        pixel_bus.Show();
        while (!pixel_bus.CanShow())
            ;
        xSemaphoreGive(semaphore);
    }
}

void commit()
{
    xTaskNotifyGive(commit_task);
    while (xSemaphoreTake(semaphore, portMAX_DELAY) != pdTRUE)
        ;
}

void init_task()
{
    commit_task = NULL;
    semaphore = xSemaphoreCreateBinary();

    xTaskCreatePinnedToCore(
        commitTaskProcedure,         /* Task function. */
        "ShowRunnerTask",            /* name of task. */
        10000,                       /* Stack size of task */
        NULL,                        /* parameter of the task */
        4,                           /* priority of the task */
        &commit_task,                /* Task handle to keep track of created task */
        1);                          /* pin task to core core_id */
}

void setup()
{
   pixel_bus.begin();
   init_task();
}

void loop()
{
    commit();
    delay(10);
}
Clone this wiki locally