You built a thermostat set with two buttons, and the user set it to 25 °C. The power went off and came back, and the number returned to the value in the code. Ordinary variables in RAM are wiped when the power goes off. The fix is to save the important values in memory that isn't wiped.
Types of memory in a microcontroller
| Memory | On the Uno | Wiped with the power? | What's in it |
|---|---|---|---|
| Flash | 32 KB | No | The code itself |
| SRAM | 2 KB | Yes | Variables while running |
| EEPROM | 1 KB | No | Settings you want to remember |
Flash is written only when you upload code, and RAM is lost with the power, so EEPROM is the natural place for settings.
EEPROM on the Arduino Uno
- A capacity of 1024 bytes (the Nano is the same, and the Mega has 4 KB).
- Each cell withstands about 100,000 writes, and reading has no limit.
- Writing a byte takes about 3.3 ms, so it's no place for fast writing.
#include <EEPROM.h>
struct Settings {
int targetTemp;
byte mode;
};
Settings s;
void setup() {
EEPROM.get(0, s); // read from address 0
if (s.targetTemp < 5 || s.targetTemp > 40) {
s = {25, 1}; // first run: default values
}
}
void saveSettings() {
EEPROM.put(0, s); // writes only the bytes that changed
}
The functions
| Function | What it does |
|---|---|
EEPROM.read(addr) and write(addr, b) | One byte |
EEPROM.update(addr, b) | Writes only if the value changed |
EEPROM.get(addr, x) and put(addr, x) | Any type (int, float or struct) |
Saving all the settings in a single struct is far easier than working out each variable's address by hand. And if you're saving two different things, sizeof(s) tells you how many bytes the struct takes, so you start the second one after it.
The first run: a magic number
A new EEPROM is usually all 255 (0xFF). So check that the value you read is sensible, as in the example, or save a "magic number" in the first byte that tells you the data has been saved before:
const byte MAGIC = 0x42; // change it when you change the struct's layout
void setup() {
if (EEPROM.read(0) != MAGIC) {
s = {25, 1}; // default values
EEPROM.put(1, s);
EEPROM.write(0, MAGIC);
} else {
EEPROM.get(1, s);
}
}
The extra benefit: if you add a new variable to the struct in a new version of the code, change the magic number, so the device starts with default values instead of misreading old data.
Preserving its life
100,000 writes is a big number, unless you write inside the loop:
| Writing every | The cell wears out after roughly |
|---|---|
| Second | A day |
| Minute | 69 days |
| Hour | 11 years |
| User change | Practically never |
- Write only when the value changes (
putandupdatedo this for bytes). - If a value changes often (a counter, for example), save it at intervals or when the user finishes adjusting.
Save once the user has finished
The user presses the button 10 times to get from 25 to 35. Don't write 10 times: wait until they stop pressing for a few seconds, and write once with millis:
bool dirty = false;
unsigned long tChange = 0;
void onButton() { // called when the user changes the value
s.targetTemp++;
dirty = true;
tChange = millis();
}
void loop() {
if (dirty && millis() - tChange > 5000) {
EEPROM.put(1, s);
dirty = false;
}
}
A counter that changes often
If you're counting something (a motor's running hours, for example), spread the writes: save in a different slot each time, rotating over 10 slots, so the lifespan is multiplied by 10. Add a sequence number so you know which slot is the newest when the device starts.
The power went off while it was writing?
If the power goes off in the middle of a write, half the struct may be new and half old. Simple protection: calculate a checksum and save it with the data, and compare it when you read. If it differs, fall back to the default values:
byte checksum(const Settings& x) {
const byte* p = (const byte*)&x;
byte c = 0;
for (size_t i = 0; i < sizeof(x); i++) c ^= p[i];
return c;
}
ESP32: the Preferences library
The ESP32 has no real EEPROM. It saves to part of the flash, and the easiest way is the Preferences library (which uses NVS):
#include <Preferences.h>
Preferences prefs;
void setup() {
prefs.begin("app", false);
int t = prefs.getInt("temp", 25); // 25 if it doesn't exist
prefs.putInt("temp", 26);
prefs.end();
}
It saves by name instead of address, and spreads writes across the flash so it lasts longer. But still, don't write every moment.
- There are functions for each type:
putFloat,putBoolandputString, andgetString("ssid", "")for a network name, for example. - Names (the namespace and the key) are 15 characters at most.
prefs.remove("temp")deletes a key, andprefs.clear()deletes the whole namespace.
A well-known mistake: the EEPROM library on the ESP32
The EEPROM.h library exists on the ESP32 as an emulation, but it needs two lines that many people forget:
EEPROM.begin(64); // in setup: reserve 64 bytes
EEPROM.put(0, s);
EEPROM.commit(); // without it, nothing is actually saved
If you forget commit(), everything will seem to work until the first power cut. That's why Preferences is easier and safer on the ESP32.
Large data?
For large logs (sensor readings all day long) use an SD card or send them to the internet. See ESP32 web server. The ESP32 also has LittleFS: a file system on the flash where you write ordinary text files.
Common mistakes
| Problem | Usual cause |
|---|---|
| Strange numbers on the first run (-1 or 255) | Empty EEPROM and no default values |
| Settings aren't saved on the ESP32 | You forgot EEPROM.commit() |
| The numbers got mixed up after editing the code | The struct's layout changed; change the magic number |
| The device became slow | EEPROM writes inside the loop |
| After months, saving stopped working | The cell wore out from too many writes |
FAQ
Does uploading new code erase the EEPROM? On the Uno, no, the values remain. On the ESP32, Preferences remain unless you enable "Erase All Flash" when uploading.
How do I know the data was written correctly? Read it back after writing and print it on the Serial Monitor, or use the checksum above.