123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- #include <ArduinoJson.h>
- #include <SD.h>
- #include <SPI.h>
- struct Config {
- char hostname[64];
- int port;
- };
- const char *filename = "/config.txt";
- Config config;
- void loadConfiguration(const char *filename, Config &config) {
-
- File file = SD.open(filename);
-
-
-
- StaticJsonDocument<512> doc;
-
- DeserializationError error = deserializeJson(doc, file);
- if (error)
- Serial.println(F("Failed to read file, using default configuration"));
-
- config.port = doc["port"] | 2731;
- strlcpy(config.hostname,
- doc["hostname"] | "example.com",
- sizeof(config.hostname));
-
- file.close();
- }
- void saveConfiguration(const char *filename, const Config &config) {
-
- SD.remove(filename);
-
- File file = SD.open(filename, FILE_WRITE);
- if (!file) {
- Serial.println(F("Failed to create file"));
- return;
- }
-
-
-
- StaticJsonDocument<256> doc;
-
- doc["hostname"] = config.hostname;
- doc["port"] = config.port;
-
- if (serializeJson(doc, file) == 0) {
- Serial.println(F("Failed to write to file"));
- }
-
- file.close();
- }
- void printFile(const char *filename) {
-
- File file = SD.open(filename);
- if (!file) {
- Serial.println(F("Failed to read file"));
- return;
- }
-
- while (file.available()) {
- Serial.print((char)file.read());
- }
- Serial.println();
-
- file.close();
- }
- void setup() {
-
- Serial.begin(9600);
- while (!Serial) continue;
-
- const int chipSelect = 4;
- while (!SD.begin(chipSelect)) {
- Serial.println(F("Failed to initialize SD library"));
- delay(1000);
- }
-
- Serial.println(F("Loading configuration..."));
- loadConfiguration(filename, config);
-
- Serial.println(F("Saving configuration..."));
- saveConfiguration(filename, config);
-
- Serial.println(F("Print config file..."));
- printFile(filename);
- }
- void loop() {
-
- }
|