Is It Safe to Initialize Global Variables from EEPROM on Startup?

Hello everyone,

I've been experimenting with initializing global variables directly from EEPROM in my Arduino sketches using the following method:

#include <EEPROM.h>

// Global declaration
int value = EEPROM.get(address, value);

This approach appears to work without any issues in my tests. However, I'm concerned about potential hidden downsides or risks that might not be immediately obvious. Are there any potential problems with initializing globals directly from EEPROM in this way? I would appreciate any insights on whether this practice is considered safe and effective.

Thanks in advance!

I am doing exactly that for a project of mine. I can even change the EEPROM data with a second sketch if I need to.

it will not work, at least not how you showing it. but:

#include <EEPROM.h>
int x=0;
void setup(){
  EEPROM.get(0, x);
}
1 Like

One says it works exactly like you wrote.

Another says it won't work, and shows you what will.

The one with the assignments in setup() is more obviously correct, at a glance.

Your way may work, now, but suffers from a potential problem if things change, that is to say that if it works, you are relying on unreliable things. And luck.

The other will work. Now and no matter who changes things you are t looking at, and shouldn't have to.

a7

This is what I use in my sketch that uses the EEPROM with the exception:

EEPROM.begin();

Is not needed in the setup(). According to the readme you just need the include.

truth

Whether it is needed depends on the Arduino board that you are using

1 Like

Good point, I only checked under the AVR boards.

Here is the code I used for testing

#include <EEPROM.h>

int testValue = EEPROM.get(0, testValue);

void setup() {
  Serial.begin(9600);

// To initialize EEPROM: Uncomment the next line, upload once, then re-comment and re-upload
//EEPROM.put(0, 123);  // Writes 123 to EEPROM at address 0. // Try to use other values than 123 to test if the code works

  Serial.print("Value read from EEPROM: ");
  Serial.println(testValue);
}

void loop() {
 
}