When I write to eeprom z-uno hangs with some probability. I'm trying to utilize EEPROM in the way it would not exhaust its resource too fast.
So I have SettingsHeader structure storing data length and is Actual flag. Loading of settings starts with configured start of EEPROM address range reads header if it is not actual reads the next one and so on till it gets to header stored most recently , take data bytes length from it and reads the data right after the header. Saving setting first rewrites current header to set isActual to false and writes new one with new data after it.
Code: Select all
struct SettingsHeader
{
boolean isActual;
word length;
word rewriteCycles;
byte crc;
};
struct SettingsData
{
byte startUpRelayOnOff;
byte crc;
};
void SettingsManager::saveSetting(){
Serial.print("Saving");
Serial.flush();
Settings* settings = context->settings;
SettingsData data;
actualHeader.isActual = false;
actualHeader.crc = calcCrc8((byte*)&actualHeader, sizeof(SettingsHeader) - 1);
EEPROM.put(actualHeaderAddress, &actualHeader, sizeof(SettingsHeader));
actualHeaderAddress += sizeof(SettingsHeader) + sizeof(SettingsData);
//Write to EEPROM start if it is full
if (actualHeaderAddress >= EEPROM_ADDR_MAX){
actualHeaderAddress = EEPROM_ADDR_MIN;
}
//build new data
data.startUpRelayOnOff = settings->startUpRelayOnOff;
data.crc = calcCrc8((byte*)&data, sizeof(SettingsData) - 1);
//build new header
actualHeader.isActual = true;
actualHeader.rewriteCycles ++;
actualHeader.length = sizeof(SettingsData);
actualHeader.crc = calcCrc8((byte*)&actualHeader, sizeof(SettingsHeader) - 1);
//save new header
EEPROM.put(actualHeaderAddress, &actualHeader, sizeof(SettingsHeader));
//save new data
EEPROM.put(actualHeaderAddress + sizeof(SettingsHeader), &data, sizeof(SettingsData));
Serial.print("Saved");
Serial.flush();
}
byte SettingsManager::calcCrc8(byte * data, byte count) {
byte result = 0xDF;
while(count--) {
result ^= *data;
data++;
}
return result;
}