Saving data in EEPROM and flash
About this lesson
SRAM forgets everything the moment the battery goes, so a device that must remember a count, a setting or a calibration copies it into non-volatile memory. Follow a pump run-time meter on an Arduino Uno R3 as it saves its total into the ATmega328P's 1,024-byte EEPROM: why each cell wears out after about 100,000 writes, how a ring of slots spreads the wear, why flash must be erased in blocks before it is written, and how a sequence number and a CRC let the firmware survive a power cut in the middle of a write. The lesson “Brown-out, resets and fault handling” explains what happens to the chip when the supply sags; this one is about keeping your data through it.
SRAM forgets at power off
A pump's run-time meter counts minutes in a variable: minutes = 36. Variables live in SRAM, which needs power to hold its bits. Pull the battery and the 36 is gone: at the next start-up the meter reads 0.
minutes = 36 in SRAM, the chip's working memory SRAM needs power to hold each bit power off -> every bit lost power on -> globals start at 0: minutes = 0 the pump really ran 36 minutes; the meter forgot
Read the lesson step by step
SRAM forgets at power off
A pump's run-time meter counts minutes in a variable: minutes = 36. Variables live in SRAM, which needs power to hold its bits. Pull the battery and the 36 is gone: at the next start-up the meter reads 0.
minutes = 36 in SRAM, the chip's working memory SRAM needs power to hold each bit power off -> every bit lost power on -> globals start at 0: minutes = 0 the pump really ran 36 minutes; the meter forgotEEPROM keeps it
EEPROM keeps its bytes with the power off: 1,024 bytes on the ATmega328P. When the pump stops, save() writes an 8-byte record into slot 0. Each byte takes about 3.3 ms, so the record takes about 26 ms.
line 5 EEPROM.put(slot * 8, r); slot 0, address 0 record struct Rec { uint32_t seq; uint16_t count; uint16_t crc; } seq sequence number: counts the saves · crc check value (step 7) #1 seq 1 count 36 crc 0xca1a bytes 01 00 00 00 24 00 1a ca time 8 bytes x 3.3 ms = 26.4 ms EEPROM 1,024 bytes, kept with no powerEach cell wears out
Every write wears an EEPROM cell a little, and the datasheet promises 100,000 write/erase cycles. Save once a minute into the same slot and it is used up in about 69 days. EEPROM.put skips bytes that have not changed, which helps a little.
endurance 100,000 write/erase cycles per cell one save a minute = 1,440 writes a day 100,000 / 1,440 = 69.4 days EEPROM.put uses EEPROM.update: an unchanged byte is not rewritten but seq changes every save, so its low byte is always writtenSpread the writes round a ring
So each save moves to the next slot, round a ring of 4. Its sequence number, a save counter stamped on it, grows by one. At 41 minutes record #2 goes to slot 1. 4 slots last 4 times longer; 128 slots, about 24 years.
line 2 Rec r = {++seq, n}; seq 1 -> 2 line 4 slot = (slot + 1) % 4; slot 0 -> 1 #2 seq 2 count 41 crc 0x691e ring of 4 277.8 days at one save a minute whole EEPROM 1,024 / 8 = 128 slots -> 24.3 years this is wear levellingFlash: erase, then write
Flash is bigger but erases in blocks: 128 bytes on the ATmega328P, 4,096 on an ESP32. Erasing sets every bit to 1; writing can only clear bits to 0, so 41 cannot become 44 in place. On an ESP32, Preferences manages this for you.
erase every bit -> 1 1111 1111 (0xff) write 41 clear bits 0010 1001 then 44 needs a 0 -> 1 0010 1100 not allowed blocks ATmega328P: 128-byte pages · ESP32: 4096-byte sectors endurance ATmega328P flash 10,000 cycles (EEPROM 100,000) ESP32 Preferences (NVS) appends records and erases whole sectors later, spreading the wearPower fails mid-write
The pump stops at 44 minutes and record #3 starts into slot 2. After 4 of its 8 bytes, about 13 ms in, the battery is pulled. Slot 2 now holds the new sequence number but a blank count and check value: a torn record.
#3 wants 03 00 00 00 2c 00 1c e8 written 03 00 00 00 ff ff ff ff 4 bytes x 3.3 ms = 13.2 ms, then no power slot 2 seq 3 count 65535 crc 0xffff the datasheet only promises a byte in progress finishes if the voltage holds (use the Brown-out Detector); a record is 8 bytes either wayCheck every slot at start-up
At power on, load() reads each slot and works out the CRC, a check value computed from the other 6 bytes. Slots 0 and 1 match their stored CRC. Torn slot 2 and empty slot 3 do not, so they are ignored.
slot 0 crc16 = 0xca1a stored 0xca1a ok slot 1 crc16 = 0x691e stored 0x691e ok slot 2 crc16 = 0x9801 stored 0xffff bad slot 3 crc16 = 0x9401 stored 0xffff bad crc16 = avr-libc _crc16_update, start 0xFFFFThe newest good record wins
Of the good records, #2 has the highest sequence number, so minutes = 41 comes back into SRAM, and the next save goes to slot 2. The power cut cost 3 minutes of counting, not all 44.
good #1 (36) #2 (41) newest #2 in slot 1 load() seq = 2, slot = 1, minutes = 41 next save -> slot 2, overwriting the torn record lost 44 - 41 = 3 minutes
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Why does the meter read 0 after the battery is pulled, even though the pump ran 36 minutes?
SRAM needs power to hold its bits. At the next start-up the global variable starts again at 0, so anything not copied into EEPROM or flash is gone.
02An EEPROM cell is rated for 100,000 write/erase cycles. Saving once a minute into the same cell, roughly how long does it last?
One save a minute is 1,440 writes a day, and 100,000 / 1,440 ≈ 69 days. Spreading the same saves over all 128 slots of the 1,024-byte EEPROM stretches that to about 24 years.
03A flash byte holds 41 (0b00101001). Why can't you write 44 (0b00101100) over it directly?
Erasing sets every bit of a block to 1, and a write can only clear bits. 44 needs bit 2 set where 41 has a 0, so the block would have to be erased first. Libraries such as ESP32 Preferences (NVS) avoid this by writing the new value somewhere else and erasing old blocks later.
04The power fails after 4 of a record's 8 bytes have been written. How does load() avoid using that record?
A torn record holds a mix of new and old bytes, so its stored check value no longer matches the one computed from its contents. load() ignores it and keeps the newest record whose CRC matches.
05After the power cut the ring holds #1 (36), #2 (41), a torn #3 and an empty slot. What does the meter resume from?
#2 is the record with the highest sequence number among those whose CRC matches, so minutes = 41. Only the 3 minutes of the run that was being saved are lost.
Glossary
- Non-volatile memory
- Memory that keeps its contents with the power off, such as EEPROM and flash. SRAM is volatile: it forgets at power off.
- EEPROM
- Electrically erasable programmable read-only memory: non-volatile memory you can write one byte at a time. The ATmega328P has 1,024 bytes of it.
- Flash memory
- Larger non-volatile memory that is erased in whole blocks (pages or sectors). Erasing sets every bit to 1; writing can only clear bits to 0.
- Endurance
- How many write/erase cycles a memory cell is guaranteed to survive before it may start to fail.
- Wear levelling
- Spreading writes over many cells, for example round a ring of slots, so that no single cell wears out early.
- Torn write
- A multi-byte write cut off part way, for example by a power cut, leaving a record that mixes new and old bytes.
- CRC (cyclic redundancy check)
- A check value computed from a block of data and stored with it. Recomputing it later shows whether the data changed or was only partly written.
- Sequence number
- A counter stored in each record that grows by one with every save, so the firmware can tell which record is the newest.
Notes and sources
- On the ATmega328P the SRAM, the EEPROM and the flash are all inside the one chip; the figure draws them apart. The Arduino Uno R3 keeps your program in the 32 KB of flash.
- The card shows only save(). The whole sketch also defines the Rec struct, crc16() using avr-libc's _crc16_update, load() that runs at power on, and a loop() that counts the minutes while pin 2 is HIGH and calls save() when the pump stops.
- The datasheet advises enabling the Brown-out Detector so the chip is held in reset while the supply is too low, and says a byte write already in progress still completes if the voltage is enough. That protects one byte, not an 8-byte record, which is why the record carries a CRC.
- The 100,000-cycle figure is the datasheet's minimum endurance per cell. The day counts assume one save a minute, every minute; a meter that saves only when the pump stops lasts much longer. The datasheet also gives data retention of 20 years at 85 °C and 100 years at 25 °C.
- Flash numbers: the ATmega328P erases and writes its flash in 128-byte pages (64 words); ESP32 boards use external SPI NOR flash with 4096-byte erase sectors. Arduino-ESP32's Preferences library stores data in NVS, which appends new values and erases whole pages later.
- A CRC catches a torn record with very high probability, not certainty. The sequence number is 32 bits, so it cannot wrap round in the life of the EEPROM.
- Microchip ATmega48A/PA/88A/PA/168A/PA/328/P datasheet (DS40002061B): endurance, EEPROM programming time, preventing EEPROM corruption, flash page size
- Arduino docs: EEPROM library (size, 3.3 ms write, 100,000 cycles, put and update)
- ArduinoCore-avr: EEPROM library README (put only rewrites changed cells)
- avr-libc user manual: <util/crc16.h>, _crc16_update
- ESP-IDF: SPI flash API (4096-byte sectors, NOR flash writes only 1 to 0)
- ESP-IDF: Non-Volatile Storage library (NVS)
- Arduino-ESP32: Preferences tutorial
Quiz Unlocks after the last step.