0
0
AutocadHow-ToBeginner · 3 min read

How to Save Data to EEPROM in Arduino: Simple Guide

To save data to EEPROM in Arduino, use the EEPROM.write(address, value) function to store a byte at a specific address. To read it back, use EEPROM.read(address). Remember to include #include <EEPROM.h> in your sketch.
📐

Syntax

The basic syntax to save a byte to EEPROM is EEPROM.write(address, value), where address is the EEPROM memory location (0 to 1023 on many boards) and value is the byte (0-255) to store. To read a byte back, use EEPROM.read(address).

Note: address must be within the EEPROM size of your Arduino model.

arduino
#include <EEPROM.h>

void setup() {
  // Save the value 123 at EEPROM address 0
  EEPROM.write(0, 123);

  // Read the value back from address 0
  byte value = EEPROM.read(0);
}

void loop() {
  // Nothing here
}
💻

Example

This example saves a number to EEPROM and reads it back to print on the Serial Monitor. It shows how to store and retrieve data persistently even after power off.

arduino
#include <EEPROM.h>

void setup() {
  Serial.begin(9600);
  while (!Serial) {}

  int address = 0;
  byte dataToSave = 42;

  // Write data to EEPROM
  EEPROM.write(address, dataToSave);

  // Read data from EEPROM
  byte readData = EEPROM.read(address);

  Serial.print("Saved value: ");
  Serial.println(dataToSave);
  Serial.print("Read value: ");
  Serial.println(readData);
}

void loop() {
  // No repeated actions needed
}
Output
Saved value: 42 Read value: 42
⚠️

Common Pitfalls

  • Writing too often: EEPROM has limited write cycles (~100,000). Avoid writing repeatedly in loop().
  • Address out of range: Writing or reading outside EEPROM size causes errors.
  • Data types: EEPROM.write() stores only one byte. For larger data, use EEPROM.put() and EEPROM.get().
arduino
#include <EEPROM.h>

void setup() {
  // Wrong: writing in loop causes wear
}

void loop() {
  EEPROM.write(0, 10); // Avoid this
}

// Correct approach:
// Write only when needed, e.g., on an event or button press.
📊

Quick Reference

FunctionPurposeNotes
EEPROM.write(address, value)Write one byte to EEPROMValue is 0-255, address within EEPROM size
EEPROM.read(address)Read one byte from EEPROMReturns byte stored at address
EEPROM.put(address, data)Write any data type to EEPROMHandles multiple bytes, safer for structs
EEPROM.get(address, data)Read any data type from EEPROMRetrieves data stored with put()

Key Takeaways

Use EEPROM.write() and EEPROM.read() to save and retrieve bytes in EEPROM.
Avoid frequent writes to EEPROM to prevent wearing it out.
Use EEPROM.put() and EEPROM.get() for saving larger or complex data types.
Always check that the address is within your Arduino's EEPROM size.
Include #include <EEPROM.h> to access EEPROM functions.