I am developing an application, which stores configuration data to EEPROM memory. I have a struct to pointer variable which holds the configuration data. I want to store, this variable to EEPROM, which I did. But when I tried to read the EEPROM after the write, I find no data in the EEPROM. Please have a look at the output.
#include <EEPROM.h>
#define config_ver "CONF"
typedef struct {
char version[10];
int num;
} conf_type;
conf_type config_var = {config_ver,50};
void saveconfig() {
Serial.println("Writing configuration!!");
for(int i=0; i < sizeof(config_var); i++) {
char d = *((char*)&config_var + i);
EEPROM.write(i,d);
}
}
void setup() {
Serial.begin(9600);
saveconfig();
Serial.println("Reading EEPROM memory");
for(int i = 0; i <= 20; i++) {
Serial.print(EEPROM.read(i));
}
}
void loop{}
Code output:
Writing configuration!!
VER01βββββββ2βββ
Reading EEPROM memory
000000000000000000000
1 Like
What is the eeprom memory address here.
Is it properly hard-coded?
Hi @Sri_Lalitha_Vinnakot
for(int i=0; i < sizeof(config_var); i++) {
char d = *((char*)&config_var + i);
EEPROM.write(i,d);
}
The address for memory starts at 0. See the for loop in my code. Its starts at zero till the size of the pointer.
ok. Try to make βiβ global.
in for loop,above read function, you are intializing βiβ to 0 and reading 20 values from thereβ¦so value at the ith location and 20 locations from it is 0. Thus it is reading 20 0βs.
Thanks for the reply. I am at first trying to write my struct variable to EEPROM, then I am trying to check if it is written successfully in EEPROM. What is the point of making βiβ global? I tried to run the same code with a global βiβ but it didnβt work.
Are you using an Arduino board or ESP or any other board? From your code, itβs evident that when you dereference the struct pointer, the value is not being written to eeprom since you have not specified the required number of memory needed for eeprom. Use EEPROM.begin(size);
in the setup function. size is the size of the eeprom memory.
Ex:
EEPROM.begin(128);
Thanks for the response. I did exactly what you have said, but nothing seems to work. I am using ESP32 in Arduino IDE to program the device.
Thats because in ESP32 their is no EEPROM. In ESP32 the flash memory is emulated as EEPROM. You have to call the commit() after a complete write.
for(int i=0; i < sizeof(config_var); i++) {
char d = *((char*)&config_var + i);
EEPROM.write(i,d);
}
EEPROM.commit();
Also, the EEPROM library is now deprecated. You may use the Preference library for EEPROM.
2 Likes
Thanks so much!! Finally some relief!!