5 V0 VMCUATmega328PSRAM minutesEEPROM · 1,024 bytes · ring of 4slot 0–slot 1–slot 2–slot 3–1void save(uint16_t n) {2 Rec r = {++seq, n};3 r.crc = crc16(r);4 slot = (slot + 1) % 4;5 EEPROM.put(slot * 8, r);6}765432100101010101010101flash · one byte36414441put
Back: the meter's board (battery, microcontroller with SRAM, EEPROM ring of 4 slots)Front: the save() code card and one byte of flash as 8 bit lampsTokens: values being saved and restored, writes, and CRC checksA pump run-time meter on an Arduino Uno R3: SRAM loses minutes = 36 when the battery is pulled, so save() copies each total into the ATmega328P's EEPROM as an 8-byte record with a sequence number and a CRC. Writes go round a ring of 4 slots to spread the wear (100,000 cycles per cell); flash is erased in blocks and a write can only clear bits. When a power cut tears record #3, the CRC check at start-up skips it and the meter resumes from #2: 41 minutes.

Keeping a value

  1. 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.

Wear and flash

Surviving a power cut

What happens

;; step 1/8 · volatile
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

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 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.