Difficulty Level: Intermediate
This tutorial explains how to store data on an EEPROM using Arduino. The EEPROM is useful for saving data such as user settings or sensor readings that need to be retained even after the Arduino is powered down.
EEPROM is a form of non-volatile memory, meaning it can store data permanently (or until it is rewritten), even when the Arduino is powered off. This makes it ideal for saving data that should persist across reboots, such as configuration settings or states.
Arduino comes with a built-in EEPROM library that allows you to write and read bytes to and from the EEPROM memory. Each EEPROM location can store one byte (8 bits) of data.
In the following example, we will write a number to the EEPROM and read it back from the memory to verify the storage.
// Include the EEPROM library
#include <EEPROM.h>
void setup() {
// Start serial communication to monitor EEPROM actions
Serial.begin(9600);
// Define a byte to store in EEPROM
byte storedValue = 10;
// Write the value to EEPROM at address 0
EEPROM.write(0, storedValue);
Serial.print("Value written to EEPROM: ");
Serial.println(storedValue);
// Read the value back from EEPROM
byte readValue = EEPROM.read(0);
Serial.print("Value read from EEPROM: ");
Serial.println(readValue);
}
void loop() {
// Nothing needed here
}
In the code above, we use the EEPROM.write()
function to write a byte (10) to address 0 of the EEPROM. Then, using EEPROM.read()
, we read back the value from that same location and display it in the Serial Monitor.
EEPROM.write(address, value)
: Writes a byte to a specific address in the EEPROM. The address must be an integer between 0 and 1023 (on ATmega328-based boards).EEPROM.read(address)
: Reads the byte stored at a specific EEPROM address.To store larger data types (e.g., int or float), you need to break them down into multiple bytes and store them in consecutive EEPROM addresses. Here's how you can do it:
int someInt = 1234;
void setup() {
Serial.begin(9600);
// Write an integer to EEPROM
EEPROM.put(0, someInt);
// Read an integer from EEPROM
int readInt;
EEPROM.get(0, readInt);
Serial.print("Integer read from EEPROM: ");
Serial.println(readInt);
}
void loop() {
// No code in the loop
}
Note: The EEPROM.put()
and EEPROM.get()
functions allow you to store and retrieve data types larger than one byte, such as int, float, or structures.
The amount of EEPROM available depends on the type of Arduino you're using. For example:
EEPROM has a limited lifespan in terms of write cycles, typically around 100,000 writes per address. This means you should avoid excessive writing to the EEPROM unless necessary.
EEPROM allows you to store persistent data on your Arduino projects, which is useful for saving settings or sensor values. By using the EEPROM.write()
and EEPROM.read()
functions, you can store single-byte values, and with EEPROM.put()
and EEPROM.get()
, you can store larger data types like integers or floats.