🛠 Mode power-down, watchdog et journalisation EEPROM
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
- 1 × Arduino Mega 2560 + USB cable (for testing)
- 1 × sensor on A0 (potentiometer for testing)
- Battery or 7–12 V jack power supply for autonomy measurements
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
- Using
Serial.printaftersleep_cpuwithout resetting: the UART resumes normally, but many forgetsleep_disable, causing the second sleep to occur before the measurement. - Configuring the watchdog in reset mode: the board restarts instead of waking up; the EEPROM buffer survives, but the RAM is lost.
- Writing to the EEPROM in every loop even when the value doesn't change:
EEPROM.updateavoids unnecessary writes, which is crucial for endurance. - Believing that the entire board consumes less than 100 µA: the 16U2 and the regulator do not sleep along with the ATmega.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino