1

I am trying to save a string/char to EEPROM with EEPROM.put() and then get the value, but it doesn't work and I get a blank value when I do a EEPROM.get(). I remember this is how it worked on arduino nano, but now I am trying with an ESP32 board, do they work different ?

#include <EEPROM.h>

char my_string[8];

void setup() {

  Serial.begin(115200);

// I am writing by this code, then comment it out to try to read from EEPROM
/*
    my_string[0] = 'S';
    my_string[1] = 'N';
    my_string[2] = '-';
    my_string[3] = 'A';
    my_string[4] = 'B';
    my_string[5] = 'C';
    my_string[6] = 'D';
    
  EEPROM.put(0, my_string);
*/

  EEPROM.get(0, my_string);

  Serial.println("data is: ");
  Serial.println((char*)my_string);
}


void loop() { }
4

EEPROM can't store string. It stores numbers. put() takes a type and stores that type as numbers.

The char[] isn't a string - it's a number. More specifically it's a memory address for where the string data is stored.

All you're doing is storing that memory address, not the data itself.

Instead you need to iterate over your string. You should also store the length of the string if it's going to be variable.

For example:


void storeString(const char *str) {
    EEPROM.write(0, strlen(str)); // Store the string length
    for (int i = 0; i < strlen(str); i++) {
        EEPROM.write(i + 1, str[i]);
    }
}

void getString(char *str) {
    int len = EEPROM.read(0);
    for (int i = 0; i < len; i++) {
        str[i] = EEPROM.read(i + 1);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.