Store and Retrieve Data from EEPROM using ESP32
What is EEPROM in ESP32?
EEPROM (Electrically Erasable Programmable Read-Only Memory) is a type of non-volatile memory used to store data permanently even after the ESP32 is powered off. The ESP32 doesn't have dedicated EEPROM, but it simulates EEPROM using flash memory through the EEPROM library.
Working Principle of EEPROM
The EEPROM library allows reading and writing data to flash memory. You can store bytes, integers, or other data types at specific addresses and retrieve them even after reboot. It uses a flash page reserved for this purpose.
- Include the EEPROM library.
- Call EEPROM.begin(size) to initialize memory.
- Use EEPROM.write(address, value) to store data.
- Use EEPROM.read(address) to retrieve data.
- Call EEPROM.commit() to save changes to flash.
Formula: N/A
Components Required
- ESP32 Development Board
- Micro USB Cable
- Arduino IDE
Pin Configuration
- N/A: EEPROM access is internal, no physical pins are used.
EEPROM is simulated on flash memory, so excessive writes can reduce flash lifespan. Use it wisely for settings, states, or infrequent data storage.
Arduino Code for EEPROM Read/Write
1#include <EEPROM.h>
2
3#define EEPROM_SIZE 64
4
5void setup() {
6 Serial.begin(115200);
7
8 EEPROM.begin(EEPROM_SIZE);
9
10 int value = EEPROM.read(0);
11 Serial.print("Previously stored value: ");
12 Serial.println(value);
13
14 EEPROM.write(0, value + 1);
15 EEPROM.commit();
16 Serial.println("Value updated and stored.");
17}
18
19void loop() {
20 // Nothing in loop
21}
Code Explanation (Line-by-Line)
- #include <EEPROM.h>: Includes the EEPROM library to access simulated flash storage.
- #define EEPROM_SIZE 64: Defines the number of bytes to allocate for EEPROM (max 512).
- EEPROM.begin(EEPROM_SIZE);: Initializes the EEPROM with specified size.
- EEPROM.read(0);: Reads the byte stored at address 0.
- EEPROM.write(0, value + 1);: Increments the value and writes it back to EEPROM.
- EEPROM.commit();: Commits the changes to flash memory (must call after write).
Applications
- Storing user settings
- Saving device states across resets
- Keeping calibration data
- Storing sensor thresholds or preferences
- Logging data in low-frequency events
Conclusion
EEPROM functionality in ESP32 allows persistent storage of small amounts of data even after power loss. It’s ideal for saving configurations, states, or sensor thresholds. Just remember to call `EEPROM.commit()` after writing and avoid excessive write operations to protect flash memory.