EEPROM (Electrically Erasable Programmable Read-Only Memory) is a type of non-volatile memory that is used in microcontrollers like the ESP32 to store data permanently. This means that the data stored in EEPROM is retained even after the device is powered off or reset.
Why use EEPROM on ESP32?
EEPROM is useful for storing data that needs to be preserved during the normal operation of the device, such as:
- Device configuration: user preferences, network settings, etc.
- Historical data: event logs, sensor readings, etc.
- Identification data: serial numbers, MAC addresses, etc.
How does EEPROM work on ESP32?
The ESP32 does not have dedicated EEPROM memory, but the EEPROM library of the Arduino core for ESP32 emulates EEPROM functionality using a section of Flash memory. Flash memory is another type of non-volatile memory that is used to store program code and system data.
The EEPROM library provides functions for reading and writing data to the emulated Flash memory. The data is stored at individual addresses, and each address can store an 8-bit value (0 to 255). The total size of the emulated EEPROM memory is 512 bytes.
Advantages of EEPROM on ESP32:
- Persistent data storage: Data is retained even after the device is powered off or reset.
- Easy to use: The EEPROM library provides simple functions for reading and writing data.
- Non-volatile: Data is not erased when power is lost.
Disadvantages of EEPROM on ESP32:
- Limited lifespan: EEPROM memory cells have a limited number of write cycles.
- Slow write speed: Writing to EEPROM memory is slower than reading.
- Limited size: The total size of the emulated EEPROM memory is only 512 bytes.
Overall, EEPROM is a valuable tool for storing persistent data on the ESP32. It is easy to use, non-volatile, and has low power consumption. However, it is important to be aware of the limitations of EEPROM, such as the limited lifespan, slow write speed, and limited size.
Example code in .cpp on the Platformio platform of Visual Studio Code:
#include <Arduino.h>
#include <EEPROM.h>
// Define the EEPROM size
#define EEPROM_SIZE 64
// Define the address to write to
#define ADDRESS 0
void setup() {
// Initialize Serial for debugging
Serial.begin(9600);
// Initialize EEPROM
if (!EEPROM.begin(EEPROM_SIZE)) {
Serial.println("Failed to initialize EEPROM");
Serial.println("Restarting...");
delay(1000);
ESP.restart();
}
// Write data to EEPROM
EEPROM.write(ADDRESS, 123);
EEPROM.commit();
Serial.println("Data written to EEPROM");
// Read data from EEPROM
byte data = EEPROM.read(ADDRESS);
Serial.print("Data read from EEPROM: ");
Serial.println(data);
// Erase data from EEPROM
EEPROM.write(ADDRESS, 0);
EEPROM.commit();
Serial.println("Data erased from EEPROM");
// Read data from EEPROM again to confirm it has been erased
data = EEPROM.read(ADDRESS);
Serial.print("Data read from EEPROM: ");
Serial.println(data);
}
void loop() {
// Nothing to do here
}
Leave a Reply Cancel reply