Simvik

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 for key in the active page. Return true and set value, or false if 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_VALID to 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 0

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

Learn it first

More Flash, EEPROM and FRAM problems