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.
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.
#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() {
}