Use an MCU's low-power modes in foreground/background systems
The proper use of an embedded MCU's low-power/sleep modes is critical to a design's success.
In today's world of battery-operated devices, the proper use of the low-power/sleep modes provided in most embedded microcontrollers (MCUs) is critical. At the same time, most high-volume MCU applications, such as home appliances, vending machines, motor controllers, and electronic toys, are organized as foreground/background systems (super-loops or main + ISRs).
The foreground/background architecture consists of two main parts--the foreground comprises the interrupt service routines (ISRs) that handle asynchronous external events in a timely fashion, and the background is an infinite loop that uses all remaining CPU cycles to perform the less time-critical processing.
The foreground typically communicates with the background through shared memory. The background loop protects this memory from potential corruption by disabling interrupts when accessing the shared variables.
To employ a low-power MCU mode, the background loop must first determine that all external and internal events have been processed so that the CPU clock can be stopped until the next external event (an interrupt) will wake the CPU up. This situation is called the idle condition and is illustrated in Figure 1.
Because the determination of the idle condition involves testing the variables shared with the foreground (ISRs), the background loop must disable interrupts before detecting the idle condition. Moreover, the idle condition remains valid only as long as interrupts remain disabled. If the interrupts were enabled after the background loop determines that all its work is done for now, but before actually switching to the low-power mode, an interrupt could preempt the background loop at this point and an ISR could produce new work for the background loop, thus invalidating the idle condition.