Simvik

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:

  • 0 if they are already identical,
  • 1 if data can be programmed directly (every change is a 1 becoming 0),
  • 2 if 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: 0

Clearing 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: 2

Learn it first

More Flash, EEPROM and FRAM problems