EEPROM (also written E2PROM and pronounced “e-e-prom”, “double-e prom”, “e-squared”, or simply “e-prom”) stands for Electrically Erasable Programmable Read-Only Memory and is a type of non-volatile memory used in computers and other electronic devices to store small amounts of data that must be saved when power is removed.
Unlike bytes in most other kinds of non-volatile memory, individual bytes in a traditional EEPROM can be independently read, erased, and re-written.
EEPROM library is really handy when it come to storing and retrieveing data on your Arduino. This storage will persist even if you unplug or reset your board.
In order to use EEPROM library you need to to include
#include "EEPROM.h"If you use Arduino makefile, don’t forget to add the lib in your linkage:
ARDUINO_LIBS = EEPROMThe function we’ll use in the EEPROM library are:
1 2 |
EEPROM.write(int address, char *value); // Writting one character at address char value = EEPROM.read(int address); // Reading one character from address |
Because we want to write more comple object such as one int, and two strings we need to define a structure containing all our informations.
1 2 3 4 5 |
struct WifiCredentials { char SSID[30]; char password[30]; int serutityType; }; |
We’ll not use directly the raw EEPROM library functions but write two functions to direclty write and read our whole structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
void EEPROMreadStruct(int address, char *buffer, int len) { int i = 0; while (i < len) { buffer[i] = EEPROM.read(address + i); i++; } } void EEPROMwriteStruct(int address, char *buffer, int len) { int i = 0; while (i < len) { EEPROM.write(address + i, buffer[i]); i++; } } |
Now we can easily store and retrieve our struct:
1 2 3 4 5 |
WifiCredentials w; EEPROMreadStruct(0, (char *) &w, sizeof(w)); //we can use or modify our informations before saving them again. EEPROMwriteStruct(0, (char *) &w, sizeof(w)); |
If we want to save more than on structure, we just offset the address of sizeof(w) * the number of items.
Warning: The EEPROM memory is only available for storing data for long term and keeping them even in case of reboot or reset of your Arduino. The EEPROM chip have about 100.000 read/write safe calls. After data may be corrupted!
Leave a Reply