When yous create a datalogging It's of import to structure your data, sometime a proficient solution can be JSON format.
JavaScript Object Note (JSON) is an open-standard file format that uses human being-readable text to transmit data objects consisting of aspect–value pairs and array data types (or whatever other serializable value). It is a very common data format used for asynchronous browser–server communication, including as a replacement for XML in some AJAX-style systems.
JSON is a language-independent data format. It was derived from JavaScript, only as of 2017 many programming languages include code to generate and parse JSON-format data. The official Internet media type for JSON isawarding/json
. JSON filenames use the extension.json
. (cit. wiki)
For case, you demand to archive and update the value of some totals many times, you can create a construction like this:
{ "lastUpdate": "05/06/2019 06:l:57", "energyLifetime": 21698620, "energyYearly": 1363005, "energyMonthly": 58660, "energyWeekly": 41858, "energyDaily": 158 }
Here an example of bombardment voltage log:
{ "lastUpdate": "30/01/2019 21:24:34", "data": { "1004": 3.914468, "1024": 3.931694, "1044": 3.90479, "1104": 3.973645, "1124": 3.969726, "1144": three.954823, "1204": 3.957871, "1224": 3.930581, "1244": iii.954048, "1304": 3.947516, "1324": 3.945629, "1344": three.863081, "1404": iii.919597, "1424": 3.927387, "1444": 3.912968, "1504": 3.856597, "1524": 3.846629, "1544": 3.903871, "1604": 3.857226, "1624": three.889839, "1644": 3.865693, "1704": 3.846145, "1724": 3.780726, "1744": 3.846677, "1804": iii.770323, "1824": three.778887, "1844": iii.769597, "1904": 3.778693, "1924": 3.806177, "1944": 3.801145, "2004": 3.744049, "2024": 3.707661, "2044": 3.780871, "2104": 3.708484, "2124": 3.729726, "0003": 4.138742, "0023": iv.147887, "0043": four.143387, "0103": 4.139806, "0123": 4.078258, "0143": 4.128, "0203": four.107871, "0223": iv.066645, "0243": iv.103419, "0303": 4.082081, "0323": 4.126839, "0343": 4.118032, "0403": 4.096113, "0423": iv.110532, "0443": four.099307, "0503": 4.013565, "0523": 4.089581, "0544": 4.075549, "0604": 4.025274, "0624": 4.067129, "0644": 3.997742, "0704": 3.987677, "0724": iii.981823, "0744": 4.006113, "0804": 4.0035, "0824": three.966968, "0844": 4.016418, "0904": 3.969049, "0924": four.002532, "0944": 3.907742 } }
As you tin can see It's more readable than CSV or other format, and It'south more than versatile.
Library
For Arduino like system exist a library that can be considered a standard, you can download It from github or Arduino IDE library management.
For this library be a site besides very informative.
How to
The usage is quite simply, the difference from previous version is that DynamicJsonDocument
is no more than dynamic manage of retentiveness, so now we can apply that document for all (static and dynamic).
const size_t chapters = 1024; DynamicJsonDocument md(capacity);
It's importanto to calculate the capacity is the max size of your file, to take an idea of the size you need you tin bank check here, Information technology'southward a simple calculator that from file give yous the relative size.
To set up the SD you tin refer to my article "How to employ SD card with esp8266 and Arduino".
In this case we write a file like:
{ "energyLifetime": 21698620, "energyYearly": 1363005 }
A classic configuration file construction.
I add a comment on all relevant code.
/* Write JSON file to SD { "energyLifetime": 21698620, "energyYearly": 1363005 } by Mischianti Renzo <https://www.mischianti.org> https://www.mischianti.org/ */ #include <ArduinoJson.h> #include <SD.h> #include <SPI.h> const int chipSelect = iv; const char *filename = "/examination.txt"; // <- SD library uses 8.3 filenames // Prints the content of a file to the Serial void printFile(const char *filename) { // Open file for reading File file = SD.open(filename); if (!file) { Serial.println(F("Failed to read file")); return; } // Extract each characters past one past 1 while (file.available()) { Series.print((char)file.read()); } Serial.println(); // Close the file file.close(); } void setup() { // Initialize serial port Series.brainstorm(9600); while (!Serial) continue; delay(500); // Initialize SD library while (!SD.begin(chipSelect)) { Serial.println(F("Failed to initialize SD library")); filibuster(1000); } SD.remove(filename); // Open file for writing File file = SD.open(filename, FILE_WRITE); if (!file) { Serial.println(F("Failed to create file")); return; } // Classify a temporary JsonDocument // Don't forget to modify the capacity to friction match your requirements. // Utilise arduinojson.org/v6/banana to compute the capacity. // StaticJsonDocument<512> doc; // You tin can use DynamicJsonDocument as well DynamicJsonDocument doc(512); // Set the values in the document doctor["energyLifetime"] = 21698620; doc["energyYearly"] = 1363005; // Serialize JSON to file if (serializeJson(doc, file) == 0) { Serial.println(F("Failed to write to file")); } // Close the file file.close(); // Print test file Series.println(F("Print test file...")); printFile(filename); } void loop() { // not used in this example }
Generate an assortment of data, add an chemical element every 5 seconds and update the original file.
The construction generated is like this:
{ "millis": 10735, "data": [ { "prevNumOfElem": ane, "newNumOfElem": 2 }, { "prevNumOfElem": 2, "newNumOfElem": 3 }, { "prevNumOfElem": 3, "newNumOfElem": 4 } ] }
Where millis is overrided and a new value appear on assortment every time.
/* Write JSON file to SD by Mischianti Renzo <https://www.mischianti.org> https://www.mischianti.org/ */ #include <ArduinoJson.h> #include <SD.h> #include <SPI.h> const int chipSelect = four; const char *filename = "/exam.jso"; // <- SD library uses viii.3 filenames // Prints the content of a file to the Serial void printFile(const char *filename) { // Open up file for reading File file = SD.open(filename); if (!file) { Serial.println(F("Failed to read file")); render; } // Extract each characters by one past one while (file.available()) { Serial.impress((char) file.read()); } Serial.println(); // Close the file file.close(); } void setup() { // Initialize series port Series.brainstorm(9600); while (!Series) keep; delay(500); // Initialize SD library while (!SD.begin(chipSelect)) { Serial.println(F("Failed to initialize SD library")); delay(1000); } Serial.println(F("SD library initialized")); Serial.println(F("Delete original file if exists!")); SD.remove(filename); } void loop() { // Allocate a temporary JsonDocument // Don't forget to alter the capacity to match your requirements. // Use arduinojson.org/v6/assistant to compute the capacity. // StaticJsonDocument<512> doc; // You can apply DynamicJsonDocument too DynamicJsonDocument doc(1024); JsonObject obj; // Open file File file = SD.open(filename); if (!file) { Serial.println(F("Failed to create file, probably not exists")); Serial.println(F("Create an empty one!")); obj = doc.to<JsonObject>(); } else { DeserializationError error = deserializeJson(doc, file); if (error) { // if the file didn't open up, print an fault: Serial.println(F("Error parsing JSON ")); Series.println(fault.c_str()); // create an empty JSON object obj = physician.to<JsonObject>(); } else { // GET THE ROOT OBJECT TO Manipulate obj = doc.equally<JsonObject>(); } } // close the file already loaded: file.shut(); obj[F("millis")] = millis(); JsonArray information; // Check if be the array if (!obj.containsKey(F("information"))) { Series.println(F("Non detect data array! Crete one!")); data = obj.createNestedArray(F("data")); } else { Serial.println(F("Find data array!")); data = obj[F("data")]; } // create an object to add to the assortment JsonObject objArrayData = data.createNestedObject(); objArrayData["prevNumOfElem"] = data.size(); objArrayData["newNumOfElem"] = data.size() + 1; SD.remove(filename); // Open file for writing file = SD.open(filename, FILE_WRITE); // Serialize JSON to file if (serializeJson(dr., file) == 0) { Series.println(F("Failed to write to file")); } // Close the file file.close(); // Print test file Serial.println(F("Print exam file...")); printFile(filename); delay(5000); }
Now let's organize the lawmaking a bit. The lawmaking in this format is unusable, just with 2 simple functions it should improve.
/* Write JSON file to SD by Renzo Mischianti <https://www.mischianti.org> https://www.mischianti.org/ */ #include <ArduinoJson.h> #include <SD.h> #include <SPI.h> const int chipSelect = four; const char *filename = "/test.jso"; // <- SD library uses 8.three filenames File myFileSDCart; /** * Part to deserialize file from SD * by Renzo Mischianti <https://www.mischianti.org> * instance: * DynamicJsonDocument doc(1024); JsonObject obj; obj = getJSonFromFile(&doc, filename); */ JsonObject getJSonFromFile(DynamicJsonDocument *doc, String filename, bool forceCleanONJsonError = true ) { // open the file for reading: myFileSDCart = SD.open(filename); if (myFileSDCart) { // read from the file until at that place's nothing else in it: // if (myFileSDCart.available()) { // firstWrite = fake; // } DeserializationError error = deserializeJson(*dr., myFileSDCart); if (error) { // if the file didn't open, impress an error: Series.print(F("Mistake parsing JSON ")); Serial.println(mistake.c_str()); if (forceCleanONJsonError){ return doc->to<JsonObject>(); } } // close the file: myFileSDCart.close(); return doc->every bit<JsonObject>(); } else { // if the file didn't open up, impress an error: Serial.print(F("Mistake opening (or file not exists) ")); Serial.println(filename); Serial.println(F("Empty json created")); return doc->to<JsonObject>(); } } /** * Part to serialize file to SD * by Renzo Mischianti <https://www.mischianti.org> * instance: * boolean isSaved = saveJSonToAFile(&doc, filename); */ bool saveJSonToAFile(DynamicJsonDocument *dr., String filename) { SD.remove(filename); // open the file. notation that only i file tin can be open at a time, // so you take to close this one earlier opening some other. Serial.println(F("Open file in write mode")); myFileSDCart = SD.open(filename, FILE_WRITE); if (myFileSDCart) { Serial.print(F("Filename --> ")); Serial.println(filename); Serial.print(F("Kickoff write...")); serializeJson(*doc, myFileSDCart); Serial.print(F("...")); // close the file: myFileSDCart.close(); Serial.println(F("washed.")); return true; } else { // if the file didn't open up, print an error: Serial.print(F("Error opening ")); Serial.println(filename); return false; } } // Prints the content of a file to the Serial void printFile(const char *filename) { // Open file for reading File file = SD.open(filename); if (!file) { Serial.println(F("Failed to read file")); render; } // Excerpt each characters by one by one while (file.available()) { Serial.print((char) file.read()); } Serial.println(); // Close the file file.close(); } void setup() { // Initialize series port Serial.begin(9600); while (!Serial) go on; filibuster(500); // Initialize SD library while (!SD.begin(chipSelect)) { Serial.println(F("Failed to initialize SD library")); delay(1000); } Series.println(F("SD library initialized")); Serial.println(F("Delete original file if exists!")); SD.remove(filename); } void loop() { // Allocate a temporary JsonDocument // Don't forget to change the capacity to match your requirements. // Use arduinojson.org/v6/assistant to compute the capacity. // StaticJsonDocument<512> doctor; // You can employ DynamicJsonDocument equally well DynamicJsonDocument doc(1024); JsonObject obj; obj = getJSonFromFile(&doctor, filename); obj[F("millis")] = millis(); JsonArray data; // Cheque if exist the array if (!obj.containsKey(F("data"))) { Series.println(F("Not find data array! Crete one!")); data = obj.createNestedArray(F("information")); } else { Serial.println(F("Detect data array!")); data = obj[F("information")]; } // create an object to add together to the assortment JsonObject objArrayData = data.createNestedObject(); objArrayData["prevNumOfElem"] = data.size(); objArrayData["newNumOfElem"] = data.size() + 1; boolean isSaved = saveJSonToAFile(&doc, filename); if (isSaved){ Series.println("File saved!"); }else{ Serial.println("Error on relieve File!"); } // Print test file Series.println(F("Print examination file...")); printFile(filename); delay(5000); }
Now I think information technology'south improved and it's pretty articulate.
Thanks
How to Read Information From a Json File From Internet on Arduino
Source: https://www.mischianti.org/2020/01/26/manage-json-file-with-arduino-and-esp8266/
Komentar
Posting Komentar