EEPROM emulation in flash
Store key/value settings as records appended to a flash page, and compact them into the other page when it fills. A hard embedded C problem (Flash, EEPROM…
hard · Flash, EEPROM and FRAM · flash · eeprom-emulation · log-structured · power-loss
Many microcontrollers have no EEPROM, so settings live in flash, which cannot be rewritten in place. Each write appends a record to the active page; the newest record for a key wins. Each record is one word: the key in the top 16 bits, the value in the bottom 16 (key 0xFFFF is never used).
ee_read(key, &value): find the newest record forkeyin the active page. Returntrueand setvalue, orfalseif there is none.ee_write(key, value): append the record in the first erased slot of the active page. If the page is full, compact:- copy the newest record of every other key into the other page (which is always erased), then the new record,
- mark the other page valid by writing
PAGE_VALIDto its header, - erase the old page.
If the keys would not fit even after compacting, change nothing and return false. Otherwise return true.
The order of the compaction steps matters: a power cut at any point must leave one valid page with every setting in it. flash_erase records it if you erase the only valid page.
Starter code
bool ee_read(uint16_t key, uint16_t *value) {
int p = ee_active();
for (int i = 1; i < PAGE_WORDS; i++) {
uint32_t w = page[p][i];
if (w != ERASED && (w >> 16) == key) {
*value = (uint16_t)w;
return true;
}
}
return false;
}
bool ee_write(uint16_t key, uint16_t value) {
int p = ee_active();
for (int i = 1; i < PAGE_WORDS; i++) {
if (page[p][i] == ERASED) {
flash_write(p, i, (uint32_t)key << 16 | value);
return true;
}
}
return false;
}Example tests
The newest value of a key wins
ee_format();
ee_write(1, 100);
ee_write(2, 200);
ee_write(1, 101);
show(3);Expected output:
1=101 2=200 3=- page 0 erases 0Fill the page and compact
ee_format();
ee_write(2, 7);
for (uint16_t v = 0; v < 10; v++) ee_write(1, v);
show(3);Expected output:
1=9 2=7 3=- page 1 erases 1Learn it first
- Flash, EEPROM and FRAM · Erase before write, endurance, wear levelling and surviving power loss.
More Flash, EEPROM and FRAM problems
- Program or erase? · Decide whether new data can be programmed over what flash holds now, or needs an erase first.
- A wear-levelled counter · Spread a counter's writes over several slots and find its value again after a reset.
- Energy meter: spread the writes · Pick the next EEPROM slot for the meter's running total so no single cell wears out.