Search code examples
stringappendesp8266eeprom

Arduino ESP8266 read String from EEPROM


I achieve to read a String from the ESP8266 EEPROM - so far so good.

However, trying to append a second string to the just read first one does not work!

I start with having the number 2 at address 0 of the EEPROM. I read from address 0 to 6.

Here is my ESP8266.ino code :

    String readM = "";
    String appendixStr = "|||";
    Serial.print("appendixStr = ");
    Serial.println(appendixStr);
    String dailyzStr = "";
    for (int a = 0; a < 7; ++a) {           // addr 0...6
        dailyzStr += char(EEPROM.read(a));
    }
    readM += dailyzStr + appendixStr;
    Serial.print("hmmm = ");
    Serial.println(readM);

And here is what the log prints:

enter image description here

Clearly, I would expect hmmm = 2||| but I only get hmmm = 2

Why is it not possible to append ??


Solution

  • I would recommend to use this:

    #include <EEPROM.h>
    // Tell it where to store your config data in EEPROM
    #define cfgStart 32
    // To check if it is your config data
    #define version "abc"
    
    struct storeStruct_t{
      char myVersion[3];
      char name[32];
    };
    
    void saveConfig() {
      // Save configuration from RAM into EEPROM
      EEPROM.begin(4095);
      EEPROM.put( cfgStart, settings );
      delay(200);
      EEPROM.commit();                      // Only needed for ESP8266 to get data written
      EEPROM.end();                         // Free RAM copy of structure
    }
    
    void loadConfig() {
      // Loads configuration from EEPROM into RAM
      Serial.println("Loading config");
      storeStruct_t load;
      EEPROM.begin(4095);
      EEPROM.get( cfgStart, load);
      EEPROM.end();
      // Check if it is your real struct
      if (test.myVersion[0] != version[0] ||
          test.myVersion[1] != version[1] ||
          test.myVersion[2] != version[2]) {
        saveConfig();
        return;
      }
      settings = load;
    }
    
    // Empty settings struct which will be filled from loadConfig()
    storeStruct_t settings = {
      "",
      ""
    };
    

    Use saveConfig() to save the settings struct
    If you want to load from the EEPROM use loadConfig() -> it will be stored in the settings struct