Save data in nonvolatile memory

Another approach to EEPROM limits is to use a ring memory, you can then shift around the ring periodically spreading the read/write operations over several addresses. Here's a snippet where I create a 20-byte ring (starting at byte 20 of the EEPROM) during setup using one additional byte (in byte 0) to store the current address of where by data is stored. The data's location shifts around the ring once each time the sketch is started. Here, I am storing 1 byte of data and my worst case guess is that it will be read ten times and written 210 times each day, while the processor will be re-started about 10 times a day. Thus, the byte where the data address is stored will be reliable for 100000/10 days, or 27+ years, and the ring will last 100000*20/220 days, or about 25 years. If your data updates more frequently, you need a bigger ring, and if you need more than 254 cells, your address will need to be stored in 2 bytes instead of 1. (The Serial.print statements are there just so that I can see what happens at startup; they will be gone in actual use. The ring doesn't start at byte 1, but at byte 20, because I will use the low bytes to index other rings.)

  ModeAddress = EEPROM.read (0); // address where Mode value was last stored
  if (ModeAddress == 0){
    Serial.println (F("A Mode value has not yet been stored"));
    ModeAddress = 20;
  }
  else {
    Mode = EEPROM.read (ModeAddress);
    Serial.print (F("Stored Mode = "));
    Serial.print (Mode);
    Serial.print (F(" in byte "));
    Serial.print (ModeAddress);
    ModeAddress = ModeAddress + 1;
//  EEPROM memory ring runs from address 20 through 39
    if (ModeAddress > 39){
      ModeAddress = 20;
    }
  }
  EEPROM.write (0, ModeAddress); // address where Mode will be stored
  EEPROM.write (ModeAddress, Mode); // re-stored in new address
  Serial.print (F("   Mode will now be stored in byte "));
  Serial.println (ModeAddress);

Ciao,
Lenny

1 Like