0

I am using the following code to save and load credentials to and from EEPROM:

void loadCredentials() {
  EEPROM.begin(512);
  EEPROM.get(0, ssid);
  EEPROM.get(0+sizeof(ssid), password);
  char ok[2+1];
  EEPROM.get(0+sizeof(ssid)+sizeof(password), ok);
  EEPROM.end();
  if (String(ok) != String("OK")) {
    ssid[0] = 0;
    password[0] = 0;
  }
  Serial.println("Recovered credentials:");
  Serial.println(ssid);
  Serial.println(strlen(password)>0?"********":"<no password>");
}

/** Store WLAN credentials to EEPROM */
void saveCredentials() {
  EEPROM.begin(512);
  EEPROM.put(0, ssid);
  EEPROM.put(0+sizeof(ssid), password);
  char ok[2+1] = "OK";
  EEPROM.put(0+sizeof(ssid)+sizeof(password), ok);
  EEPROM.commit();
  EEPROM.end();
  Serial.print("Saving SSID: ");
  Serial.println(ssid);
  Serial.print("Password: ");
  Serial.println(password); 
  Serial.println("Done");
}

However, loadCredentials() always returns empty or invalid credentials. I cannot quite understand why though as saveCredentials() appears to run correctly, and WiFi.begin(ssid, passaord) works without any issues (until you reset)

here is the code used to set the credentials into the variables:

    if(ssidchange){
      a = String(a);
      a.toCharArray(tempssid, 50);
      ssid = tempssid;
      Serial.print("Done, SSID changed to ");
      Serial.println(ssid);
      ssidchange = false;
    }
    else if(passchange){
      char temppass[50];
      String a2 = String(a);
      a2.toCharArray(temppass, 50);
      ssid = tempssid;
      password = temppass;
      Serial.print("SSID changed to ");
      Serial.println(tempssid);
      Serial.print("and pass changed to ");
      Serial.println(password);
      saveCredentials();
      delay(3000);
      ESP.restart();
    }

Tank you very much in advance!

Aguilaair
  • 118
  • 1
  • 6

1 Answers1

0

Better way to make a structure which has member like ssid, password etc. e.g.

struct wificredential{
  char ssid[30];
  char pass[30];
}

and then storing that whole structure in eeprom at specific address. and later fetch it from same address whenever we want

I have done that to build database for framework here

Community
  • 1
  • 1
Suraj Inamdar
  • 181
  • 1
  • 1