2

I'm trying to write two strings to an Arduino Uno's EEPROM. Here, the first code block works fine: it writes string(True/False) at 'address 0'. But the second block, which writes data at 'address 5', is not working as expected.Reading data at address 5 prints a blank line. What am I missing here? Is this the correct way to write two different strings to EEPROM?

First code block:

int state = LOW;
char first_eeprom_value;
if (state == LOW) {
  state = HIGH;
  char example_string[4] = "True";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5 ; i++) {
    EEPROM.update(i, example_string[i]);
  }
} else {
  state = LOW;
  char example_string[5] = "False";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5; i++) {
    EEPROM.update(i, example_string[i]);
  }
}
Time = millis();

Second code block:

char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);      
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);     
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
}

Time = millis();

//reading data at address 5
int addr = 5;
char value = EEPROM.read(addr);
Serial.println(value);// this prints blank line
smc
  • 203
  • 1
  • 5
  • 14

1 Answers1

2

You are cycling outside the string, thus creating undefined behavior.

Try replacing the second block with this:

char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);      
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);     
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
}

Please note that this is not optimal; I suggest you to use fixed-length strings, and fill the unused spaces with blanks or 0s, so you can read back all the bytes you wrote in a safe way

wondra
  • 158
  • 5
frarugi87
  • 2,731
  • 12
  • 19