Storing settings in Flash and EEPROM
Values that must survive power-off go to Flash or EEPROM. Sector erase, write endurance, and a storage scheme that is safe against power loss.
Properties of Flash
- It must be erased before writing, and the erase unit is a sector (a few KB up to 128 KB)
- Erasing sets every bit to 1; writing can only change 1 to 0
- Write/erase endurance is around 10,000 cycles
- During an erase (tens of ms up to 1 s), code execution from the same bank may stall
A safe storage pattern
- Reserve two dedicated sectors outside the code area in the linker script
- Store the data with a version number and a CRC
- Write new values to the other sector (or to a free slot in the same sector), and read back the newest record whose CRC is valid
- When a sector fills up, move to the other sector and erase the previous one
This way the old value survives if power is lost during a write, and wear is spread out. ST's EEPROM emulation application note uses this method.
External EEPROM / FRAM
An I2C EEPROM is written byte by byte and lasts on the order of a million cycles. FRAM has practically unlimited endurance and writes complete instantly, which suits values that change often (distance travelled, hours of use).