🛠 Persister une calibration dans l'EEPROM de l'ATmega (512 octets ou 1 Ko)

Arduino Duemilanove — Board Fiche · intermediaire · Schéma : IMG-duemilanove-intermediaire-3-eeprom-persister-calibration.svg — Arduino Duemilanove avec puce ATmega328 dont la zone EEPROM 1 Ko est surlignée, bouton sur broche 2 pour sauvegarder, moniteur série affichant la valeur rechargée après rebranchement de l'alimentation.

Objectives

One of the true joys of the AVR compared to the Due (which has 0 bytes of EEPROM): the Duemilanove includes 512 bytes of EEPROM (ATmega168) or 1 KB (ATmega328), preserved without power. You will store a calibration value in a structure, write it only when it changes (EEPROM has limited write cycles), and verify that it survives a complete power cut.

Hardware

Complete code

// Calibration persistee en EEPROM (bibliothque EEPROM fournie avec le core)
#include <EEPROM.h>

struct Calibration {          // 4 octets
  uint16_t zero;              // offset de calibration
  uint16_t magic;             // marqueur de validite
};
const uint16_t MAGIC = 0xABCD;
const byte BOUTON = 2;

Calibration cal;

void setup {
  pinMode(BOUTON, INPUT_PULLUP);
  Serial.begin(9600);
  EEPROM.get(0, cal);                       // lecture adresse 0
  if (cal.magic != MAGIC) {                 // premiere vie de la carte ?
    cal.zero = analogRead(A0);
    cal.magic = MAGIC;
    EEPROM.put(0, cal);                     // ecriture initiale
    Serial.println("Calibration initialisee");
  } else {
    Serial.print("Calibration rechargee : zero=");
    Serial.println(cal.zero);
  }
}

void loop {
  if (digitalRead(BOUTON) == LOW) {         // bouton enfonce
    delay(50);                              // anti-rebond grossier
    if (digitalRead(BOUTON) == LOW) {
      cal.zero = analogRead(A0);
      EEPROM.put(0, cal);                   // écrit seulement sur demande
      Serial.print("zero enregistre : ");
      Serial.println(cal.zero);
      while (digitalRead(BOUTON) == LOW) { } // attend le relachement
    }
  }
}

Expected verification

First execution: "Calibration initialized". Turn off completely (unplug USB AND power supply), plug back in: the board displays "Calibration reloaded: zero=…" with the previous value, not a reset. Pressing the button with the potentiometer in a different position changes the persisted value. On a 168, the same structure occupies 4 of the 512 available bytes.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials