EEPROM Put

The microcontroller on the Arduino and Genuino boards have 512 bytes of EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive).

The purpose of this example is to show the EEPROM.put() method that writes data on EEPROM using also the EEPROM.update() that writes data only if it is different from the previous content of the locations to be written. The number of bytes written is related to the datatype or custom structure of the variable to be written.

Hardware Required

  • Arduino or Genuino Board

Circuit

There is no circuit for this example.

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematics

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Code

/***
    eeprom_put example.

    This shows how to use the EEPROM.put() method.
    Also, this sketch will pre-set the EEPROM data for the
    example sketch eeprom_get.

    Note, unlike the single byte version EEPROM.write(),
    the put method will use update semantics. As in a byte
    will only be written to the EEPROM if the data is actually
    different.

    Written by Christopher Andrews 2015
    Released under MIT licence.
***/


#include <EEPROM.h>

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

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!");
}

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

See also

  • EEPROM library reference
  • EEPROM Clear - Fills the content of the EEPROM memory with “0”.
  • EEPROM Read – Reads values stored into EEPROM and prints them on Serial.
  • EEPROM Write – Stores values read from A0 into EEPROM.
  • EEPROM Crc – Calculates the CRC of EEPROM contents as if it was an array.
  • EEPROM Iteration – Programming examples on how to go through the EEPROM memory locations.
  • EEPROM Get – Get values from EEPROM and prints as float on serial.
  • EEPROM Update – Stores values read from A0 into EEPROM, writing the value only if different, to increase EEPROM life.


Last revision 2018/05/17 by SM