0

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.

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.