🛠 Mode power-down, watchdog et journalisation EEPROM

Arduino Mega 2560 (Rev3) · avance · Schéma : IMG-mega-2560-avance-3-low-power-watchdog-eeprom.svg — cycle de veille de l’ATmega2560 : mesure, écriture dans l’EEPROM 4 Ko en mémoire tampon circulaire, mise en sommeil power-down, réveil par le watchdog

Objectives

Extend the battery life of a data logger: put the ATmega2560 into power-down mode (CPU, clocks, and peripherals off) and wake it up periodically via the watchdog, while logging measurements into the Mega's 4 KB of EEPROM — four times more than on an Uno — as a circular buffer that survives power cuts.

Hardware

Warning: The board's power consumption is not specified by the manufacturer, and the linear regulator as well as the 16U2 USB chip consume power even when the ATmega is asleep. The actual current savings concern the microcontroller alone; for a low-power product, the chip must be powered directly.

Complete Code

// Sommeil power-down + watchdog + journal EEPROM circulaire
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <EEPROM.h>

const uint16_t N_REC = 1024;        // 2 octets/rec -> 2 Ko dédiés
uint16_t slot = 0;

ISR(WDT_vect) { /* réveil seul : rien à faire ici */ }

void setup {
  Serial.begin(115200);
  slot = EEPROM.read(0); slot |= EEPROM.read(1) << 8;
  if (slot >= N_REC) slot = 0;      // curseur de réécriture
  // Watchdog : 2 s, mode interruption (pas de reset)
  MCUSR &= ~(1 << WDRF);
  WDTCSR |= (1 << WDCE) | (1 << WDE);
  WDTCSR = (1 << WDIE) | (1 << WDP1) | (1 << WDP2);  // ~2 s
}

void loop {
  uint16_t v = analogRead(A0);
  EEPROM.update(2 + 2 * slot, (uint8_t)(v & 0xFF));
  EEPROM.update(3 + 2 * slot, (uint8_t)(v >> 8));
  slot = (slot + 1) % N_REC;
  EEPROM.update(0, (uint8_t)(slot & 0xFF));
  EEPROM.update(1, (uint8_t)(slot >> 8));
  Serial.print(F("slot ")); Serial.println(slot);

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable;
  sleep_cpu;          // dort jusqu'au réveil watchdog
  sleep_disable;
}

Expected Verification

The serial monitor displays a slot number every ~2 seconds (the watchdog successfully wakes up the microcontroller). After turning off and back on, the counter resumes where it left off: the EEPROM has retained the cursor and the measurements.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials