Search code examples
arduinoesp8266arduino-esp8266

Arduino ESP8266 EEPROM commit() returns false


I want to save the SSID and password in the EEPROM in my Arduino Sketch Wlan.

Actually everything works so far, except that the commit () returns a false. And that's why the memory is empty again after a restart.

My code:

void writePROM()
{
  EEPROM.begin(0);
  EEPROM.write(0, 0xAA);

  byte ssidLength = ssid.length();
  byte passLength = pass.length();

  int adress = 2;
  EEPROM.write(1, (byte)ssidLength);
  for(int i = 0; i < ssidLength; i++)
  {
    EEPROM.write(adress + i, (byte)ssid[i]);
  }
  adress += ssidLength + 1;

  EEPROM.write(adress++, passLength);
  for(int i = 0; i < passLength; i++)
  {
    EEPROM.write(adress + i, pass[i]);
  }

  bool bRc = EEPROM.commit();
  if(bRc)
  {
    Serial.println("Write successfully");
  }
  else
  {
    Serial.println("Write error");
  }
  
  
  Serial.println("Write name to EEPROM = " + ssid);
  Serial.println("Write password to EEPROM = " + pass);
}

What I am doing wrong?


Solution

  • First of all, good on you for checking the result of the commit() call.

    You're passing 0 when you initialize the EEPROM library:

      EEPROM.begin(0);
    

    You need to pass it the number of bytes that you're looking to store using it.

    You can read the code for the EEPROM library to confirm this:

    void EEPROMClass::begin(size_t size) {
      if (size <= 0) {
        DEBUGV("EEPROMClass::begin error, size == 0\n");
        return;
      }
    

    If you pass 0 it simply returns without doing any setup. You can also see that commit() will do nothing in this case:

    bool EEPROMClass::commit() {
      if (!_size)
        return false;
    

    In your case you should call EEPROM.begin() with at least the maximum size of an SSID and password plus one each for the zero terminating bytes (so, 32 characters for the SSID, 63 for the password, plus 2 for 97).

    But, as @Juraj pointed out in the comments, you don't need to do any of this as the ESP8266 will automatically persist the Wifi credentials.