0
0
AutocadHow-ToBeginner · 3 min read

How to Use EEPROM in Arduino: Syntax, Example, and Tips

To use EEPROM in Arduino, include the EEPROM.h library, then use EEPROM.read(address) to read and EEPROM.write(address, value) to write data at a specific memory address. This allows you to store data that stays saved even when the Arduino is powered off.
📐

Syntax

The EEPROM library provides simple functions to read and write bytes to the Arduino's non-volatile memory.

  • EEPROM.read(address): Reads a byte from the given address.
  • EEPROM.write(address, value): Writes a byte value to the given address.
  • address: The memory location (0 to EEPROM size - 1).
  • value: The byte (0-255) to store.
arduino
#include <EEPROM.h>

int address = 0; // Define address
byte value = EEPROM.read(address);  // Read byte from EEPROM
EEPROM.write(address, value);       // Write byte to EEPROM
💻

Example

This example writes the number 42 to EEPROM address 0, then reads it back and prints it to the Serial Monitor.

arduino
#include <EEPROM.h>

void setup() {
  Serial.begin(9600);
  delay(1000); // Wait for Serial to start

  int address = 0;
  byte valueToWrite = 42;

  EEPROM.write(address, valueToWrite);  // Save 42 at address 0

  byte valueRead = EEPROM.read(address); // Read from address 0

  Serial.print("Value read from EEPROM: ");
  Serial.println(valueRead);
}

void loop() {
  // Nothing here
}
Output
Value read from EEPROM: 42
⚠️

Common Pitfalls

  • Writing too often: EEPROM has limited write cycles (~100,000). Avoid writing repeatedly in loop().
  • Not waiting for Serial: Serial output may not appear if you don't wait after Serial.begin().
  • Address out of range: Always use addresses within EEPROM size (usually 512 or 1024 bytes).
  • Writing without checking: Use EEPROM.update() to write only if the value changes, saving write cycles.
arduino
// Wrong: Writing every loop iteration
/*
void loop() {
  EEPROM.write(0, 42); // Bad: wears out EEPROM fast
}
*/

// Right: Write once in setup or only when needed
void setup() {
  byte current = EEPROM.read(0);
  if (current != 42) {
    EEPROM.write(0, 42); // Write only if different
  }
}
📊

Quick Reference

Here is a quick summary of useful EEPROM functions:

FunctionDescription
EEPROM.read(address)Read a byte from EEPROM at address
EEPROM.write(address, value)Write a byte value to EEPROM at address
EEPROM.update(address, value)Write value only if it differs from current, saving write cycles
EEPROM.length()Returns total EEPROM size in bytes

Key Takeaways

Include EEPROM.h to access EEPROM functions in Arduino.
Use EEPROM.read() and EEPROM.write() to read and write bytes at specific addresses.
Avoid frequent writes to EEPROM to prevent wearing it out; use EEPROM.update() when possible.
Always check that your address is within the EEPROM size limits.
Use Serial output with a delay after Serial.begin() to see printed results.