When trying to read empty EEPROM hangs the device

As described in https://docs.particle.io/reference/device-os/firmware/electron/#get-
I tried to check if EEPROM is empty using both EEPROM.get and EEPROM.read()

uint16_t val;
  EEPROM.get(add, val);
  if(val==0xFFFF) return "";
uint8_t value = EEPROM.read(int address);
if(value == 0xFF) return "";

If there is something written in EEPROM, both works ok but if I tried to access empty space, the device will stop working.
What is the best way to check if EEPROM at certain address is empty or not.

I’ve experienced this behavior on many photons. My workaround is to write 0b00000000 values to all the byte addresses during commissioning of a new device. Not elegant, but it worked.

Just out of interest, why would you need to explicitly test for empty EEPROM?
The common way would be to read your expected data and just treat the special case when you don’t find valid data.
This would catch the empty case as well as corrupted/overwritten data.

To do that reliably it’s good to have both - a magic number and a checksum - in your dataset.

However, hanging should not appear and maybe @rickkas7 could give this a check.
Meanwhile could you also clarify which device OS version you are running on your Electron?

Hello @ScruffR, thanks for advice.
I was running device os 1.0.1
My intention was to write certain data if that area is empty.
Maybe I should have write all eeprom area as ‘\0’ before accessing any address, however even if my solution is not safe, the device should not reset by itself as you mentioned.

Since there is no such thing as ‘try’ and ‘catch exception’, the device atleast should return something.

“Resetting” the cells to 0x00 is not the best approach as it inevitably means that the next write will have to relocate the EEPROM window as there are no bits that can be written to anymore.
For flash memory bits can only be cleared (set to 0) indidvidually but to set them (1) you’ll need a page erase - this is what causes flash wear.

I haven’t tried it, but what happens when you “initialise” the EEPROM window by writing all 0xFF (“confirm” the value that should be there all along) and then try the code you have above?

With this code my Electron doesn’t block

uint32_t addr = 0;
uint16_t data;

void setup() {
  data = 0xFFFF;
  EEPROM.put(addr, data); // optional (remove/comment when run once)

void loop() {
  Serial.print("loop ");
  EEPROM.get(addr, data);
  addr += sizeof(data);
  Serial.printlnf("%06d: 0x%04x", addr, data);
  if (addr >= EEPROM.length()) {
      addr = 0;

See here

1 Like