Search code examples
esp32

When setting up a esp32 for an asynchronous web server, can there be code within the void loop()?


I have ran into a couple examples that don't really have any code written in the void loop() section when using the esp32 as an asynchronous web server. Just curious if I can run other code there before I begin designing some things out.


Solution

  • Yes.

    The Arduino Core for the ESP32 runs over the ESP-IDF (Espressif IoT Development Framework). ESP-IDF uses a port of FreeRTOS. FreeRTOS provides lightweight tasks.

    The async web server uses AsyncTCP, which uses its own task for event callbacks. You can see the code here.

    loop() is just a task. You can still run your own code in it (and make your own tasks if you want that much asynchrony). You can see the code that calls loop() here.

    These tasks are non-preemptive - only one can run at a time, no others can do anything until a task voluntarily yields control of the processor (using yield() or delay() in the Arduino Core).

    For callbacks from the async web server you should do the work you need to do and then return as soon as possible - don't yield or call delay() in its callbacks or you may block the TCP and web server event handler from handling other events (like open connections or received data). Definitely do not busy loop waiting for time to pass in it. If you need to do any substantial amount of work to handle a web request you're best off setting a shared variable that loop() inspects, and then doing the work in loop().