EEPROM Storing and Getting Struct Problems

I’m trying to store a struct full of preferences and I can read each value fine (through the testString, which is a particle variable) until I get to the DSTRule. The DSTRule and alarmTimes do not show so I don’t think they are being stored (or retrieved). I’ve included the relevant code below; any help as to why this is occurring would be greatly appreciated.

struct Preferences {
  int version;
  int timeZone; //UTC time zone offset
  int hourFormat; //12 or 24
  int piezoHertz; //Piezo alarm frequency
  int LEDCurrent; //LED current rating (in mA)
  int ledBrightness; //Maximum brightness (0 to 100%)
  String DSTRule; //US, EU, or OFF
  std::vector<std::vector<int>> alarmTimes; // {hour, minute, second, isOnce, light, sound, dayOfWeek, del}
};

Preferences preferences;
  //EEPROM.clear();
  testString = "zo";
  EEPROM.get(0, preferences);
  testString += "get";
  if(preferences.version != 0) {
    std::vector<std::vector<int>> alarmTimes;
    preferences = {0, -8, 12, 2000, 700, 100, "US", alarmTimes};
    EEPROM.put(0, preferences);
    testString += "put";
  }
  testString += preferences.timeZone;
  testString += preferences.hourFormat;
  testString += preferences.piezoHertz;
  testString += preferences.LEDCurrent;
  testString += preferences.ledBrightness;
  testString += preferences.DSTRule;
  testString += preferences.alarmTimes;

A String object does not actually contain the string but only a pointer the the dynamically allocated heap space.
If you want to put a string in your struct, you should use char[].

A similar thing goes for vectors and other objects using dynamic memory.
For these you’d need some way of serialising/deserialising.

1 Like

If you really only have three values for DSTRule, I’d use an enum instead of a string. And use a fixed 8-element array instead of a vector for alarmTimes.

enum DSTRule { DST_US, DST_EU, DST_OFF};

struct Preferences {
  int version;
  int timeZone; //UTC time zone offset
  int hourFormat; //12 or 24
  int piezoHertz; //Piezo alarm frequency
  int LEDCurrent; //LED current rating (in mA)
  int ledBrightness; //Maximum brightness (0 to 100%)
  DSTRule dstRule; //DST_US, DST_EU, or DST_OFF
  int alarmTimes[8]; // {hour, minute, second, isOnce, light, sound, dayOfWeek, del}
};
2 Likes