Skip to content

Instantly share code, notes, and snippets.

@lonelybinary
Last active June 18, 2023 05:36
Show Gist options
  • Save lonelybinary/e2f4110fde911ef6343c899327600ea6 to your computer and use it in GitHub Desktop.
Save lonelybinary/e2f4110fde911ef6343c899327600ea6 to your computer and use it in GitHub Desktop.
Arduino ESP32 Leveraging Preferences for Permanent Data Retention
/*
In the following example, we will use preferences to record the ESP32 boot times.
*/
#include <Preferences.h>
Preferences preferences;
String str_key_type(int key_type);
void setup() {
Serial.begin(115200);
// Open the Preferences with namespace "lonelybinary" with read and write permission
preferences.begin("lonelybinary", false);
/*
try to read the counter from the namespace "lonelybinary"
if the counter does not exist, it will return a default value of 0
*/
int counter = preferences.getInt("counter", 0);
counter++;
// Print the counter to Serial Monitor
Serial.printf("Current reboot counter value: %u\n", counter);
Serial.print("Is key Exist? : ");
Serial.println(preferences.isKey("counter") ? "Yes" : "No");
Serial.print("Key Type : ");
Serial.println(str_key_type(preferences.getType("counter")));
// Store the counter to the Preferences
preferences.putUInt("counter", counter);
// Close the Preferences
preferences.end();
Serial.println("Restarting in 30 seconds...");
delay(30000);
ESP.restart();
}
void loop() {}
String str_key_type(int key_type) {
switch (key_type) {
case PT_I8:
return "PT_I8";
case PT_U8:
return "PT_U8";
case PT_I16:
return "PT_I16";
case PT_U16:
return "PT_U16";
case PT_I32:
return "PT_I32";
case PT_U32:
return "PT_U32";
case PT_I64:
return "PT_I64";
case PT_U64:
return "PT_U64";
case PT_STR:
return "PT_STR";
case PT_BLOB:
return "PT_BLOB";
case PT_INVALID:
return "PT_INVALID";
default:
return "UNKNOWN";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment