It’s very convenient to use the EEPROM memory to save parameters on Arduino since It’s not lost when Arduino is off. EEPROM is built on the class on Arduino therefore users can directly use it without installing external libraries. In order to use the EEPROM functions, please have a look at these articles here from the Robotics Back-End. In this post, I’m going to share with everyone how to create a library to write and read char arrays into EEPROM.
Fisrt of all, we need to create a header file with a name and extension should be *.h. Here I created a file name MyEEROM.h.
#ifndef MYEEPROM_H
#define MYEEPROM_H
#include <Arduino.h>
class MyEEPROM
{
public:
MyEEPROM();
void writeChartoEEPROM(int addrOffset, char message[], const uint8_t size);
char *readCharFromEEPROM(int addrOffset);
};
#endif
Then create a source file with the extension is .cpp. It’s named MyEEROM.ccp
#include "MyEEPROM.h"
#include <EEPROM.h>
#include <Arduino.h>
//Check
MyEEPROM::MyEEPROM()
{
}
//Write a Char Array into EEPROM: The code
void MyEEPROM::writeChartoEEPROM(int addrOffset, char message[], const uint8_t size)
{
EEPROM.write(addrOffset, size);
for (int i = 0; i < size; i++)
{
EEPROM.write(addrOffset + 1 + i, message[i]);
}
}
char *MyEEPROM::readCharFromEEPROM(int addrOffset)
{
int newCharLen = EEPROM.read(addrOffset);
//char data[newCharLen + 1]; //could not return char array
char *data = (char *) malloc (newCharLen + 1);
for (int i = 0; i < newCharLen; i++)
{
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newCharLen] = '\0';
return data;
}
I’ve already made an example named EEPROM.ino for you to test the EEPROM library which listed as below:
#include "MyEEPROM.h"
void setup() {
Serial.begin(9600);
int addrOffset = 0;
// Writing
char writeData[5] = "1,923";
MyEEPROM myEEPROM;
//myEEPROM.writeChartoEEPROM(addrOffset, writeData, sizeof(writeData));
// Reading
char *data = myEEPROM.readCharFromEEPROM(addrOffset);
Serial.print("data read from eeprom: ");
Serial.println(data);
}
void loop() {}
In the end, put all three files in one folder and run the example by using Arduino IDE. Please note that the folder name should be the same with the Arduino file (i.e EEPROM). I already made the codes to be available on my Github page here.