In my recent project, I have to parse incoming JSON data in Arduino and I successfully did it. But it is only for one constant data string.
For example, if my incoming JSON string like:
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}
And Arduino code for parsing this data is below:
#include <LiquidCrystal.h>
#include <ArduinoJson.h>
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String response = "";
bool begin = false;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop() {
StaticJsonBuffer<100> jsonBuffer;
while(Serial.available() || !begin) {
char in = Serial.read();
if (in == '{') {
begin = true;
}
if(begin) {
response += (in);
}
if(in == '}') {
break;
}
delay(1);
}
JsonObject& root = jsonBuffer.parseObject(response);
String TPS = root["TPS"];
String MAP = root["MAP"];
String LOAD = root["LOAD"];
lcd.setCursor(0, 0);
lcd.print(TPS);
lcd.setCursor(8, 0);
lcd.print(MAP);
lcd.setCursor(0, 1);
lcd.print(LOAD);
}
Then the output looks like:
TPS : 0.40
MAP : 0.95
LOAD : 14
That's fine, but when the incoming JSON string changes, what should I do?
Suppose the incoming JSON string looks like:
{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}
Because I have to handle both incoming JSON strings, I can't replace any part like:
String LOAD = root["LOAD"];
String RPM = root["RPM"];
String INJECTION_TIME = root["INJECTION_TIME"];
lcd.setCursor(0, 0);
lcd.print(LOAD);
lcd.setCursor(8, 0);
lcd.print(RPM);
lcd.setCursor(0, 1);
lcd.print(INJECTION_TIME);
Instead of
String TPS = root["TPS"];
String MAP = root["MAP"];
String LOAD = root["LOAD"];
lcd.setCursor(0, 0);
lcd.print(TPS);
lcd.setCursor(8, 0);
lcd.print(MAP);
lcd.setCursor(0, 1);
lcd.print(LOAD);
jsonBuffer.parse(Serial)
? – Edgar Bonet Jun 28 '17 at 8:42jsonBuffer.parse(Serial)
? – Edgar Bonet Jun 28 '17 at 10:31