• 27 Posts
  • 369 Comments
Joined 2 years ago
cake
Cake day: June 7th, 2024

help-circle





















  • Arduino is based on the ‘giant loop’ model, where you initialize settings in the setup() function, then wait for events (inputs, timers, handlers, etc) in the loop() function.

    Each time, the loop() function has to finish before it can be called again. So if there are timing related actions, there’s a chance they may fall out of sync or stutter. If you want to advance an animation frame, you’ll need to maintain all the state, and hope the loop gets called often enough so the frame can advance. If you want to sync up the animation to an RTC, then you’ll want to track whether the current loop syncs up with a time code before deciding whether to advance the animation (or not). Pretty soon your giant loop will likely get complicated and messy.

    Another option is to look at something like SoftPWM for controlling LEDs and see how they set up animation timing. Or to use the millis() function instead of delay() to manage timing. Adafruit has a nice tutorial on that: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

    To get more asynchronous activity going, the next option is to move to a more task-based system like FreeRTOS. Here you set up ‘tasks’ which can yield to each other, so you can have more asynchronous events. But the mental model is very different than the Arduino loop. The toolchain is also completely different. Here’s a decent primer: https://controllerstech.com/freertos-on-arduino-tutorial-part-1/

    If your target device is an ESP32, the underlying OS is actually FreeRTOS. Arduino is a compatibility layer on top. So you can use the Arduino IDE and toolchain to write FreeRTOS tasks. Many peripheral device drivers can also be shared between the two. However, the minute you switch to tasks, the Arduino loop doesn’t work any more. Examples here: https://randomnerdtutorials.com/esp32-freertos-arduino-tasks/

    From your description, it sounds like you may want to switch to FreeRTOS tasks.