-->
Page 1 of 1

Weird behaviour when writing to EEPROM

PostPosted: Sun Nov 20, 2016 5:53 pm
by frischevollmilch
Hello, I am trying to save my wifi credentials of my ESP8266 in EEPROM with the following code:

Code: Select all#include <EEPROM.h>

struct WifiCredentials
{
  String ssid;
  String passphrase;
};

bool saveCredentials(String ssid, String passphrase)

  uint16_t ssid_address = 0;
  for(int i = ssid_address; i < ssid_address + 32; i++)
  {
    EEPROM.write(i, ssid[i]);
  }
  uint16_t passphrase_address = 32;
  for(int i = passphrase_address; i < passphrase_address + 32; i++)
  {
    EEPROM.write(i, passphrase[i]);
  }
  EEPROM.commit();

  return true;
}

WifiCredentials loadCredentials()
{
  String ssid;
  String passphrase;

  uint16_t ssid_address = 0;
  for(int i = ssid_address; i < ssid_address + 32; i++)
  {
    ssid += char(EEPROM.read(i));
  }
  uint16_t passphrase_address = 32;
  for(int i = passphrase_address; i < passphrase_address + 32; i++)
  {
    passphrase += char(EEPROM.read(i));
  }

  return WifiCredentials { ssid, passphrase };
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  EEPROM.begin(512);
 
  saveCredentials("abc", "123");
  WifiCredentials cred = loadCredentials();
  Serial.println(cred.ssid);
  Serial.println(cred.passphrase);
}

void loop() {
  // put your main code here, to run repeatedly:

}


Now I am writing the example credentials into EEPROM and then read them again. I would expect the output to be:

Code: Select allabc
123


but instead it is:

Code: Select allabc



I checked the code a thousand times but couldn't find my mistake. The only thing I could imagine would be my ESP8266 being broken at this point but at the other hand it's probably just a stupid mistake.

Can you guys help me out? Thanks!

Re: Weird behaviour when writing to EEPROM

PostPosted: Mon Nov 21, 2016 5:50 am
by eduperez
Problem is in this loop inside "saveCredentials":
Code: Select all  uint16_t passphrase_address = 32;
  for(int i = passphrase_address; i < passphrase_address + 32; i++)
  {
    EEPROM.write(i, passphrase[i]);
  }

Here, "i" starts at 32 and goes up to 63, thus you cannot use it at "passphrase[i]"; I would try this instead:
Code: Select all  uint16_t passphrase_address = 32;
  for(int i = 0; i < 32; i++)
  {
    EEPROM.write(i + passphrase_address, passphrase[i]);
  }

Re: Weird behaviour when writing to EEPROM

PostPosted: Mon Nov 21, 2016 12:49 pm
by frischevollmilch
Oh no, the mistake was just as stupid as I expected. Thank you, you saved my day!