Simvik

Energy meter: spread the writes

Pick the next EEPROM slot for the meter's running total so no single cell wears out. A medium embedded C problem (Flash, EEPROM and FRAM), run and graded in…

medium · Flash, EEPROM and FRAM · wear-levelling · eeprom · sequence-numbers · product

Product: Smart electricity meter (Energy)

Requirement. The meter saves its energy total every hour for 20 years: 175,000 writes, more than an EEPROM cell's 100,000-write life. So it rotates through 8 slots, each holding a sequence number and the total.

Return the index of the slot to write next: the one after the slot with the highest sequence number (wrapping from 7 to 0), skipping nothing. Erased slots (sequence 0xFFFFFFFF) are not the newest. If every slot is erased, start at slot 0.

Starter code

int next_write_slot(const slot_t s[8]) {
  for (int i = 0; i < 8; i++)
    if (s[i].seq == 0xFFFFFFFFu) return i;
  return 0;
}

Example tests

A new meter, and its first few hours

slot_t s[8];
for (int i = 0; i < 8; i++) { s[i].seq = 0xFFFFFFFFu; s[i].wh = 0; }
printf("%d ", next_write_slot(s));
for (int i = 0; i < 3; i++) s[i].seq = (uint32_t)(i + 1);
printf("%d\n", next_write_slot(s));

Expected output:

0 3

Once every slot has been written

slot_t s[8];
for (int i = 0; i < 8; i++) { s[i].seq = (uint32_t)(9 + i); s[i].wh = 0; }
printf("%d ", next_write_slot(s));
uint32_t later[8] = { 17, 18, 19, 12, 13, 14, 15, 16 };
for (int i = 0; i < 8; i++) s[i].seq = later[i];
printf("%d\n", next_write_slot(s));

Expected output:

0 3

Learn it first

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