A wear-levelled counter
Spread a counter's writes over several slots and find its value again after a reset. A medium embedded C problem (Flash, EEPROM and FRAM), run and graded in…
medium · Flash, EEPROM and FRAM · eeprom · wear-levelling · power-loss
A boot counter is incremented on every start. EEPROM cells survive only a limited number of writes, so the counter is spread over SLOTS slots: each increment writes the new value into the slot after the one holding the current value, wrapping around. Slots that were never written read as ERASED.
counter_read()returns the current value: the largest value in any written slot, or 0 if all slots are erased.counter_increment()writes the current value plus 1 into the next slot, usingee_write. When every slot is erased, the first write goes to slot 0.
The device can reset at any time, so keep no state in RAM: work everything out from ee.
Starter code
uint32_t counter_read(void) {
return ee[0] == ERASED ? 0 : ee[0];
}
void counter_increment(void) {
ee_write(0, counter_read() + 1);
}Example tests
Ten boots from a new EEPROM
erase_all();
show();
for (int i = 0; i < 10; i++) counter_increment();
show();Expected output:
value 0, writes 0 0 0 0
value 10, writes 3 3 2 2Learn 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.
- 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.
- Energy meter: spread the writes · Pick the next EEPROM slot for the meter's running total so no single cell wears out.