Close

Saving variables in EEPROM

A project log for R'lieh - Aquarium/ closed ecosystem management

An automated and connected aquarium management system

Audrey RobinelAudrey Robinel 05/15/2015 at 20:000 Comments

The cooling system is set to turn on at 24.5°C and off at 24°C. However i made it so that it is possible to change this value. By sending the command "setLowTemp1:X", the low temperature will be set to X, and there is a command to set the high temperature. However, without further modifications, the values would be lost after a power loss. In order to prevent that, i decided to store the values in the Atmega328p. A way to save values in the chip is to write them in the EEPROM.

For those unfamiliar with this concept, EEPROM stands for Electrically Erasable Programmable Read-Only Memory. I invite you to read more on the subject of EEPROM on this wikipedia link.

On the ATMega chips, there is some EEPROM memory, and on the ATMega328p, there is 1024 Bytes of EEPROM (http://playground.arduino.cc/Code/EEPROM-Flash).

By default, in order to access the EEPROM, one would use the EEPROM.h library described on Arduino.cc.

However, it only supports reading and writing int values from 0 to 255. Since i had to store floats, and didn't want to fiddle with this, i used the EEPROMex.h library. It is meant to be used in the same way as the basic library (code written for EEPROM.h works with this lib), but extends it by adding read and write functions for many types, including floats.

I thus added the following section in my code :

if(cmd  =="setLowTemp1")
    {
      if(param0f!=-1.0)
      {
        lowTemp1=param0f;
        EEPROM.updateFloat(lowTemp1Address,lowTemp1);
        printCmdResultXML(0, true, lowTemp1Tag+" set");
      }
      else
      {
        printCmdResultXML(1, true, missingArgumentString+":"+lowTemp1Tag);
      }
    }
    else if(cmd  =="getLowTemp1")
    {
      Serial.print(openTag1+lowTemp1Tag+closingTag);
      Serial.print(lowTemp1);
      Serial.println(openTag2+lowTemp1Tag+closingTag);
    }
His section handles the commands related to the low temperature (the second only shows it, but the first one is used to store it in the EEPROM. I used the update function rather than write so that if it is unchanged, it won't actually write it, preserving the memory. Indeed, it has 100 000 writes per cell, so it's better not to overuse it in vain.

In the setup function of the ATMega328p, i use this to retrieve the values :

  lowTemp1=EEPROM.readFloat(lowTemp1Address); 
  highTemp1=EEPROM.readFloat(highTemp1Address);
With this, i can now save user specified values for some settings.

I will probably add the possibility of storing the fading time int the EEPROM as well.

Discussions