Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By Masoud Navidi
#87610 hi everyone!

I'm trying to save some string variables into EEPROM, like, password, ssid, username and so on but I can't find a perfect way for it. I have a code which doesn't work for me.

if you see any problems in the code please tell me or if you have a code which does actually works, please let me know of it.

P.S. if I put delay(1000) in loops of write_word and read_word functions, the write_word function takes much more time than read_word. I assume that write_word function is writing '0' into EEPROM and read_word reads the first '0' and finishes the function. but I'm not sure.

Code: Select allString read_word(int addr)
{
  String word1;
  char readChar;
  int i = addr;

  while (readChar != '\0')
  {
    readChar = char(EEPROM.read(i));
    delay(10);
    i++;

    if (readChar != '\0')
    {
      word1 += readChar;
    }
  }

  return word1;
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
void write_word(int addr, String word2)
{
  delay(10);

  for (int i = addr; i < word2.length() + addr; ++i) {
    Serial.println(word2[i]);
    EEPROM.write(i, word2[i]);
  }

  EEPROM.write(word2.length() + addr, '\0');
  EEPROM.commit();
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
void init_val(void)
{
  byte initialized = EEPROM.read(initializing);

  if (initialized != 124)  // it must be 123 but I put 124 here so this part will be run eveytime
  {
    EEPROM.write(initializing, 123);
    EEPROM.write(ap_st_mode_add, st_mode);
    EEPROM.commit();

    // note that ap_pass_add and ap_pass_add are defined as 50 and 100 respectively
    // ap_pass and ap_ssid are global string variables
   
    String init_pass_ssid = "DEFUALT";
    write_word(ap_pass_add, init_pass_ssid);
    write_word(ap_ssid_add, init_pass_ssid);
  }

  ap_st_mode = EEPROM.read(ap_st_mode_add);
  ap_pass = read_word(ap_pass_add);
  ap_ssid = read_word(ap_ssid_add);

}
User avatar
By Masoud Navidi
#87611 I have found the problem, it was a silly mistake.

In write_word function, I have used int i for address and for index of the word2, that was the mistake.

this is the corrected code:

Code: Select allvoid write_word(int addr, String word2)
{
  delay(10);
  int str_len = word2.length() + 1;

  for (int i = addr; i < str_len + addr; ++i)
  {
    EEPROM.write(i, word2.charAt(i - addr)); // the problem was here
  }

  EEPROM.write(str_len + addr, '\0');
  EEPROM.commit();
}