EEPROM technique

Hi all,
I’m trying to write an integer to EEPROM but have intermittent issues when I go to read it back. Below is the basic of what I’m trying to do:

int NextFeedTimeHr;    // values from 1 to 23
int NextFeedTimeMin;  // values 0 to 59


void setup(){
    EEPROM.get(1, NextFeedTimeHr);
    EEPROM.get(2, NextFeedTimeMin);
}

void loop(){
    //do stuff then go to Set_Feed_Time() to change next feed time.....(only happens twice a day)
}

void Set_Feed_Time() {
    EEPROM.put(1, NextFeedTimeHr);
    EEPROM.put(2, NextFeedTimeMin);
 }

Occasionally the value gets corrupted sometimes and i get a random large positive/negative number or it will not save to memory at all. Any suggestions?

FYI i just pull all power to the module and plug it back in to test to see if values will load back up correctly.

Thanks,
-Jp-

An int needs four bytes, but with your addresses 1 and 2 your integers are overlapping.

Either store your values in one-byte types like uint8_t or use addresses that allow for enough seperation like

  EEPROM.put(0, intOne);
  EEPROM.put(4, intTwo);

Or use a struct and store that as a single entity.

1 Like

To expand on @ScruffR’s answer, I usually use a struct with a version field so I know when to initialize the storage.

const int currentVersion = 10;
struct {
  int version;
  int NextFeedTimeHr;    // values from 1 to 23
  int NextFeedTimeMin;  // values 0 to 59
} storage;

void setup() {
  EEPROM.get(0, storage);
  if (storage.version != currentVersion) {
    storage.version = currentVersion;
    storage.NextFeedTimeHr = 18;
    storage.NextFeedTimeMin = 0;
    saveStorage();
  }
}

void loop() {
  // do stuff and call saveStorage() to persist data
}

void saveStorage() {
  EEPROM.put(0, storage);
}
4 Likes

Thank you both for your replies!