Tutorial 10: EEPROM

Saving data such that it is preserved after a power cycle or an update to the code may be important to your project. In this tutorial I show you how to access the Arduino's EEPROM, allowing you to save data just like it were an SD card!

Of course the amount of data you can save to the EEPROM is quite small: the Arduino UNO only allows for 1kB of data storage and the Arduino MEGA2560 only allows 4kB. However if all you're trying to achieve is hold a last known value of a sensor, input, or some other parameter, the EEPROM provides more than enough space!


DIFFICULTY
EASY
CIRCUITRY KNOWLEDGE
LITTLE
C++ PROGRAMMING
LITTLE
ABOUT
0
MINUTES
  • Some of the limitations of the Arduino’s EEPROM
  • How to write to an Arduino’s EEPROM
  • How to read from an Arduino’s EEPROM
You can copy / paste the code below if you’re having issues with typos or want a shortcut. However I recommend that you follow along in the tutorial to understand what is going on!


#include <EEPROM.h>
// EEPROM is good 100,000 write/erase cycles
// 3.3 ms per write

int LED1 = 10 ;
int LED2 = 11 ;
int button1 = 7 ;
int button2 = 8 ;

int lastPress = 0 ;

uint8_t EEPROMaddress = 130 ;

void setup() {
  pinMode(LED1, OUTPUT) ;
  pinMode(LED2, OUTPUT) ;
  pinMode(button1, INPUT) ;
  pinMode(button2, INPUT) ;
}

void loop() {
  lastPress = EEPROM.read(EEPROMaddress) ;
  
  if (digitalRead(button1)){
    lastPress = button1 ;
    EEPROM.write(EEPROMaddress, lastPress) ;
  }
  else if (digitalRead(button2)){
    lastPress = button2 ;
    EEPROM.write(EEPROMaddress, lastPress) ;
  }

  if (lastPress == button1){
    digitalWrite(LED2, LOW) ;
    digitalWrite(LED1, HIGH) ;
  }
  else if (lastPress == button2){
    digitalWrite(LED1, LOW) ;
    digitalWrite(LED2, HIGH) ;
  }

}
The tutorial quickly shows some circuit diagrams. Here they are: