Program or erase?
Decide whether new data can be programmed over what flash holds now, or needs an erase first. An easy embedded C problem (Flash, EEPROM and FRAM), run and…
easy · Flash, EEPROM and FRAM · flash · bits
Erasing flash sets every bit to 1. Programming can only clear bits, from 1 to 0; turning a 0 back into a 1 needs an erase of the whole sector. Drivers check this before writing, to skip writes that change nothing and avoid erases that are not needed.
Write flash_check(cur, data, n), comparing n bytes of what flash holds now (cur) with what should be there (data). Return:
0if they are already identical,1ifdatacan be programmed directly (every change is a 1 becoming 0),2if any bit must go from 0 to 1, so the sector must be erased first.
Starter code
int flash_check(const uint8_t *cur, const uint8_t *data, size_t n) {
for (size_t i = 0; i < n; i++)
if (cur[i] != data[i]) return 1;
return 0;
}Example tests
Erased flash, then the same data again
uint8_t erased[3] = { 0xFF, 0xFF, 0xFF };
uint8_t data[3] = { 0x12, 0x34, 0x56 };
check("erased", erased, data, 3);
check("same", data, data, 3);Expected output:
erased: 1
same: 0Clearing a bit and setting a bit
uint8_t cur[3] = { 0x12, 0x34, 0x56 };
uint8_t clear[3] = { 0x12, 0x30, 0x56 };
uint8_t set[3] = { 0x12, 0x36, 0x56 };
check("clear", cur, clear, 3);
check("set", cur, set, 3);Expected output:
clear: 1
set: 2Learn it first
- Flash, EEPROM and FRAM · Erase before write, endurance, wear levelling and surviving power loss.
More Flash, EEPROM and FRAM problems
- 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.
- Energy meter: spread the writes · Pick the next EEPROM slot for the meter's running total so no single cell wears out.