How to read data from EEPROM in Arduino?

ArduinoHardwareSoftware & Coding

Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data.

Example

We will see how to read data from EEPROM in this example. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from − File → Examples → EEPROM.

We will look at the eeprom_read example. It is quite straightforward, thanks to the EEPROM library.

We begin with the inclusion of the library.

#include <EEPROM.h>

Next, some global variables are defined.

int address = 0;
byte value;

Within the setup, we just initialize Serial.

void setup() {
   // initialize serial and wait for port to open:
   Serial.begin(9600);
   while (!Serial) {
      ; // wait for serial port to connect. Needed for native USB port only
   }
}

In the loop, we use the EEPROM.read() function to read one byte of data. We print that byte on the Serial Monitor, and then increment the address to read the next byte. If we reach the end of EEPROM memory, we go back to the beginning (address = 0).

void loop() {
   // read a byte from the current address of the EEPROM
   value = EEPROM.read(address);
   Serial.print(address);

   Serial.print("\t");
   Serial.print(value, DEC);
   Serial.println();

   address = address + 1;
   if (address == EEPROM.length()) {
      address = 0;
   }
   delay(500);
}

As you can see, this was quite straightforward. If you need to read value from a specific address, you can just provide that address as the argument in EEPROM.read(). The only limitation of EEPROM.read() is that it can read only one byte of data at a time, and therefore, you need to iterate in order to get the required number of bytes.

raja
Published on 26-Jul-2021 09:36:16
Advertisements