← Back to the chapter · Previous detail · Next detail →

Technical detail · Software Optimization Techniques

A delay is not always sleep

18.12 A Busy-Waiting delay() Does Not Sleep, And You Must Offload The Watching

Two traps turn an intended low-power design back into a polling one. The first is the busy-wait delay. On Arduino AVR, a call like delay(10) busy-waits and does not enter low-power sleep; on ESP32 Arduino, delay() yields to FreeRTOS, which can permit automatic light sleep when configured. Check the target implementation and current trace before assigning an active-current cost. A duty cycle built from such busy-wait delays still pays active current the whole time. The fix is to replace the delay with a real sleep primitive - a wait-for-interrupt, light sleep, or deep sleep - armed with a timer wake, so the core is genuinely off during the interval.

The arithmetic is unforgiving. A busy-waiting implementation that waits one second with delay(1000) at 8 mA burns 8 mA-s during that second even though it did no useful work. Across 3600 one-second waits, that is 8 mAh per hour of waiting current. A timer-backed sleep at 10 uA over the same hour is about 0.010 mAh before wake work, so the firmware primitive - delay versus sleep - decides almost the whole current budget.

The second trap is watching in software. If the “event” is detected by the CPU reading a sensor or analog-to-digital converter (ADC) in a loop, the core cannot sleep, and you have an event-driven shape with polling energy. The watching must be offloaded to a peripheral that runs while the core sleeps: a general-purpose input/output (GPIO) interrupt for a digital line, an analog comparator or the sensor’s own threshold interrupt for a level crossing, or a low-power timer for periodic wakes. Only then can the processor stay asleep until the peripheral raises an interrupt. One more caveat closes the loop: if events become very frequent, the wake and processing overhead can keep the core effectively awake anyway, and batching several events per wake restores the benefit. Event-driven design wins when the watching is offloaded and the events are sparse relative to the processing.

← Back to the chapter · Previous detail · Next detail →