In my recent project, I'm working with Arduino and JSON. Now, I get data from JSON and I can able to receive in Arduino side.
Below one is my Arduino code:
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
String response = "";
bool begin = false;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop()
{
while(Serial.available() || !begin)
{
char in = Serial.read();
if (in == '{')
{
begin = true;
}
if(begin) response += (in);
if(in == '}')
{
break;
}
delay(1);
}
lcd.setCursor(0, 0);
lcd.print(response);
}
Output :
{"TPS":"0.40","MAP":"1.05","LOAD":"14"}
Now, I want to split data means store 0.40
in one variable, 1.05
in another variable and 14
in another variable. I don't know how to split this.
-
Try this: hackingmajenkoblog.wordpress.com/2017/04/08/…Majenko– Majenko2017年05月13日 11:13:01 +00:00Commented May 13, 2017 at 11:13
-
Can try this JSON library: github.com/bblanchon/ArduinoJsongoddland_16– goddland_162017年05月13日 11:36:13 +00:00Commented May 13, 2017 at 11:36
-
@goddland_16 I try out that library but I face one problem.Hasan– Hasan2017年05月13日 11:41:01 +00:00Commented May 13, 2017 at 11:41
-
if you know the number of variables and it is fixed, and the order of incoming data, you can parse yourself. Well, I can parse the example string provided all the above conditions are met.goddland_16– goddland_162017年05月13日 12:16:00 +00:00Commented May 13, 2017 at 12:16
1 Answer 1
Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.
Below is my code:
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
String responseOne = "";
String responseTwo = "";
String responseThree = "";
bool begin = false;
int counter = 0;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop()
{
while(Serial.available() || !begin)
{
char in = Serial.read();
if (in == '{')
{
begin = true;
}
if(begin)
{
counter++;
if(counter >= 9 && counter <= 12) // This gives 0.40
{
responseOne += (in); // 0.40 store in responseOne variable
}
if(counter >= 22 && counter <= 25) // This gives 1.05
{
responseTwo += (in); // 1.05 store in responseTwo
}
if(counter >= 36 && counter <= 37) // This gives 14
{
responseThree += (in); // 14 store in responseThree
}
}
if(in == '}')
{
break;
}
delay(1);
}
float newResponseOne = responseOne.toFloat(); // Convert string into Float
float newResponseTwo = responseTwo.toFloat(); // Convert string into Float
int newResponseThree = responseThree.toInt(); // Convert string into Integer
lcd.setCursor(0, 0);
lcd.print(newResponseOne);
lcd.setCursor(8, 0);
lcd.print(newResponseTwo);
lcd.setCursor(0, 1);
lcd.print(newResponseThree);
}