# How to update existing data in EEPROM with Arduino?

ArduinoSoftware & CodingHardware

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 update existing data 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_update example. You essentially use the EEPROM.update() function. The EEPROM.update() function is different from EEPROM.write() in the sense that it will overwrite the value in the EEPROM only if the new value is different from what is already stored at that address. Why? Because each EEPROM has a limited number of write cycles (~100,000) per address. If we keep overwriting the same value at any address location, we reduce the lifespan of the EEPROM.

We begin with the inclusion of the library.

#include <EEPROM.h>

Next, we define a global variable for the address. Nothing happens in the setup.

int address = 0;
void setup() {
/** EMpty setup **/
}

Within the loop, we read values from an analog input (A0 in this case), and write it to the EEPROM using the .update() function. We then increment the address and repeat this. If we reach the end of the EEPROM's length, we go back to the beginning (addr = 0).

Note that we are dividing the analog read output by 4, because a byte can only have values from 0 to 255, whereas analogRead() output values range from 0 to 1023.

void loop() {
int val = analogRead(A0) / 4;
EEPROM.update(address, val);
/***
The function EEPROM.update(address, val) is equivalent to the following:
if( EEPROM.read(address) != val ){
EEPROM.write(address, val);
}
***/
address = address + 1;
if (address == EEPROM.length()) {
address = 0;
}
delay(100);
}

As is mentioned in the comments, the .update() function is equivalent to reading the EEPROM at that address, and writing to it only if the new value is different from the read value.

Published on 26-Jul-2021 09:47:04
Advertisements