Skip to content

EEPROM and Arduino. A deeper view

Another way is to use wl and wr as bytes and not as unsigned integers.
The operation wl=MyInteger will always select the last 8 bits from the MyInteger value.
So if MyInteger=XXXXXXXXYYYYYYYY and wr=MyInteger then wr = YYYYYYYY
So , now for the left part we have to move it 8 position to the right wl=MyInteger>>8;
wl=00000000XXXXXXXX=XXXXXXXX

The rest is pretty similar to the first approach.

#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
//THE BYTE ALWAYS SELECTS THE LAST 8 BITS

byte wl;
wl=MyInteger>>8; //8 zeros at beginning wl=XXXXXXXX

byte wr;
wr=MyInteger; //wr=YYYYYYYY

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

}

unsigned int ReadFromEEPROM(){

byte wl;
wl=EEPROM.read(0); // I read wl=XXXXXXXX

byte wr;
wr=EEPROM.read(1); //I read wr=YYYYYYYY

unsigned int w;
w=wl;   //w=00000000XXXXXXXX
w=w<<8; //w=XXXXXXXX00000000
w=w+wr; //w=XXXXXXXX00000000+YYYYYYYY=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);

}

You can download this example from here : EEPROMAdvancedExample2

Below you can watch the video demo of our program