Challenge 2: EEPROM Calibration Storage
Challenge 2: EEPROM Calibration Storage
animation
sensing
calibration
Challenge 2: EEPROM Calibration Storage
A device that loses its coefficients on restart cannot use its last fit. Store the gain and offset, then check that the stored values are valid before using them.
Note
Goal: Persist calibration coefficients so they survive power cycles.
Tasks:
Add the EEPROM library and save the calculated calibration. Load it at startup and check a magic number to detect an uncalibrated state. Add a ‘w’ command to write the calibration and an ‘e’ command to erase it.
#include <EEPROM.h>
// EEPROM addresses
const int EEPROM_MAGIC_ADDR = 0;
const int EEPROM_GAIN_ADDR = 4;
const int EEPROM_OFFSET_ADDR = 8;
const int EEPROM_MAGIC_VALUE = 0xCAFE;
void saveCalibrationToEEPROM() {
EEPROM.begin(64);
EEPROM.put(EEPROM_MAGIC_ADDR, EEPROM_MAGIC_VALUE);
EEPROM.put(EEPROM_GAIN_ADDR, calGain);
EEPROM.put(EEPROM_OFFSET_ADDR, calOffset);
EEPROM.commit();
Serial.println("Calibration saved to EEPROM!");
}
void loadCalibrationFromEEPROM() {
EEPROM.begin(64);
int magic;
EEPROM.get(EEPROM_MAGIC_ADDR, magic);
if (magic == EEPROM_MAGIC_VALUE) {
EEPROM.get(EEPROM_GAIN_ADDR, calGain);
EEPROM.get(EEPROM_OFFSET_ADDR, calOffset);
Serial.println("Calibration loaded from EEPROM");
} else {
Serial.println("No valid calibration found, using defaults");
calGain = 1.0;
calOffset = 0.0;
}
}