Ir al contenido

Retaining data across power loss: EEPROM and non-volatile storage patterns

A machine's counters, setpoints and last known state should usually survive a power cycle. The pump station needs to remember how many cycles it has run and its configured level threshold. M-Duino and Ardbox are built on Arduino Mega and Leonardo boards, both with onboard EEPROM, which is what this lesson uses.

What you will learn

  • Save and restore a value with EEPROM.put() and EEPROM.get().
  • Restore saved values in setup() after a restart.
  • Limit writes so the memory does not wear out.

Writing and reading a value

#include <EEPROM.h>

int cycleCount = 0;

void saveCycleCount(int count) {
  EEPROM.put(0, count);
}

int loadCycleCount() {
  int count;
  EEPROM.get(0, count);
  return count;
}

void setup() {
  Serial.begin(9600);
  cycleCount = loadCycleCount();
  Serial.print("Cycles so far: ");
  Serial.println(cycleCount);
}

EEPROM.put() and EEPROM.get() handle any data type, including structs, and put() only writes bytes that actually changed. A freshly programmed board can hold meaningless values in EEPROM, so validate what you read (for example, discard negative or implausible values) before using it.

Try it: increase cycleCount, save it, power the PLC off and on, and check in the Serial Monitor that the value comes back.

Why write frequency matters

EEPROM cells survive a large but finite number of writes. Writing on every pass of loop(), potentially thousands of times per second, can wear a cell out in hours or days. Write only when a value changes, and for fast-changing values add a minimum time between writes using the millis() pattern from lesson 2.

unsigned long lastSave = 0;
const unsigned long minSaveInterval = 60000;  // at most once a minute
int lastSavedCount = -1;

void loop() {
  // cycleCount is incremented elsewhere in your logic

  if (cycleCount != lastSavedCount && millis() - lastSave >= minSaveInterval) {
    saveCycleCount(cycleCount);
    lastSavedCount = cycleCount;
    lastSave = millis();
  }
}

Saving on change alone is not enough when the value changes constantly. The time limit caps the wear whatever the machine does.

What EEPROM is not for

EEPROM suits small, rarely changing values: setpoints, configuration, a cycle counter. It is a poor fit for continuous data such as raw sensor telemetry, both for the write limit and because its capacity is small compared with an SD card or an external data logger.

Go deeper

Next lesson: what happens when the code freezes, with a watchdog. Take the quiz below first.

Calificación
0 0

No hay comentarios por ahora.

para ser el primero en comentar.