🛠 Mode power-down et réveil par watchdog (AVR C nu)

Arduino Leonardo — Board Fiche · avance · Schéma : IMG-leonardo-avance-9-leonardo-low-power-powerdown-watchdog.svg — Leonardo sur batterie en sommeil profond, puce ATmega32u4 endormie et chiot-chien de garde (watchdog) la réveillant toutes les ~2,1 s

Objectives

Optimize the power consumption of the ATmega32u4 in bare-metal AVR C: switch the core to power-down mode (deep sleep, hardware clocks stopped) and wake it up periodically using the watchdog timer configured in interrupt mode (~2.1 s). This is the foundation of any battery-powered project. Specific warning for the Leonardo: the USB transceiver connected to a host consumes power continuously; to measure true sleep current, unplug the USB cable or cut the VBUS line.

Hardware

Complete code

/* Sommeil power-down + reveil watchdog ~2,1 s — ATmega32u4
 * Build : avr-gcc -mmcu=atmega32u4 -Os sleep.c -o sleep.elf
 * Flash  : avrdude par ICSP, ou outils avr109 via Caterina. */
#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>

ISR(WDT_vect) {
  PINB = (1 << PINB7); // bascule la LED D13 a chaque reveil
}

int main(void) {
  DDRB |= (1 << DDB7);            // PB7 (D13) en sortie

  MCUSR &= ~(1 << WDRF);          // efface la cause de reset
  WDTCSR |= (1 << WDCE) | (1 << WDE);      // sequence de modification
  WDTCSR = (1 << WDIE) | (1 << WDP2) | (1 << WDP1) | (1 << WDP0); // ~2,1 s, mode interruption

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);     // sommeil le plus profond
  sleep_enable;
  sei;

  while (1) {
    sleep_cpu;      // le coeur s'arrete ; le watchdog le reveille
    sleep_disable;  // securite : on ne dort qu'un cycle a la fois
    sleep_enable;
  }
}

Expected verification

The LED blinks approximately every 2.1 s (the toggle occurs in the watchdog ISR, then the core goes back to sleep). Insert an ammeter in series with the power supply, with USB disconnected: the average current drops drastically compared to normal operation, as most of the time is spent in power-down. The official datasheet does not provide a typical current value (check the Microchip ATmega32u4 datasheet for precise figures).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials