I'm working on project which require to save some data into the EEPROM.
As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call EEPROM.commit()
. You also have to call EEPROM.begin(size)
(I used size = 512) before start to use it.
I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with
EEPROM.write(..)
...
EEPROM.read(..)
and with
EEPROM.put(..)
...
EEPROM.get(..)
but nothing change.
Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?
EDIT: here's the code
void setup()
{
Serial.begin(9600);
Serial.println();
EEPROM.begin(512);
EEPROM.write(0, 62);
EEPROM.write(10, 103);
//EEPROM.commit();
EEPROM.end();
Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
}
I always read 0 in the output.
2 Answers 2
You can read the emulated EEPROM only between begin
and end
. It works with memory image.
begin
allocates the in-memory image.commit
writes it to flash.end
commits and deletes the memory image.
Here is some ESP8266 example code to store and read strings from EEPROM data:
#include <EEPROM.h>
void writeString(char add,String data);
String read_String(char add);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
EEPROM.begin(512); // Note::
String data = "Hello World";
Serial.print("Writing Data:");
Serial.println(data);
writeString(10, data); //Address 10 and String type data
delay(10);
}
void loop() {
// put your main code here, to run repeatedly:
String recivedData;
recivedData = read_String(10);
Serial.print("Read Data:");
Serial.println(recivedData);
delay(1000);
}
void writeString(char add,String data)
{
int _size = data.length();
int i;
for(i=0;i<_size;i++)
{
EEPROM.write(add+i,data[i]);
}
EEPROM.write(add+_size,'0円'); //Add termination null character for String Data
}
String read_String(char add)
{
int i;
char data[100]; //Max 100 Bytes
int len=0;
unsigned char k;
k=EEPROM.read(add);
while(k != '0円' && len<500) //Read until null character
{
k=EEPROM.read(add+len);
data[len]=k;
len++;
}
data[len]='0円';
return String(data);
}
read
only betweenbegin
andend
. it works with memory image.begin
allocates the in-memory image.commit
writes it to flash.end
commits and deletes the memory image