When I save a value to NVS using Preferences.h its value is changed when i upload the program. I was under the impression that it would unchanged so important values can be reused between program updates.
Below is an example, I have tried other functions in Preferences.h with same result.
#include <Arduino.h>
#include <Preferences.h>
#include <nvs_flash.h>
Preferences prefs;
const char nameSpace[]="nameSpace";
const char key[]="myKey";
void eraseNVS() {
nvs_flash_erase(); // erase the NVS partition and...
nvs_flash_init(); // initialize the NVS partition.
Serial.printf("NVS erased, free entries=%d\n", prefs.freeEntries());
}
void test1() {
prefs.begin(nameSpace);
Serial.printf("Previous value from NVS = %lu\n", prefs.getUInt(key));
uint newVal=micros();
Serial.printf("New value = %lu\n", newVal);
prefs.putUInt(key, newVal);
Serial.printf("New value from NVS = %lu\n", prefs.getUInt(key));
prefs.end();
}
void setup() {
Serial.begin(115200);
Serial.println();
//eraseNVS(); // Uncomment to clear NVS.
test1();
}
void loop() {}
The issue is with your code, as you always write and read the same value from the flash!
Here is what happens:
- The ESP boots up
- It gets the current micros()
- This value is written to the preferences (nvs)
- The value is read out again and printed (same value as above)
The current micros will (nearly) always be the exact same value.
So the question is, what do you want to acheive?
Thank you for helping with this, here is an example:
I reset the ESP and get the following
Previous value from NVS = 27862
New value = 27888
New value from NVS = 27888
Then I upload the program (same program, no changes) to ESP and get:
Previous value from NVS = 27890
New value = 27877
New value from NVS = 27877
I would expect the value 27888 (first run) to show up as “Previous value” but it is 27890, clearly not the same. I use micros() only as a mean to get different values for presentation purpose. Any thoughts?
Okay 
Yes that works.
Also between two uploads, the NVS does not get modified.
It works as expected.
After uploading there might be one or two reboot’s you don’t see as the serial monitor connection is not yet restablished.
So change your setup()
to wait a few seconds:
void setup() {
Serial.begin(115200);
for (size_t i=3; i>0; i--) {
Serial.println(i);
delay(1000);
}
// eraseNVS(); // Uncomment to clear NVS.
test1();
}
Awesame, thanks.
It works, I would not have thought that there can be several reboots.
Just for fun I tested (without your code) a delay() between getUInt and putUInt and that works if delay is >=1900 msec.
1 Like