Arduino EEPROM Read/Write

The following tutorial shows a basic code to read and write the Arduino board EEPROM memory. This memory module can store values even after the board is powered off or reset. In this tutorial we use this memory to store an LED state. The LED is controlled on/off with a button. The LED we use is the built in LED of the UNO board.

The wirring diagram is the following,

Arduino UNO – Button connected to D3 point

To use the EEPROM memory of the board the following header include is required

#include <EEPROM.h>

To read the EEPROM the following code is required

EEPROM.read(address);

The address is () based on the board the byte address. For example for UNO boards (ATMEGA328P) the EEPROM size is 1024 byte, so the address is from 0-1023. On byte of value can store values from 0-255.

To write/update the EEPROM data at an address the following code is required. update is only write the new value to the eeprom only if it is differs from the old one.

EEPROM.update(address,value);

Writing to the EEPROM is limited by the EEPROM lifecycle of the microchip. Usually it has around 100.000 write/erease cycle. Read is usually unlimited.

The following code save the builtin LED-s state controlled with the button connected to D3. If you switch on the LED ad reset the board the LED will turn on again. This is because in the setup we check the LED_state, what is stored in the EEPROM at the first address (0). At the LOOP when we press the button, the new state of the LED update the old one.

#include <EEPROM.h>
int buttonPin = 3; // Button Connected to D3
// The setup() function runs once each time the micro-controller starts
void setup()
{
	pinMode(LED_BUILTIN, OUTPUT); //Builtin LED as Output
	pinMode(buttonPin, INPUT); //Button at D3 as INPUT

	//check EEPROM saved state
	int Led_state = EEPROM.read(0);// Read Byte at EEPROM addres 0

	if (Led_state == 1) {
		digitalWrite(LED_BUILTIN, HIGH);
	}
	else {
		digitalWrite(LED_BUILTIN, LOW);
	}
	

}
// Add the main program code into the continuous loop() function
void loop()
{
	//When button pushed
	if (digitalRead(buttonPin)) {
		//Based on the eeprom value and LED state
		switch (EEPROM.read(0)) {
			case 1: //Led is on - Switch off
				digitalWrite(LED_BUILTIN, LOW);
				EEPROM.update(0, 0);
			break;
			default: //LED is off - Switch on
				digitalWrite(LED_BUILTIN, HIGH);
				EEPROM.update(0, 1);
			break;
		}
	}

}

For more detailed infomations about the eeprom follow the ARduino.cc guide:

https://www.arduino.cc/en/Reference/EEPROM

Leave a Reply

Your email address will not be published. Required fields are marked *