Skip to content

EEPROM and Arduino. A deeper view

The program increase and  save into the EEPROM every 10 seconds an integer value.

Please notice that the EEPROM can be written 100.000 times so use this program only as a demo since sooner or later will destruct your ATMEGA micro controller.

#include <EEPROM.h>

unsigned int StoredValue;

void SaveToEEPROM(unsigned int MyInteger){

  //MyInteger is 2 byte (unsigned int) so 2*8=16bit long
  //Lets say that: MyInteger XXXXXXXXYYYYYYYY 

  unsigned int wl;
  wl=MyInteger>>8; //8 zeros at beggining wl=00000000XXXXXXXX

  unsigned int wr;
  wr=MyInteger<<8; //8 zeros at end wr=YYYYYYYY00000000
  wr=wr>>8;        //I do : wr=00000000YYYYYYYY

  EEPROM.write(0,wl); //I write XXXXXXXX
  EEPROM.write(1,wr); //I write YYYYYYYY

}

unsigned int ReadFromEEPROM(){

  unsigned int wl;
  wl=EEPROM.read(0); // I read wl = 00000000XXXXXXXX
  wl=wl<<8;          //wl=XXXXXXXX00000000

  unsigned int wr;
  wr=EEPROM.read(1); //I read wr=00000000YYYYYYYY

  unsigned int w;
  w=wl+wr;           //w=XXXXXXXX00000000+00000000YYYYYYYY=XXXXXXXXYYYYYYYY

  return w;

}

void setup()                      // the set up part (runs only once)
{
  Serial.begin(9600);             // set up Serial library at 9600 bps  

  //Read from the EEPROM
  StoredValue=ReadFromEEPROM();

  if (StoredValue>60000) {
    StoredValue=0;
  }

  Serial.print("The latest stored value is : "); //Print the stored value
  Serial.println(StoredValue,DEC);

}

void loop()                       // The main loop (runs over and over again)
{

  Serial.println("I am sleeping for 10 sec");
  delay(10000);

  //Save a new value at the EEPROM
  SaveToEEPROM(StoredValue+1);

  //Read again from the EEPROM
  StoredValue=ReadFromEEPROM();
  Serial.print("The new stored value after 10sec is : ");
  Serial.println(StoredValue,DEC); 

}

As you can see this method is pretty easy.

Also notice that the program every time it starts reads from the EEPROM the last saved value so remembers the latest unsigned integer even if arduino switches off.

You can download this example from here : EEPROMAdvancedExample