Writing struct to EEPROM doesn't work with strings inside it

I'm trying to save an array of structures in the EEPROM memory. The 0 address is the flag, if there was nothing written to it previously, the default values are set and written to the EEPROM memory using EEPROM.put. I then used EEPROM.get to get the saved data back, which I then print to the serial monitor to see that it saved correctly. If I reset the arduino, the flag is set so it reads all of the structures from the EEPROM. After printing these to the serial monitor, the name strings come back as gibberish. Any help would be greatly appreciated. Thanks in advance.

#include <EEPROM.h>

struct member{                        //structure for each user
  String name;                        //name for each user
  String password;                    //password for each user
  int strikes;                        //strikes 
  int userclearance;                  //clearance
};

struct member user[3];
int useraddress[] = {1,150,301};
int eepromreset = 0;

void setup() {
  Serial.begin(9600); 
  if(eepromreset == 1){
    for (int i = 0 ; i < EEPROM.length() ; i++) {
      EEPROM.write(i, 0);
    }
  }
  if(EEPROM.read(0) == 0){
    user[0] = {"Jack", "0000#", 0, 3};
    user[1] = {"Billy", "0000#", 0, 2};       //declare user variables 
    user[2] = {"Sean", "0000#", 0, 1};
    for(int i = 0; i<3; i++){
      EEPROM.put(useraddress[i], user[i]);
      EEPROM.get(useraddress[i], user[i]);
    }
    EEPROM.write(0,1);
  }
  else{
    for(int i = 0; i<3; i++){
      user[i] = EEPROM.get(useraddress[i], user[i]);
    }
  }
  for(int i =0; i<3; i++){
    Serial.println(user[i].name);
    Serial.println(user[i].password);
    Serial.println(user[i].strikes);
    Serial.println(user[i].userclearance);
    delay(1000);
  }
}
  

void loop() {
}

The Serial output after first running the code is correct, as follows:

Jack
0000#
0
3
Billy
0000#
0
2
Sean
0000#
0
1

However after pressing the reset button on the arduino or turning it on/off, the output is:

Screenshot_3

There is a simple reason to it:

The "String" variables (with a capitol S in front) contain only a pointer to the characters somewhere in the memory, they do not keep the data ... So you are just storing the addresses where the names have been stored at write-time ...

You can either go the mostly recommended way, avoid "String" and use C/C++ character arrays or you may have a look at this tutorial that provides routines to handle Strings together with EEPROM:

https://roboticsbackend.com/arduino-write-string-in-eeprom/

Good luck
ec2021

P.S.: And here is another source that supplies routines to read/write strings to EEPROM:

https://gist.github.com/smching/05261f11da11e0a5dc834f944afd5961

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.