Storing and Reading Custom Data on EEPROM in Arduino — Part 1
Many a times while developing embedded applications, we require some data to be saved between hardware resets/ power cuts.
This can be accomplished by using the EEPROM memory to store the data at runtime.
EEPROM which stands for Electronically Erasable Programmable Read-Only Memory, is a type of non-volatile Read-Only Memory, which allows individual bytes to written and erased in the memory.
Since, it is a type of non-volatile memory, the data written to the EEPROM doesn’t get erased even when the power is turned off, and thus can be safely used to store data like user settings or some other parameters generated at runtime.
A basic Implementation on Arduino Uno
Now we will look at two very basic programs to work with the EEPROM in Arduino Uno.
The first program will store a simple character array into the EEPROM memory.
// A simple program to write charcater bytes into the EEPROM
#include <EEPROM.h>
#define MESSAGE_LENGTH 6
char myMessage[MESSAGE_LENGTH] = {'M','E','D','I','U','M'};
uint8_t eepromBaseAddress = 10;
void setup() {
// put your setup code here, to run once:
for (unsigned int index = 0; index < MESSAGE_LENGTH; index++) {
EEPROM.write(eepromBaseAddress+index, myMessage[index]);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
As you can see, the above program simply iterates over the char array and stores each byte in contiguous memory locations, with the help of the EEPROM.write() function.
This function simply takes two arguments:
- The address of the memory location as unsigned int (0–255).
- The data byte to store at the specified memory address.
The second program simply reads the characters byte by byte from the EEPROM memory and displays it on the serial terminal
// A simple program to read charcater bytes from the EEPROM
#include <EEPROM.h>
#define MESSAGE_LENGTH 6
char myMessage[MESSAGE_LENGTH];
uint8_t eepromBaseAddress = 10;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(1000);
for (unsigned int index = 0; index < MESSAGE_LENGTH; index++) {
myMessage[index] = EEPROM.read(eepromBaseAddress+index);
}
delay(1000);
for(unsigned int index = 0; index< MESSAGE_LENGTH; index++){
Serial.print(myMessage[index]);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
The above program simply iterates over the contiguous memory locations, fetches each byte and stores them into an array. And finally displays them as bytes.
As you can see, even if the power is turned off, the second program can read the text data stored in EEPROM, every time.
In the next blog post, we will look at how to store and retrieve data which span over multiple bytes into EEPROM.