|
| 1 | +/* |
| 2 | + Microcontroller startup counter example with ESP32 Preferences library. |
| 3 | +
|
| 4 | + This simple example demonstrates using the Preferences library to store how many times |
| 5 | + the microcontroller has booted. The Preferences library is a wrapper around the Non-volatile |
| 6 | + storage on ESP32 processor. |
| 7 | +
|
| 8 | + created for arduino-esp32 09 Feb 2017 |
| 9 | + by Martin Sloup (Arcao) |
| 10 | +*/ |
| 11 | + |
| 12 | +#include <Preferences.h> |
| 13 | + |
| 14 | +Preferences preferences; |
| 15 | + |
| 16 | +void setup() { |
| 17 | + Serial.begin(115200); |
| 18 | + while(!Serial); |
| 19 | + Serial.println(); |
| 20 | + |
| 21 | + // Open Preferences with my-app namespace. Each application module, library, etc |
| 22 | + // has to use a namespace name to prevent key name collisions. We will open storage in |
| 23 | + // RW-mode (second parameter has to be false). |
| 24 | + // Note: Namespace name is limited to 15 chars. |
| 25 | + if (!preferences.begin("my-app1", false)) { |
| 26 | + Serial.println("Cannot initialize preferences"); |
| 27 | + Serial.println("Make sure your WiFi firmware version is greater than 0.3.0"); |
| 28 | + while(1) {}; |
| 29 | + } |
| 30 | + |
| 31 | + // Serial.println(">Clear"); |
| 32 | + // preferences.clear(); |
| 33 | + // Serial.println("<Clear"); |
| 34 | + |
| 35 | + |
| 36 | + // Remove all preferences under the opened namespace |
| 37 | + //preferences.clear(); |
| 38 | + |
| 39 | + // Or remove the counter key only |
| 40 | + //preferences.remove("counter"); |
| 41 | + |
| 42 | + // Get the counter value, if the key does not exist, return a default value of 0 |
| 43 | + // Note: Key name is limited to 15 chars. |
| 44 | + unsigned int counter = preferences.getUInt("counter2", 0); |
| 45 | + |
| 46 | + // Increase counter by 1 |
| 47 | + counter++; |
| 48 | + |
| 49 | + // Print the counter to Serial Monitor |
| 50 | + Serial.print("Current counter value: "); |
| 51 | + Serial.println(counter, HEX); |
| 52 | + |
| 53 | + // Store the counter to the Preferences |
| 54 | + preferences.putUInt("counter2", counter); |
| 55 | + |
| 56 | + // Close the Preferences |
| 57 | + preferences.end(); |
| 58 | + |
| 59 | + // Wait 10 seconds |
| 60 | + Serial.println("Restarting in 10 seconds..."); |
| 61 | + delay(10000); |
| 62 | + |
| 63 | + // Reset |
| 64 | + NVIC_SystemReset(); |
| 65 | +} |
| 66 | + |
| 67 | +void loop() {} |
0 commit comments