Arduino-Storage
External Memory Storage library for Arduino
Persistent.ino
Go to the documentation of this file.
1 #include "Storage.h"
2 #include "Driver/EEPROM.h"
3 
4 // Use internal eeprom for configuration storage
6 
7 // Configuration values
8 struct config_t {
9  uint32_t timestamp;
10  char ssid[32];
11  uint8_t mac[6];
12 };
13 
14 // Macro to enforce naming convention
15 #define PERSISTENT(v) persistent_ ## v
16 
17 // Reset to default configuration flag
18 bool reset;
20 
21 // Persistent configuration
23 Storage::Cache PERSISTENT(config)(eeprom, &config, sizeof(config));
24 
25 // Default configuration
26 static const char ssid[] PROGMEM = "Wi-Fi SSID";
27 static const uint8_t mac[6] PROGMEM = { 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed };
28 
29 void setup()
30 {
31  Serial.begin(57600);
32  while (!Serial);
33 
34  // Check the reset flag; write default configuration or read persistent
35  PERSISTENT(reset).read();
36  if (reset) {
37  Serial.println(F("Write default configuration"));
38  config.timestamp = 0;
39  strcat_P(config.ssid, ssid);
40  memcpy_P(config.mac, mac, sizeof(mac));
41  PERSISTENT(config).write();
42  reset = false;
43  PERSISTENT(reset).write();
44  }
45  else {
46  Serial.println(F("Read configuration"));
47  PERSISTENT(config).read();
48  }
49 
50  Serial.print(millis() / 1000.0);
51  Serial.print(F(":reset@"));
52  Serial.print(PERSISTENT(reset).addr());
53  Serial.print(F(" = "));
54  Serial.println(reset);
55 }
56 
57 void loop()
58 {
59  static uint8_t n = 0;
60  uint32_t start = millis();
61 
62  // Print configuration
63  Serial.print(start / 1000.0);
64  Serial.print(F(":config@"));
65  Serial.print(PERSISTENT(config).addr());
66  Serial.print(F(": timestamp = "));
67  Serial.print(config.timestamp);
68  Serial.print(F(", ssid = \""));
69  Serial.print(config.ssid);
70  Serial.print(F("\", mac = "));
71  for (size_t i = 0; i < sizeof(config.mac); i++) {
72  Serial.print(config.mac[i], HEX);
73  if (i + 1 < sizeof(config.mac)) Serial.print(':');
74  }
75  Serial.println();
76  Serial.flush();
77  uint32_t ms = millis() - start;
78  delay(1000 - ms);
79  if (++n < 60) return;
80  n = 0;
81 
82  // Update timestamp every minute and write to eeprom
83  Serial.println(F("Update timestamp"));
84  config.timestamp++;
85  PERSISTENT(config).Block::write(offsetof(config_t, timestamp),
86  &config.timestamp,
87  sizeof(config.timestamp));
88 }
uint8_t mac[6]
Definition: Persistent.ino:11
char ssid[32]
Definition: Persistent.ino:10
Definition: EEPROM.h:27
void loop()
Definition: Persistent.ino:57
bool reset
Definition: Persistent.ino:18
EEPROM eeprom
Definition: Persistent.ino:5
#define PERSISTENT(v)
Definition: Persistent.ino:15
void setup()
Definition: Persistent.ino:29
config_t config
Definition: Persistent.ino:22
uint32_t timestamp
Definition: Persistent.ino:9