EEPROM (Electrically Erasable Programmable Read-Only Memory) is a non-volatile memory type found on most Arduino boards. It allows you to store data even when the power is disconnected, making it suitable for settings, calibration values, or other data that needs to be retained. Here’s a guide on how to use it:
Understanding EEPROM
- Non-Volatile: Data persists even after power off.
- Limited Writes: EEPROM has a limited number of write cycles (typically around 100,000). Avoid constantly writing to it.
- Byte-Oriented: Data is stored in individual bytes.
Arduino EEPROM Library
The Arduino IDE comes with the built-in
EEPROM.read(address)
: Reads a byte from the specified address.EEPROM.write(address, value)
: Writes a byte to the specified address.EEPROM.length()
: Returns the total size of the EEPROM in bytes.
Example: Storing and Retrieving an Integer
#include <EEPROM.h>
int address = 0; // EEPROM address to use
void setup() {
Serial.begin(9600);
}
void loop() {
// Read integer from EEPROM
int storedValue = EEPROM.read(address) * 256 + EEPROM.read(address + 1);
// Display the value
Serial.print("Stored Value: ");
Serial.println(storedValue);
// Wait for 5 seconds
delay(5000);
// Increment and store back
storedValue++;
EEPROM.write(address, storedValue / 256);
EEPROM.write(address + 1, storedValue % 256);
}
Explanation
- Include Header: Include the EEPROM library.
- Address: Define an address where you want to store the data.
- Reading: Since integers are typically two bytes, we read two consecutive bytes from the EEPROM and combine them.
- Writing: We split the integer into two bytes and write them to consecutive addresses.
Pro Tips:
- Data Structures: For more complex data types, consider using data structures or packing multiple values into a single byte.
- Wear Leveling: If you need frequent writes, implement a wear-leveling algorithm to distribute writes across the EEPROM, extending its lifespan.
Tags: Arduino, EEPROM, Data Storage, Non-Volatile Memory, Embedded Systems