Sub topic 12
Saving Small Values in EEPROM
This chapter assumes you can upload a sketch, use the Serial Monitor, and read basic C++ (structs, pointers, arrays). It also assumes you know the difference between flash, SRAM and EEPROM from the first chapter. The examples target an AVR board such as the Uno, which has 1 KB of EEPROM. The ATmega328P chip on the Uno has 1024 bytes, so valid addresses run from 0 to 1023.
Why EEPROM belongs in a memory chapter
SRAM is small and loses its contents when power is removed. Flash holds your program and its constant data, but your running sketch cannot treat it as ordinary writable storage. EEPROM fills the gap. It is a small block of non-volatile memory that your sketch can read and write byte by byte, and its contents survive resets and power cycles.
Typical uses are:
- Calibration offsets for a sensor.
- User settings such as a blink interval or a mode number.
- A boot counter or a "last known state".
- A small identifier or serial number written once.
EEPROM is a poor fit for logging streams of readings. It is tiny, and it wears out, as described below.
Wear and timing
Each EEPROM cell is rated for roughly 100,000 write/erase cycles on AVR chips. Reads are unlimited. The limit applies to each individual cell, so one byte written every second would pass 100,000 writes in about 28 hours. A byte written once per day would last centuries.
Two consequences follow:
- Never write to EEPROM from
loop()on every pass without a guard. - Write only when the value has actually changed.
Writes are also slow. While a write is in progress, the hardware is busy, and a long run of writes can delay time-critical code. Writing a 10-byte struct takes about 33 ms.
The EEPROM library basics
The EEPROM library ships with the Arduino AVR core. Include it with #include <EEPROM.h>. The main functions are:
| Function | Purpose |
|---|---|
| `EEPROM.read(addr)` | Read one byte at `addr`. |
| `EEPROM.write(addr, value)` | Write one byte. Always performs the write. |
| `EEPROM.update(addr, value)` | Write one byte only if it differs from what is stored. |
| `EEPROM.put(addr, obj)` | Write any object (int, float, struct) starting at `addr`. Uses `update` internally. |
| `EEPROM.get(addr, obj)` | Read an object of the same type from `addr`. |
| `EEPROM.length()` | Number of bytes available (1024 on an Uno). |
EEPROM.put() is convenient because it skips bytes that are already correct. That means calling it repeatedly with unchanged data does not wear the cells. EEPROM.write() has no such check, so prefer update() or put().
Storing a struct
The chapter's basic example stores a small settings struct and reads it back:
#include <EEPROM.h>
struct Settings {
uint16_t interval;
uint8_t mode;
};
void setup() {
Serial.begin(9600);
Settings s = {1000, 2};
EEPROM.put(0, s);
Settings loaded;
EEPROM.get(0, loaded);
Serial.println(loaded.interval);
}
void loop() {
}put() writes sizeof(Settings) bytes starting at address 0. On AVR that is 3 bytes: two for interval and one for mode. get() copies the same number of bytes back into loaded. Because the type is known at compile time, you do not pass a length.
Run it and the Serial Monitor prints 1000. Power-cycle the board and run a sketch that only calls get(), and it prints 1000 again. The value survived.
Tracking addresses
If you store several items, you must keep their addresses from overlapping. Hard-coded numbers such as EEPROM.put(0, a) and EEPROM.put(2, b) break the moment a changes size. A safer pattern advances an address by the size of each item:
#include <EEPROM.h>
struct Calibration {
float offset;
float scale;
};
const int ADDR_CAL = 0;
const int ADDR_COUNT = ADDR_CAL + sizeof(Calibration);
void setup() {
Serial.begin(9600);
Calibration cal = {0.25f, 1.02f};
EEPROM.put(ADDR_CAL, cal);
uint16_t bootCount;
EEPROM.get(ADDR_COUNT, bootCount);
bootCount++;
EEPROM.put(ADDR_COUNT, bootCount);
Serial.print(F("Boots: "));
Serial.println(bootCount);
}
void loop() {
}Here ADDR_COUNT is derived from the size of the preceding item, so changing Calibration moves the counter automatically. Note the catch in this sketch: on a brand-new chip, bootCount starts from whatever the cells contain, which is usually 0xFFFF. The next section addresses that.
Handling first boot: unprogrammed EEPROM
A new or erased AVR EEPROM reads 0xFF in every byte. A uint16_t read from it is 65535, and a float read from it is not a valid number (it is NaN). If your sketch trusts the stored data blindly, it will start with nonsense values.
The standard fix is a marker, often called a magic number, stored next to the data. On startup you check the marker. If it is missing, you write defaults.
#include <EEPROM.h>
struct Settings {
uint8_t magic;
uint16_t interval;
uint8_t mode;
};
const uint8_t MAGIC = 0xA5;
const int ADDR_SETTINGS = 0;
Settings settings;
void loadSettings() {
EEPROM.get(ADDR_SETTINGS, settings);
if (settings.magic != MAGIC) {
settings.magic = MAGIC;
settings.interval = 1000;
settings.mode = 1;
EEPROM.put(ADDR_SETTINGS, settings);
Serial.println(F("Defaults written"));
} else {
Serial.println(F("Settings loaded"));
}
}
void setup() {
Serial.begin(9600);
loadSettings();
Serial.print(F("Interval: "));
Serial.println(settings.interval);
}
void loop() {
}The first run prints "Defaults written". Every later run prints "Settings loaded". If you later change the layout of Settings, change the magic value too (or add a version byte). Otherwise old data will be misread as the new layout.
For data that matters more, store a checksum or CRC of the struct alongside it. A simple magic byte catches blank memory but not partial corruption, such as power loss in the middle of a write.
Writing only when something changed
A common mistake is saving a setting every time loop() runs. A better pattern keeps the working copy in SRAM and saves only on a change event, such as a button press:
#include <EEPROM.h>
const int ADDR_MODE = 0;
uint8_t mode;
void setup() {
Serial.begin(9600);
mode = EEPROM.read(ADDR_MODE);
if (mode > 3) {
mode = 0;
}
Serial.print(F("Mode: "));
Serial.println(mode);
}
void changeMode() {
mode = (mode + 1) % 4;
EEPROM.update(ADDR_MODE, mode);
}
void loop() {
if (Serial.available() > 0) {
Serial.read();
changeMode();
Serial.print(F("Mode: "));
Serial.println(mode);
}
}Send any character from the Serial Monitor to advance the mode. The new value is saved only at that moment. The range check after read() handles the blank-EEPROM case, since 0xFF is greater than 3.
Edge cases and gotchas
- Struct padding. On 8-bit AVR, structs are not padded, so sizes are predictable. On 32-bit boards the compiler may insert padding bytes, so the same struct can be larger there.
- Pointers do not survive.
put()copies the bytes of the object. If the struct holds a pointer, only the address is stored, which is meaningless after a reset. AStringobject has the same problem, so store achararray instead. - Brown-out during a write. If power fails mid-write, the data may be half old and half new. A checksum detects this.
- Layout changes. Reordering struct members changes where each value sits. Use a version byte and migrate or reset.
- Other boards. The Uno has 1 KB, the Mega 2560 has 4 KB, and the Nano Every and some other boards emulate EEPROM differently. Boards such as the ESP8266 and ESP32 need
EEPROM.begin(size)andEEPROM.commit(). Check your board's core documentation before reusing code. - Erase on upload. Normal uploads leave EEPROM alone unless the EESAVE fuse has been cleared. Burning a bootloader or using some programmers can wipe it.
How EEPROM fits the memory budget
EEPROM costs no SRAM beyond the variables you copy values into. The library code does occupy some flash. A struct read with get() into a global adds its size to static SRAM, so reading a large block you only need briefly is better done into a local variable or a byte at a time.
Summary of good practice
- Keep a working copy of each setting in SRAM and read EEPROM at startup.
- Use
update()orput()so unchanged bytes are not rewritten. - Save on events, never on every loop pass.
- Add a magic number or version so blank or outdated data is detected.
- Compute addresses from
sizeofinstead of typing numbers. - Add a checksum when corrupted data would cause harm.
Exercise
A sketch calls EEPROM.write(10, counter) once per loop pass, and loop() runs about 100 times per second. Roughly how long until the cell at address 10 reaches its rated 100,000 write cycles, and what two changes would fix the problem?
Show answer
At 100 writes per second, 100,000 writes take 1,000 seconds, about 17 minutes. The fix is to write only when the value changes (use EEPROM.update() instead of write()) and to save on an event or at a limited rate, such as when the user changes a setting or once per minute, keeping the working value in SRAM in between.
Exercise
You add a new uint8_t field at the start of a stored Settings struct and re-upload. Existing boards now show strange values after boot. Why, and how do you prevent it?
Show answer
The old bytes in EEPROM were written with the old layout, so every field is now read from the wrong offset. Prevent it by storing a magic number or version byte with the struct, checking it at startup, and writing defaults (or migrating the old data) when it does not match the current version.
Exercise
Why does reading a float with EEPROM.get() from a brand-new Uno give an unusable value, and how would you detect that case?
Show answer
Unprogrammed EEPROM cells read 0xFF, so the four bytes of the float are all 0xFF, which is a NaN (not a valid number). Detect it by testing with isnan(), or better, by checking a magic marker stored beside the data before trusting any value.