Arduino EEPROM Explained – Remember Last LED State

This tutorial explains what is the Arduino EEPROM and what it is useful for. We’re also going to show you how to write and read from the EEPROM and build a project example to put the concepts learned into practice.

We have a similar tutorial for the ESP32: ESP32 Flash Memory – Store Permanent Data (Write and Read)

Introduction

When you define and use a variable, the  generated data within a sketch only lasts as long as the Arduino is on. If you reset or power off the Arduino, the data stored disappears.

If you want to keep the data stored for future use you need to use the Arduino EEPROM. This stores the variable’s data even when the Arduino resets or the power is turned off.

What is EEPROM?

The microcontroller on the Arduino board (ATMEGA328 in case of Arduino UNO, shown in figure below) has EEPROM (Electrically Erasable Programmable Read-Only Memory). This is a small space that can store byte variables.

The variables stored in the EEPROM kept there, event when you reset or power off the Arduino. Simply, the EEPROM is permanent storage similar to a hard drive in computers.

The EEPROM can be read, erased and re-written electronically. In Arduino, you can read and write from the EEPROM easily using the EEPROM library.

How many bytes can you store?

Each EEPROM position can save one byte, which means you can only store 8-bit numbers, which includes integer values between 0 and 255.

The bytes you can store on EEPROM dependson the microcontrollers on the Arduino boards. Take a look at the table below:

MicrocontrollerEEPROM
ATmega328 (Arduino Uno, Nano, Mini)1024 bytes
ATmega168 (Arduino Nano)512 bytes
ATmega2560 (Arduino Mega)4096 bytes

However, if you need to store more data you can get an external EEPROM.

The EEPROM finite life

The EEPROM has a finite life. In Arduino, the EEPROM is specified to handle 100 000 write/erase cycles for each position. However, reads are unlimited. This means you can read from the EEPROM as many times as you want without compromising its life expectancy.

Applications in Arduino projects – Remember last state

The EEPROM is useful in Arduino projects that need to keep data even when the Arduino resets or when power is removed.

It is specially useful to remember the last state of a variable or to remember how many times an appliance was activated.

For example, imagine the following scenario:

  • You’re controlling a lamp with your Arduino and the lamp is on;
  • The Arduino suddenly loses power;
  • When the power backs on, the lamp stays off – it doesn’t keep its last change.

You don’t want this to happen. You want the Arduino to remember what was happening before losing power and return to the last state.

To solve this problem, you can save the lamp’s state in the EEPROM and add a condition to your sketch to initially check whether the state of the lamp corresponds to the state previously saved in the EEPROM.

We’ll exemplify this with an example later in this post in the Example: Arduino EEPROM remember stored LED state.

Read and Write

You can easily read and write into the EEPROM using the EEPROM library.

To include the EEPROM library:

#include <EEPROM.h>

Write

To write data into the EEPROM, you use the EEPROM.write() function that takes in two arguments. The first one is the EEPROM location or address where you want to save the data, and the second is the value we want to save:

EEPROM.write(address, value);

For example, to write 9 on address 0, you’ll have:

EEPROM.write(0, 9);

Read

To read a byte from the EEPROM, you use the EEPROM.read() function. This function takes the address of the byte has an argument.

EEPROM.read(address);

For example, to read the byte stored previously in address 0.:

EEPROM.read(0);

This would return 9, which is the value stored in that location.

Update a value

The EEPROM.update() function is particularly useful. It only writes on the EEPROM if the value written is different from the one already saved.

As the EEPROM has limited life expectancy due to limited write/erase cycles, using the EEPROM.update() function instead of the EEPROM.write() saves cycles

You use the EEPROM.update() function as follows:

EEPROM.update(address, value);

At the moment, we have 9 stored in the address 0. So, if we call:

EEPROM.update(0, 9);

It won’t write on the EEPROM again, as the value currently saved is the same we want to write.

Example: Arduino EEPROM remember stored LED state

In this example, we’re going to show you how to make the Arduino remember the stored LED state, even when we reset the Arduino or the power goes off.

The following figure shows what we’re going to exemplify:

Parts required

Here’s the parts required for this project

  • Arduino UNO – read Best Arduino Starter Kits
  • 1x LED 
  • 1x 220Ω resistor 
  • 1x Pushbutton 
  • 1x 1kΩ resistor 
  • 1x Breadboard 
  • Jumper wires 

Schematics

Here’s the circuit schematics for this project. This is just a pushbutton that will turn an LED on and off.

Code

Copy the following code to the Arduino IDE and upload it to your Arduino board. Make sure you have the right board and COM port selected.

/*
 
 
 */

#include <EEPROM.h>

const int buttonPin = 8;    // pushbutton pin
const int ledPin = 4;       // LED pin

int ledState;                // variable to hold the led state
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin


// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  // set input and output
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);

  // initialize serial monitor
  Serial.begin (9600);

  //check stored LED state on EEPROM using function defined at the end of the code
  checkLedState(); 
}

void loop() {
  // read the state of the switch into a local variable
  int reading = digitalRead(buttonPin);

  if(reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if(reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if(buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED state
  digitalWrite(ledPin, ledState);
  // save the current LED state in the EEPROM
  EEPROM.update(0, ledState);
  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState
  lastButtonState = reading;
}

// Prints and upates the LED state
// when the Arduino board restarts or powers up
void checkLedState() {
   Serial.println("LED status after restart: ");
   ledState = EEPROM.read(0);
   if(ledState == 1) {
    Serial.println ("ON");
    digitalWrite(ledPin, HIGH);
   } 
   if(ledState == 0) {
    Serial.println ("OFF");
    digitalWrite(ledPin, LOW);
   }
}

This is a debounce code that changes the LED state every time you press the pushbutton. But there’s something special about this code – it remembers the saved LED state, even after resetting or powering of the Arduino.

Basically, we save the current LED state in the ledState variable and save it to the EEPROM with the following line:

EEPROM.update(0,ledState);

At the beginning of the code on the setup(), we check the ledState saved on EEPROM and set the led on or off accordingly to that state when we restart the program. We do that with a function we’ve created at the end of the code, checkLedState()

void checkLedState() {
    Serial.println("LED status after restart: ");
    ledState = EEPROM.read(0);
     if (ledState == 1) {
       Serial.println ("ON");
       digitalWrite(ledPin, HIGH);
     } 
     if (ledState == 0) {
       Serial.println ("OFF");
       digitalWrite(ledPin, LOW);
     }
}

Demonstration

For a demonstration of this example, watch the video below.

Wrapping up

In this post you’ve learned about the Arduino EEPROM and what it is useful for. You’ve created an Arduino sketch that remembers the last LED state even after resetting the Arduino.

This is just a simple example for you to understand how the use of EEPROM. The idea is that you apply the concepts learned in this tutorial to your own projects.

We hope you’ve found this article useful.

Thanks for reading.

Published by Gnd_To_Vcc

Here to spread my knowledge . Knowledge should always be spread not stored.

2 thoughts on “Arduino EEPROM Explained – Remember Last LED State

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: