Summary
Running multiple independent loops in Arduino is challenging due to the blocking nature of delay(). The provided code sequentially executes loops, causing LEDs to flash in sequence rather than concurrently. The root cause is the single-threaded execution model of Arduino, which halts all operations during delay().
Root Cause
- Blocking
delay(): Thedelay()function pauses the entire program, preventing concurrent execution. - Single-threaded execution: Arduino runs one task at a time, making true parallelism impossible without external libraries or hardware.
Why This Happens in Real Systems
- Microcontroller limitations: Arduino Uno operates on a single core, executing instructions sequentially.
- Lack of multitasking: Without an operating system, Arduino cannot context-switch between tasks.
Real-World Impact
- Non-concurrent behavior: LEDs flash sequentially instead of independently.
- Inefficient resource use: CPU remains idle during
delay(), wasting processing power.
Example or Code
unsigned long previousBlueMillis = 0;
unsigned long previousGreenMillis = 0;
unsigned long previousRedMillis = 0;
const long blueInterval = 1000;
const long greenInterval = 500;
const long redInterval = 200;
void loop() {
unsigned long currentMillis = millis();
// Blue LED
if (currentMillis - previousBlueMillis >= blueInterval) {
previousBlueMillis = currentMillis;
digitalWrite(bluLED, !digitalRead(bluLED));
}
// Green LED
if (currentMillis - previousGreenMillis >= greenInterval) {
previousGreenMillis = currentMillis;
digitalWrite(grnLED, !digitalRead(grnLED));
}
// Red LED
if (currentMillis - previousRedMillis >= redInterval) {
previousRedMillis = currentMillis;
digitalWrite(redLED, !digitalRead(redLED));
}
}
How Senior Engineers Fix It
- Replace
delay()withmillis(): Use non-blocking timing to check elapsed time without halting execution. - Leverage libraries: Use
TaskSchedulerorTickerfor pseudo-multitasking. - Optimize code: Minimize blocking operations and maximize efficiency.
Why Juniors Miss It
- Overreliance on
delay(): Beginners often usedelay()without understanding its blocking nature. - Lack of timing alternatives: Unawareness of
millis()for non-blocking timing. - Misunderstanding concurrency: Assuming Arduino supports true parallelism without external tools.