Please checkout the YouTube video as it covers off on my code in quite a bit of detail.
In the video I look at two options, the first being simply including the EEPROM functions in the body of the main code sketch. This works fine and is a pretty good option however I also looked at an option where I created a dedicated Class to encapsulate all the Settings code. Personally this is the way I will be goind, however feel free to adopt whatever method works for you.
The class is pretty straight forward and I have included the code below, if you want you can simply copy the code below into two correctly named tabs in your sketch and use it.
You will need to change the following code so it is relevant for your project.
// Settings Version
#define SETTING_VER "SBR2.0"
// Parameters Structure
typedef struct {
float pidP;
float pidI;
float pidD;
float pidDB;
float pidOPMin;
float pidOPMax;
float turnSpeed;
float maxSpeed;
char ver[sizeof(SETTING_VER)];
} ParametersType;
Settings.h
------------------
//
// Settings Class
//
#ifndef SETTINGS_H
#define SETTINGS_H
#include "Arduino.h"
#include <EEPROM.h>
// Settings Version
#define SETTING_VER "SBR2.0"
// Parameters Structure
typedef struct {
float pidP;
float pidI;
float pidD;
float pidDB;
float pidOPMin;
float pidOPMax;
float turnSpeed;
float maxSpeed;
char ver[sizeof(SETTING_VER)];
} ParametersType;
class Settings
{
public:
Settings(ParametersType defaults);
void save();
ParametersType *parameters;
private:
byte buffer[sizeof(ParametersType)];
};
#endif
----------------
Settings.cpp
-----------------
//
// Settings Class
//
#include "Arduino.h"
#include "Settings.h"
Settings::Settings(ParametersType defaults) {
memcpy(buffer, &defaults, sizeof(defaults));
// Read version number from EEPROM
char savedVersion[sizeof(SETTING_VER)];
int eepromVersionOffset = sizeof(buffer) - sizeof(SETTING_VER);
EEPROM.get(eepromVersionOffset,savedVersion);
// If version in EEPROM is correct, overwrite the default coonfig with eeprom values
if (strcmp(savedVersion,SETTING_VER) == 0) {
// Overwrite the structure with EEPROM data
EEPROM.get(0,buffer);
}
parameters = (ParametersType *) buffer;
}
void Settings::save() {
EEPROM.put(0,buffer);
}