Skip to content

Arduino and memory how to

The EEPROM as we said before is the arduino's hard disk. Can be re-written 100.000 times so use this method with care.

#include <EEPROM.h>

// this constant won't change:
const int  buttonPin = 12;    // the pin that the pushbutton is attached to

// Variables will change:
unsigned int buttonPushCounter;   // counter for the number of button presses
unsigned int buttonState = 0;     // current state of the button
unsigned int lastButtonState = 0; // previous state of the button

void SaveToEEPROM(int address ,byte value){
  EEPROM.write(address, value);

byte ReadFromEEPROM(int address){

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);

  // initialize serial communication:

  //Restore last saved buttonPushCounter value
  buttonPushCounter = ReadFromEEPROM(0);

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter, DEC);

      //Save the new buttonPushCounter into EEPROM

    else {
      // if the current state is LOW then the button
      // went from on to off:
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;


The first thing you should notice is the use of the EEPROM library (#include )

We have made two pretty simple functions the SaveToEEPROM and the ReadFromEEPROM

The SaveToEEPROM needs the physical address of the EEPROM memory in order to write and the second is the value to write with dimension 1 byte.
In order to read the stored byte we use the ReadFromEEPROM and we give as input the physical address.

Notice that this time the buttonPushCounter is not initialized since we use the ReadFromEEPROM function in order to initialize our variable within the void setup() function.

Each time we press the button we store the new buttonPushCounter value at the EEPROM.
Notice that saving at the EEPROM the variable is a not recommended option for real life projects.

An observation : EEPROM.write writes one byte at each address, but what happens if we wanted to store an integer? We will discuss this limitation later in another article.

Here is a demonstrative video of the EEPROM example :

Let's see the third memory option , the flash.