Chuyển đến nội dung

Bài 32 · Power and Debugging

Sleep Modes and Low-Power Design

Make Arduino projects last on batteries: duty cycling, AVR sleep modes, watchdog timer wakeups, wake from pin interrupts, and calculating average current.

A microcontroller that runs flat out all day wastes most of its energy doing nothing: a weather node that reports once a minute needs the processor for a few milliseconds, then idles for the rest. The art of low-power design is to sleep as much as possible, wake only to work, and ensure the sleeping circuit really draws very little. Done well, a node can run for months or years on two AA cells.

Real sleep behavior needs real hardware and a multimeter, so the sketches are read-only. The C programs are labelled stand-ins: they compute average current and simulate a watchdog wake cycle.

Why delay() is not sleep

delay(1000) keeps the processor running at full speed, executing a tight loop. The chip draws the same current as when it does real work. A real sleep mode stops the CPU clock and most peripherals, dropping the draw by a factor of hundreds, until something wakes it: a timer, a pin change, a serial byte.

On the ATmega328P, the main modes (from lightest to deepest) are:

Mode Stops Wake sources Approx. chip current
Idle CPU, flash clock any interrupt, timers, serial about 4 mA at 5 V, 16 MHz
ADC noise reduction CPU, most clocks ADC done, external interrupts, watchdog a bit less
Power-save most; timer 2 keeps running timer 2, interrupts, watchdog about 1 microamp range
Power-down nearly everything external interrupts, watchdog, pin change about 0.1 microamp, plus the watchdog if on (roughly 4 to 6 microamps)

These are chip numbers. A full Uno board still draws tens of milliamps asleep because of the USB-serial chip, the power LED and the regulator. For battery projects use a bare ATmega328P, a Pro Mini with the power LED and regulator removed, or a board designed for low power (see power supplies and batteries).

Sleeping with avr/sleep.h

C++
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

volatile bool woke = false;

ISR(WDT_vect) {
  woke = true;                      // watchdog interrupt: just a wakeup
}

void setupWatchdog8s() {
  cli();
  MCUSR &= ~(1 << WDRF);
  WDTCSR |= (1 << WDCE) | (1 << WDE);          // allow changes
  WDTCSR = (1 << WDIE) | (1 << WDP3) | (1 << WDP0);  // interrupt every 8 s, no reset
  sei();
}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  ADCSRA &= ~(1 << ADEN);           // turn the ADC off (saves current)
  sleep_cpu();                      // execution stops here until an interrupt
  sleep_disable();
  ADCSRA |= (1 << ADEN);            // turn the ADC back on
}

void setup() {
  Serial.begin(9600);
  setupWatchdog8s();
}

void loop() {
  sleepNow();                       // about 8 s of sleep
  if (woke) {
    woke = false;
    Serial.println("Woke up, measuring...");
    // read the sensor, transmit, then loop to sleep again
  }
}

Several details matter:

  • The watchdog timer is a small independent timer. Configured for interrupt mode (WDIE), it wakes the chip after 16 ms up to 8 seconds, with an inexact internal oscillator. For longer sleeps, count wake-ups.
  • Variables shared with an interrupt must be volatile, or the compiler may assume they never change.
  • Keep interrupt routines (ISR) short: set a flag and return.
  • Some libraries (such as LowPower by Rocket Scream or Narcoleptic) wrap all of this: LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); does the above in one line.

Waking on an event

Instead of a timer, a button press or sensor signal can wake the board, which is ideal for devices that act on events (a door sensor, a rain gauge pulse). On the Uno, pins 2 and 3 support attachInterrupt to wake from power-down on a LOW level or any change (the Uno wakes from sleep on LOW only on these pins):

C++
const int WAKE_PIN = 2;

void wakeUp() { }                   // empty is fine: waking is the point

void setup() {
  pinMode(WAKE_PIN, INPUT_PULLUP);
}

void loop() {
  attachInterrupt(digitalPinToInterrupt(WAKE_PIN), wakeUp, LOW);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_mode();
  detachInterrupt(digitalPinToInterrupt(WAKE_PIN));
  // handle the event here
}

Pin-change interrupts (PCINT) allow any pin to wake the chip, but need more register setup.

C Stand-in: watchdog wake cycles (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Average current: the math that decides everything

If the board works for t_active seconds at I_active and sleeps the rest of a period T at I_sleep:

I_avg = (I_active x t_active + I_sleep x (T - t_active)) / T

Then runtime in hours is capacity / I_avg. Typical case: a sensor node needs 20 mA for 100 ms once a minute and sleeps at 0.02 mA. The average is (20 x 0.1 + 0.02 x 59.9) / 60 = 0.053 mA, so 2000 mAh lasts 2000 / 0.053 which is about 37,000 hours (over 4 years, in theory; self-discharge and the real sleep current of the rest of the circuit will limit it).

C Stand-in: average current and battery life (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Reporting every ten minutes instead of every minute gains nearly a factor of ten, and the always-on version is only a few days. Work out this arithmetic before building.

Other tricks

  • Run slower: a lower clock speed and voltage (the 3.3 V, 8 MHz Pro Mini) reduce active current.
  • Power down peripherals: power_adc_disable(), power_spi_disable(), power_twi_disable(), power_timer1_disable().
  • Switch off sensors between readings using a pin (up to about 20 mA) or a transistor/MOSFET for larger loads.
  • Disable the brown-out detector while sleeping if your design allows it (it draws tens of microamps).
  • Set unused pins to INPUT_PULLUP or OUTPUT LOW to avoid floating inputs that waste current.
  • Remove always-on LEDs and regulators that waste milliamps.
  • Batch radio transmissions; radio is usually the most expensive step.
  • Measure. A multimeter in microamp mode, or a dedicated current meter, ends the guessing.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does delay(1000) not save battery?

    delay() is a busy wait. Real savings need a sleep mode that stops the CPU clock.
  2. 2. Which sleep mode is the deepest on the ATmega328P?

    Power-down stops nearly everything and wakes only on external interrupts or the watchdog.
  3. 3. Why mark a variable set in an ISR as volatile?

    The compiler cannot see interrupts. Without volatile it may cache the value in a register and never notice the change.
  4. 4. A node uses 20 mA for 0.1 s then sleeps 59.9 s at 0.02 mA. Roughly what is the average current?

    (20 x 0.1 + 0.02 x 59.9) / 60 is about 0.053 mA.

Summary

  • Sleep modes stop the CPU and peripherals; power-down drops the chip to microamps.
  • Wake with the watchdog timer or an external interrupt; keep ISRs short and shared flags volatile.
  • Average current is the duty-cycle weighted mix of active and sleep current, and it decides battery life.
  • Remove or switch off everything else that draws current: LEDs, regulators, sensors, floating pins.

Next: Debugging Sketches and Managing Memory

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.