Json arduino как использовать

от admin

Библиотека ArduinoJson

ArduinoJson доступна через менеджер библиотек в Arduino IDE. Для работы с библиотекой нужно включить заголовочный файл.

Пример десериализации файла и вывод только необходимых данных показан в статье Узнаём погоду через OpenWeatherMap.

Создание JSON-файла

Рассмотрим пример создания JSON-файла с необходимыми данными.

В мониторе порта смотрим, как выглядит запись в JSON-формате.

MessagePack. Сериализация

Кроме текстового формата JSON существует бинарный формат MessagePack. Честно признаюсь, никогда о нём не слышал до чтения примеров для библиотеки. MessagePack имеет преимущество — он эффективен для передачи данных, занимая меньше места. Это может оказаться решающим фактором при больших объёмах данных.

Пример с сериализацией не сильно отличается от аналогичного примера для JSON.

Проверить корректность данных можно на сайте msgpack-lite, декодируя набор байт.

В коде есть код, обрамлённый комментариями. Он позволяет узнать требуемый размер сообщения до отправки, не пересылая сами данные. Это пригодится, чтобы оценить объём данных и принять решение об отправке. Во время отправки сообщения этот код избыточен, так как при отправке сообщения мы можем уже сами посчитать количество отсылаемых байтов.

ide: Arduinojson

By Thomas Gumbricht October 31, 2022 October 31, 2022 Tweet Like +1

Introduction

Arduinojson is a library for serialization and deserialization of json structured documents in Arduino IDE. This post outlines how to install and use Arduinojson. The post also contains the complete json code for version 0.78 of xSpectre handheld spectrometer.

Arduinojson

Arduinojson is an evolving project and widely used as a standard container for transferring data to and from Arduino microcontrollers. When receiving data to the Arduino microcontroller, arduinojson deserializes the content to ordinary data and when packaging data for sending from the microcontroller, arduinojson serializes the data.

Add Arduinojson library

Open Arduino IDE , from the menu select:

Tools -> Manage Libraries…

Type arduinojeson in the search box . The json library you want to install is the one by Benoit Blanchon, Arduinojson. At time of writing this in October 2022 the version available is 6.19.4. Go ahead and install . Accept to install additional libraries required.

Deserialize (decode) json

Start a new Arduino IDE sketch and import Arduinojson.

Arduino JSON uses a preallocated memory pool to store the JsonObject tree, this is done by the StaticJsonBuffer. You can use ArduinoJson Assistant to compute the exact buffer size, but for this example 200 is enough.

Create a char array called json[] to store a sample JSON string, you have to escape (“/”) for passing the syntax demands of both Arduino and Arduinojson:

ESP8266 уроки. Анализ JSON в среде Arduino IDE.

В этом уроке ESP8266 создадим простую программу для синтаксического анализа строки JSON, имитирующей данные с датчика, и вывод полученных значений в последовательный порт. Для данного урока вам нужно установить библиотеки ESP8266 для Arduino IDE, о чем рассказывал здесь.

Чтобы избежать ручного декодирования строки в пригодные для использования значения, будем использовать библиотеку ArduinoJson, которая предоставляет простые в использовании классы и методы для синтаксического анализа JSON. С библиотекой и ее возможностями можно ознакомиться на GitHub.

Эта очень полезная библиотека позволяет, как кодировать, так и декодировать JSON, она очень эффективна и работает на ESP8266. Её можно установить через «менеджер библиотек» Arduino IDE, как показано на рисунке ниже.

библиотеку ArduinoJson

Основные настройки для работы esp8266 json http.

Прежде всего, необходимо подключить библиотеку ArduinoJson, реализующую функцию синтаксического анализа.

Поскольку в этой библиотеке есть некоторые приемы, позволяющие избежать проблем при ее использовании, в этом уроке будет показано, как анализировать локально созданную строку, и поэтому мы не будем использовать функции WiFi. Итак, мы просто запустим последовательное соединение. Но вы можете использовать esp8266 json http на основании предыдущих уроков.

Основной код разбора JSON с помощью ESP8266.

В функции основного цикла loop() объявим сообщение JSON, которое будет проанализировано. Символы «\» используются для экранирования двойных кавычек в строке, поскольку имена JSON требуют двойных кавычек.

Эта простая структура состоит из 2 пар «имя : значение», соответствующих типу датчика и значению для этого датчика. Для удобства чтения, структура JSON данных показана ниже без экранирования символов.

Затем нам нужно объявить объект класса StaticJsonDocument. Он будет соответствовать предварительно выделенному пулу памяти для хранения дерева объектов, и его размер указывается в параметре шаблона (значение между <> ) в байтах.

В этом случае мы объявили размер 300 байт, что более чем достаточно для строки, которую хотим проанализировать. Автор библиотеки указывает здесь два подхода к определению размера буфера. Лично я предпочитаю объявлять буфер, имеющий достаточный размер для ожидаемой полезной нагрузки сообщения, и проверять наличие ошибок на этапе синтаксического анализа.

Библиотека также поддерживает динамическое выделение памяти, но такой подход не рекомендуется.

Затем вызываем объект DeserializationError, передавая строку JSON в качестве аргумента.

Чтобы проверить, успешно ли был проанализирован JSON, проверим, удалось ли выполнить синтаксический анализ.

После этого можем использовать оператор индекса для получения проанализированных значений по их именам. Проверяем здесь информацию об операторе нижнего индекса. Другими словами, это означает, что мы используем квадратные скобки и имена параметров для получения их значений, как показано ниже

Код основного цикла программы показана ниже. Мы включили несколько дополнительных выводов информации, чтобы отделить каждую итерацию функции цикла и показать, как исходная строка изменяется при синтаксическом анализе. Нам нужно напечатать значения char из char, потому что синтаксический анализатор включает символы «\0», и поэтому, если бы мы использовали Serial.println (JSONMessage), мы бы просто видели содержимое до первого символа «\0».

Проверка кода вывода значений полученных из JSON с помощью ESP8266 (NodeMCU).

Чтобы протестировать код, просто скомпилируйте его, и загрузите на плату ESP8266 (NodeMCU). После этого откройте последовательный монитор Arduino IDE. На рисунке ниже показан результат, вывода данных в последовательный порт.

Проверка кода вывода значений полученных из JSON с помощью ESP8266 (NodeMCU).

Как видим, у этой библиотеки есть некоторые особенности, которые должны учитывать при ее использовании, чтобы избежать неожиданных проблем. К счастью, страница этой библиотеки на GitHub очень хорошо документирована, и поэтому здесь есть раздел, описывающий, как избежать ошибок.

Кроме того, настоятельно рекомендую проверить примеры программ, которые устанавливаются вместе с библиотекой, которые очень хорошо подходят для понимания того, как она работает.

Заключение к уроку Arduino json esp8266.

Заключение к уроку Arduino json esp8266.

В этом уроке показано, как легко анализировать JSON при помощи ESP8266 в среде Arduino. Естественно, это позволяет изменять данные в хорошо известном структурированном формате, который может быть легко интерпретирован другими приложениями, без необходимости реализации определенного протокола.

Поскольку микроконтроллеры и устройства IoT имеют ограниченные ресурсы, JSON создает гораздо меньше расходов ресурсов, чем, например, XML, и поэтому является очень хорошим выбором.

Тем не менее, нужно иметь в виду, что для некоторых интенсивных приложений даже JSON может создавать недопустимые нагрузки, и поэтому нам может потребоваться перейти на байтовые протоколы. Но для простых приложений, таких как чтение данных с датчика и отправка их на удаленный сервер или получение набора конфигураций, JSON является очень хорошей альтернативой.

Понравился ESP826 урок. Анализ JSON в среде Arduino IDE? Не забудь поделиться с друзьями в соц. сетях.

А также подписаться на наш канал на YouTube, вступить в группу Вконтакте, в группу на Facebook.

How to parse JSON Data with Arduino (ArduinoJson Tutorial)

Disclosure: Some of the links below are affiliate links. This means that, at zero cost to you, I will earn an affiliate commission if you click through the link and finalize a purchase. Learn Robotics is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a way for websites to earn advertising revenues by advertising and linking to Amazon.com.

Читать:
Inline coupler что это

Enjoy this article? Buy me a coffee

Liz Miller Learn Robotics

Attention: Mid-Senior Engineer Earning $80k/yr+ Ready to Break $100k-$200k/yr

Experienced Engineers: Upgrade to a $100k-$200k Robotics Career in 90 days or Less

Apply to work with our Robotics Career Consultants in our 12-Week Premium Mentorship Program.

In this article, learn how to parse JSON data with Arduino for IoT, IIoT, and Home Automation projects. We’ll start by connecting our wifi-enabled chip (ESP8266) to the Internet and then pointing it to the URL where the JSON file is stored. Then, we’ll use the ArduinoJson library to parse the JSON file into readable variables. Lastly, we’ll make checks against the variables to control outputs on our ESP8266.

JSON data is a lot easier to work with using Python, but if you’re creating an IoT device using Arduino, then this methodology comes in handy. Expect to spend an hour or so configuring this project.

This project is more advanced, so I recommend brushing up on the following topics if you’re new to Arduino and IoT.

The goal of this project is to create a secondary IoT device that receives data. If you’ve followed along with previous dweet.io tutorials, you’ll notice we spend a lot of time publishing data to a webpage. This tutorial expands on that project by creating a second device that fetches and interprets the published data.

If you’re looking to create your custom automation systems, then this can be very powerful because you’re essentially connecting two separate devices using the Internet.

Here’s a diagram of what the final solution looks like.

ArduinoJson and Dweet.io for Internet of Things

Now, let’s walk through the steps to get this working.

Materials for this Project

If you plan on using one device to publish data and another device to receive data, then you’ll need two separate ESP8266 controllers.

  • ESP8266 Controller (NodeMCU or Wemos D1 Mini) and Breadboard
  • or an IoT kit (I recommend this one.)

We’ll be demonstrating the project by sending data to the dweet.io website using a Wemos D1 Mini and then receiving data from that URL using a second device (NodeMCU). Lastly, we’ll parse the JSON file and use the data to control our LEDs.

Step 1: Wire Both Devices

Wire a potentiometer to the Wemos D1 Mini. Then, wire three LEDs to the NodeMCU. Here are some fritzing diagrams for your reference.

wiring diagrams wemos d1 mini and nodemcu for IoT project

Once your devices are wired, write and upload code to the Wemos D1 Mini to publish potentiometer data to dweet.io. We have an example of this in our Special Topics Robotics Course and this article. Then move on to the next step.

Step 2: Configure ArduinoJson Library

Install ArduinoJson library in Arduino IDE

To parse JSON files using Arduino, you’ll need to install the ArduinoJson library. Open up the Arduino IDE and go to Sketch > Include Library > Manage Libraries. Then search for ArduinoJson by Benoit Blanchon. Click the Install button. Then, include the header file at the top of your Arduino sketch.
#include <ArduinoJson.h>

Then, set up the sketch as you would normally. Define any global variables. Initialize the Serial Monitor at 115200 baud, and define any pin modes in the method. You’ll also need to connect the controller to the Internet.

Once you have the code written, it’s time to add some logic to fetch and parse JSON Data.

Step 3: View raw JSON data at the URL (dweet.io)

The first step is to view the raw JSON data hosted on dweet.io. Regardless of whether you publish this data from a device or use an existing device, it’s important to understand how the data is formatted so that we can receive it in a way that makes sense.

Open up your browser and go to dweet.io/see. Then click on the device name to see the current readings.

Find the raw JSON URL by going to dweet.io/get/latest/dweet/for/MYTHING. Replace “MYTHING” with the name of your thing. For this example, the thing name is “wemos,” so we’ll go to the URL https://dweet.io/get/latest/dweet/for/wemos

Step 4: Fetch Data from dweet.io using Arduino

Now, we’re ready to use ArduinoJson to fetch this data. Copy and paste the JSON information from dweet.io into the ArduinoJson V6 Assistant tool. This will give you the necessary notation to format and parse the JSON file correctly using the ArduinoJson library.

For this example, we care most about the potentiometer position, so we can update the variable for the potentiometer value to something more meaningful than int with_0_content_position . I’ve renamed this to potPosition for clarity. You can choose to use the generated code from the assistant tool, or modify it to best suit your application. I chose to print out the potentiometer value to the serial monitor once I receive it from the dweet.io website.

Step 5: Make Decisions based on Key-Value Pairs

Once you have the data, you can do whatever you’d like with it. Essentially, you have a local variable that can be used to toggle LEDs or local outputs based on conditions.

Let’s use the value of the potentiometer position to turn on the corresponding LED based on the following conditions.

If the position is less than 500, turn on the red LED. If the position is less than 750 and greater than 500, turn on the yellow LED. If the position is greater than 850, turn on the green LED. I chose to use global variables to hold these thresholds. You can opt to just hardcode the values if you’d like.

Here’s some example code that you can use to set up your device.

And that’s it! You can choose to update the local variable in real-time, store data into an array, create a CSV, or whatever else makes sense for your application. Once you have the data, the possibilities are endless!

Next Steps for Further Learning

In this tutorial, we learned how to parse a JSON file using Arduino. The data was stored on the dweet.io website, which we connected to and performed a GET HTTP request. Once we removed the headers and allocated the JSON file, we could use the ArduinoJson library to parse the key-value pairs and set a local variable. In turn, we were able to use this variable to check against a set of conditions and turn on a corresponding LED.

You can use this methodology to configure a network of IoT devices. These devices can automatically connect to a webpage, push and pull data, and make decisions based on the current values. As a result, you can unlock powerful, real-time metrics for applications in Industrial and Home Automation.

Join the Online Course: Be sure to sign up for the Special Topics Robotics Course to access starter code and earn a certificate for completing each of these projects.

If you enjoyed this tutorial, be sure to share it with a friend!

Похожие публикации