ProgmemExample.ino 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  3. // MIT License
  4. //
  5. // This example shows the different ways you can use Flash strings with
  6. // ArduinoJson.
  7. //
  8. // Use Flash strings sparingly, because ArduinoJson duplicates them in the
  9. // JsonDocument. Prefer plain old char*, as they are more efficient in term of
  10. // code size, speed, and memory usage.
  11. //
  12. // https://arduinojson.org/v6/example/progmem/
  13. #include <ArduinoJson.h>
  14. void setup() {
  15. #ifdef PROGMEM // <- check that Flash strings are supported
  16. DynamicJsonDocument doc(1024);
  17. // You can use a Flash String as your JSON input.
  18. // WARNING: the strings in the input will be duplicated in the JsonDocument.
  19. deserializeJson(doc, F("{\"sensor\":\"gps\",\"time\":1351824120,"
  20. "\"data\":[48.756080,2.302038]}"));
  21. JsonObject obj = doc.as<JsonObject>();
  22. // You can use a Flash String to get an element of a JsonObject
  23. // No duplication is done.
  24. long time = obj[F("time")];
  25. // You can use a Flash String to set an element of a JsonObject
  26. // WARNING: the content of the Flash String will be duplicated in the
  27. // JsonDocument.
  28. obj[F("time")] = time;
  29. // You can set a Flash String to a JsonObject or JsonArray:
  30. // WARNING: the content of the Flash String will be duplicated in the
  31. // JsonDocument.
  32. obj["sensor"] = F("gps");
  33. // It works with serialized() too:
  34. obj["sensor"] = serialized(F("\"gps\""));
  35. obj["sensor"] = serialized(F("\xA3gps"), 3);
  36. // You can compare the content of a JsonVariant to a Flash String
  37. if (obj["sensor"] == F("gps")) {
  38. // ...
  39. }
  40. #else
  41. #warning PROGMEM is not supported on this platform
  42. #endif
  43. }
  44. void loop() {
  45. // not used in this example
  46. }
  47. // See also
  48. // --------
  49. //
  50. // https://arduinojson.org/ contains the documentation for all the functions
  51. // used above. It also includes an FAQ that will help you solve any memory
  52. // problem.
  53. //
  54. // The book "Mastering ArduinoJson" contains a quick C++ course that explains
  55. // how your microcontroller stores strings in memory. It also tells why you
  56. // should not abuse Flash strings with ArduinoJson.
  57. // Learn more at https://arduinojson.org/book/
  58. // Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤