前言
单片机使用过程中,经常使用json和上位机进行通信,json数据格式为最常用的方式之一,以下简单介绍单片机串口接收json字符串的实现过程
c#include <ArduinoJson.h> int State = 0; boolean beginFlag = 0; String inputString = ""; // a String to hold incoming data bool stringComplete = false; // whether the string is complete StaticJsonDocument<200> doc; void setup() { // put your setup code here, to run once: while (!Serial); } void loop() { /*************串口数据接收**************/ while (Serial.available()) { // get the new byte: char inChar = Serial.read(); if (inChar == '{' && beginFlag == 0) { beginFlag = 1; } if (beginFlag == 1) { if (inChar == '{') { State += 1; } else if (inChar == '}') { State -= 1; } inputString += inChar; if (State == 0) { beginFlag = 0; stringComplete = true; } } } /*************接收数据解析及处理**************/ if (stringComplete) { stringComplete = false; //Serial.println(inputString); DeserializationError error = deserializeJson(doc, inputString.c_str()); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); inputString = ""; return; } //开始解析数据 inputString = ""; } }