-1

I am using nodemcu ESP8266 and write a program to store some values to EEPROM (assign buffer address 115 to 150 to store USERNAME).

When I am reading EEPROM data using for loop from 115 to 150 then it will return unknown characters with string. As I am checking for null values to determine when the string ends the code doesn't work.

image of output with strange characters

My code:

//My Code for store username
String consumername = obj [String("USERNAME")] ;
         Serial.println("writing eeprom > Consumer Name:");
          for (int i = 0; i < consumername.length(); ++i) 
              {
             EEPROM.write(115 + i, consumername[i]);
           Serial.print("Wrote: ");
              Serial.println(consumername[i]);
          }
//My Code for reading username
for (int i = 115; i < 150; ++i) 
 {
     ch = char(EEPROM.read(i));
     if(ch!='\0'){
     oname+= char(EEPROM.read(i));
 }
 }
     Serial .print("Name=");
     Serial .println(oname);
Clifford
  • 88,407
  • 13
  • 85
  • 165
Yaseen
  • 11
  • What is `obj`? Please show a [mre] – Ted Lyngmo Jan 09 '23 at 17:20
  • when writing you write the actual length but when reading you read [115,150) chars which means there is _unset_ data - change when writing to write null's for remainder if that is what you are expecting on read. you also leave open the possibility of writing beyond 150. – Computable Jan 09 '23 at 17:23

1 Answers1

4

Looks to me like you are not including the string terminator in the writing to the EEPROM. Change the i < consumername.length() to i <= consumername.length() to include the string terminator.

for (int i = 0; i <= consumername.length(); ++i) 
{
         EEPROM.write(115 + i, consumername[i]);
       Serial.print("Wrote: ");
          Serial.println(consumername[i]);
}

As pointed out in a comment below, your read loop needs a modification. In the following I assume oname is an empty string to which you are adding the characters. So you need to read the characters from EEPROM until you read the end of string at which point you are done reading.

for (int i = 115; i < 150; ++i) 
{
    ch = char(EEPROM.read(i));
    if(ch == '\0') break; // if end of string found, break out of read loop.
    oname += ch;
}
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
  • 2
    For reference : https://github.com/arduino/ArduinoCore-API/blob/master/api/String.h#L225 (the length of the string is NOT including the trailing `\0`). Lesson of the day, I never programmed for arduino. But it always is worth the effort to read the content of header files (or documentation) – Pepijn Kramer Jan 09 '23 at 17:30