Should I use a main loop or yield()?

I am about to implement a medium scale application that needs to manage quite a few things, read states, write states… Let’s call each separate set of functions, a “module”.

What would be the best practice between the following two architectures and why:

1. Main Loop

Have the main loop pass control to each module, let the module do its thing, without any blocking, and return control to the main loop, then pass control to the next module, so on and so forth.

2. Using yield()

Have setup call each module’s respective setup() functions which will enter into a while(true) {} loop that contains a yield() at the end to pass control to … not sure how control is passed… or even if that arch would work…

I am equally interested in the why as in which is the best practice.

I recommend you watch

to get an overview on programming paradigms. Your “1. Main loop” would be a superloop architecture.

In the context of Arduino-ESP32, which is running the FreeRTOS real-time operating system, a “yield” means that you pass control to another task waiting to be executed, i.e., do a context switch.

If you let all your modules run in the same task (i.e. one superloop) then calling yield() doesn’t do much pass control on to some other task running on the ESP32 (like, WiFi, watchdog clear, …).

1 Like

That’s what I’m doing.

Actually, I created SetupAndLoopAware “interface” that can implement and in effect be called one after another in the Arduino’s loop.