How to put data of any size in the EEPROM using 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.

In this article, we will see how to put data of any size (not just a byte) in the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from: File → Examples → EEPROM.

Example

We will look at the eeprom_put example. The main function of interest is EEPROM.put(). It takes two arguments, the starting address from which to start writing/ updating data, and the data to be written (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. The .put() function behaves like the .update() function, i.e., it writes to the EEPROM only if the new value to be written is different from the existing value stored in that memory location.

We begin with the inclusion of the library.

#include <EEPROM.h>

Next, we a struct is defined, which contains two floats, and a character array.

struct MyObject {
   float field1;
   byte field2;
   char name[10];
};

Within the Setup, we first initialize Serial. Next, we initialize a float, and write it to the beginning of the EEPROM (address = 0). We then advance the address variable by the size of the float (using the sizeof() function), and store a struct (using the structure defined earlier).

void setup() {

   Serial.begin(9600);
   while (!Serial) {
      ; // wait for serial port to connect. Needed for native USB port only
   }

   float f = 123.456f; //Variable to store in EEPROM.
   int eeAddress = 0; // Location we want the data to be put.

   // One simple call, with the address first and the object second.
   EEPROM.put(eeAddress, f);

   Serial.println("Written float data type!");

   /** Put is designed for use with custom structures also. **/

   // Data to store.
   MyObject customVar = {
      3.14f,
      65,
      "Working!"
   };

   eeAddress += sizeof(float); // Move address to the next byte after float 'f'.

   EEPROM.put(eeAddress, customVar);
   Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}

Nothing happens in the loop.

void loop() {
   /* Empty loop */
}

This example is a precursor to the eeprom_get example. In other words, the eeprom_get example will assume that you've run this eeprom_put example on your Arduino once.

raja
Updated on 26-Jul-2021 09:56:42

Advertisements