The Problem with Arduino Loops
When you're starting out, Arduino is great: simple, accessible, and well-documented. But as your projects grow, it's biggest strength becomes a major limitation.
Let's explore why and how using Lua with Xedge offers a better path for beginners who want to eventually move on to writing scalable professio
Arduino's main loop is easy to understand:
void loop() {
digitalWrite(13, 1); // LED on
delay(250); // Wait
digitalWrite(13, 0); // LED off
delay(750); // Wait
}
But this is a blocking loop. In other words, your entire system halts while blinking an LED.
During each delay(), the microcontroller is doing nothing else. If your project needs to handle a sensor, process network data, or respond to a button, it can't. You're stuck. There are solutions to this problem, such as the approach described in this tutorial, that show how to replace blocking delays with non-blocking timers. These methods allow your code to check whether a certain amount of time has passed, without halting the entire system. However, while working, this solution introduces a new challenge: you'll need to manually design complex state machines to manage task flow, handle timing, and track the state of each process.
Using Lua and Xedge's Non-Blocking Design
With Xedge running Lua on a microcontroller, beginners can write code that looks like a simple loop, yet is non-blocking and event-driven.
local function blink()
local pin = esp32.gpio(9,"OUT")
while true do
pin:value(false) -- LED On
coroutine.yield(true) -- Sleep
pin:value(true) -- LED Off
coroutine.yield(true) -- Sleep
end
end
timer = ba.timer(blink)
timer:set(1000) -- Timer tick = 1 second
It looks like Arduino, right? But there’s a critical difference:
- coroutine.yield(true) pauses the task without blocking the processor.
- While your LED is "waiting," the CPU can handle network requests, run other coroutines, or perform parallel tasks.
Why This Matters When Writing Embedded Programs
With Xedge, beginners can:
- Write multiple non-blocking "loops" (coroutines).
- React to HW interrupts (events) using Lua callbacks.
- Scale up from simple tasks to complex IoT systems.
- Keep code readable and beginner-friendly.
The following video demonstrates how Xedge, running on a microcontroller, executes two loops simultaneously, one loop handling communication via the MQTT IoT protocol, and another controlling an LED strip.
PLEASE CONTINUE AT Real Time Logics Website here