Storing Default State (failsafe) information in EEPROM

In building an automation platform for hydroponics, we wanted the ability to have the Arduinos start up in a default state. This would setup the lights, pumps, etc in the grow room in a preferred, known state even if the network and site controller (a RaspPi) didn’t come back online after a failure. We wanted the default state to be on-board the Arduinos and easily updated when we changed a room around.

We ended up creating a mapping that represents the default state as a pin map, with each pin having 2 bytes: one byte to denote pinMode and one to denote output value. (For the Mega2560, we store the default state for the 54 digital pins, so the pin map is 108 bytes.) We wrote two functions, one to take a pin map as a byte array and write it to EEPROM, the second reads the pin map from EEPROM and sets up the digital I/O pins accordingly. We interface with it over Ethernet, passing a string as a parameters to a command on the Ardi that calls the Write function. We added the read/set function call to the Setup function so when the Arduino boots the last thing it does in its own setup is put itself into the defined default state. Here are the functions:

Example default state map: "001000000010100000003131313100000000000000003030303031313131303030303030303010101010101010101010101000000000"

void writeDefaultData(byte stateData[]){
  for (int i = 0; i < PIN_MAP_SIZE; i++) {
    EEPROM.write(i, stateData[i]);
void setDefaultState(){
  int pin;
  byte state;
  byte value;

  pin = 0;
  for (int i = 0; i < PIN_MAP_SIZE; i+=2) {
    state = - 48; // subtract 48 because it was stored as an ascii value
    value = - 48;
    switch (state) {
      case 1:
        pinMode(pin, INPUT);
      case 2:
        pinMode(pin, INPUT_PULLUP);
      case 3:
        pinMode(pin, OUTPUT);
        digitalWrite(pin, value);
    pin = pin + 1;

We put the map size in a Define called PIN_MAP_SIZE so the code is easily ported to the Uno and other Arduino models.

Hack on,
Tyler Reed
Founder - HAPI (Hydroponic Automation Platform Initiative)
tyler @

Code tags please, half the post is in italics.

How to use this forum

Please edit your post, select the code, and put it between [code][/code] tags.

You can do that by hitting the # button above the posting area.

Ah thanks. It is done.