LoginSignup
3
0

More than 5 years have passed since last update.

ArduinoJson メモ

Posted at

ArduinoJsonですが、JsonBufferをグローバルに確保して、state管理のために使用していたところ、一定時間経過後、データが更新されない状態になりました。
調べていたところ、以下の説明がありました。
Why shouldn't I use a global JsonBuffer?
https://arduinojson.org/faq/why-shouldnt-i-use-a-global-jsonbuffer/?utm_source=github&utm_medium=issues

グローバルなJsonBufferは値を追加・更新していった時にメモリーが解放されないようです。
値を更新するたびにメモリー使用量が増加して、最後は更新できなくなる。ということが原因のようでした。

各ステートの前後比較をするために使用したかったのですが、そのように使用するには以下のように、データ格納先をまず確保して
データを扱うたびにJsonBufferを確保してJsonとして扱う、ということが必要です。

struct SensorData {
   const char* name;
   int time;
   float value;
};

#define SENSORDATA_JSON_SIZE (JSON_OBJECT_SIZE(3))

bool deserialize(SensorData& data, char* json)
{
    StaticJsonBuffer<SENSORDATA_JSON_SIZE> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(json);
    data.name = root["name"];
    data.time = root["time"];
    data.value = root["value"];
    return root.success();
}

void serialize(const SensorData& data, char* json, size_t maxSize)
{
    StaticJsonBuffer<SENSORDATA_JSON_SIZE> jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["name"] = data.name;
    root["time"] = data.time;
    root["value"] = data.value;
    root.printTo(json, maxSize);
}```
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0