|
| 1 | +/* |
| 2 | +This example shows how to use Preferences (nvs) to store a |
| 3 | +structure. Note that the maximum size of a putBytes is 496K |
| 4 | +or 97% of the nvs partition size. nvs has signifcant overhead, |
| 5 | +so should not be used for data that will change often. |
| 6 | +*/ |
| 7 | +#include <Preferences.h> |
| 8 | +Preferences prefs; |
| 9 | + |
| 10 | +typedef struct { |
| 11 | + uint8_t hour; |
| 12 | + uint8_t minute; |
| 13 | + uint8_t setting1; |
| 14 | + uint8_t setting2; |
| 15 | +} schedule_t; |
| 16 | + |
| 17 | +void setup() { |
| 18 | + Serial.begin(115200); |
| 19 | + |
| 20 | + if (!prefs.begin("schedule")) { // use "schedule" namespace |
| 21 | + Serial.println("Cannot initialize preferences"); |
| 22 | + Serial.println("Make sure your WiFi firmware version is greater than 0.3.0"); |
| 23 | + while(1) {}; |
| 24 | + } |
| 25 | + uint8_t content[] = {9, 30, 235, 255, 20, 15, 0, 1}; // two entries |
| 26 | + prefs.putBytes("schedule", content, sizeof(content)); |
| 27 | + size_t schLen = prefs.getBytesLength("schedule"); |
| 28 | + char buffer[schLen]; // prepare a buffer for the data |
| 29 | + prefs.getBytes("schedule", buffer, schLen); |
| 30 | + if (schLen % sizeof(schedule_t)) { // simple check that data fits |
| 31 | + Serial.println("Data is not correct size!"); |
| 32 | + return; |
| 33 | + } |
| 34 | + schedule_t *schedule = (schedule_t *) buffer; // cast the bytes into a struct ptr |
| 35 | + Serial.print(schedule[1].hour); |
| 36 | + Serial.print(":"); |
| 37 | + Serial.print(schedule[1].minute); |
| 38 | + Serial.print(" "); |
| 39 | + Serial.print(schedule[1].setting1); |
| 40 | + Serial.print("/"); |
| 41 | + Serial.print(schedule[1].setting2); |
| 42 | + Serial.println(); |
| 43 | + |
| 44 | + schedule[2] = {8, 30, 20, 21}; // add a third entry (unsafely) |
| 45 | + |
| 46 | + // force the struct array into a byte array |
| 47 | + prefs.putBytes("schedule", schedule, 3*sizeof(schedule_t)); |
| 48 | + schLen = prefs.getBytesLength("schedule"); |
| 49 | + char buffer2[schLen]; |
| 50 | + prefs.getBytes("schedule", buffer2, schLen); |
| 51 | + for (int x=0; x<schLen; x++) Serial.print((uint8_t)buffer[x]); |
| 52 | + Serial.println(); |
| 53 | + prefs.end(); |
| 54 | +} |
| 55 | + |
| 56 | +void loop() {} |
0 commit comments