วันศุกร์ที่ 13 มกราคม พ.ศ. 2560

Arduino Read data From serial(Qt) . Data is Json to parser type int and type string

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial big(2, 3);

#define red_led 9
#define green_led 10
#define blue_led 11
String data;
int sqt[8];


void setup()
{
  pinMode(red_led, OUTPUT);
  pinMode(green_led, OUTPUT);
  pinMode(blue_led, OUTPUT);
  analogWrite(red_led, 255);
  analogWrite(green_led, 255);
  analogWrite(blue_led, 255);
  big.begin(115200);
  Serial.begin(115200);
}

void loop()
{
  if (Serial.available())
  {
    //    char led_specifier = Serial.read();
    //    int led_brightness = Serial.parseInt();
    //    write_leds(led_specifier, led_brightness);

    data = Serial.readString();
    big.print("data = ");  big.println(data);


    StaticJsonBuffer<1200> jsonBuffer;
    JsonArray& root = jsonBuffer.parseArray(data);

    if (!root.success())
    {
      Serial.println("parseArray() failed");
      return;
    }


    int j = 0, id, ss, rr, gg;
    id = root.get(j)["id"];
    ss = root.get(j)["status"];
    rr = root.get(j)["r"];
    gg = root.get(j)["g"];
    const char* bb = root.get(j)["b"];

    // getTowrite(sqt[j], ss, rr, gg, bb);
   
    // [{"id":1,"status":1,"r":255,"g":0,"b":0},{"id":2,"status":0,"r":255,"g":255,"b":255},{"id":3,"status":0}]
    big.print("ID = ");  big.print(id); big.print(" status = "); big.print(ss); big.print(" r = ");  big.print(rr);  big.print(" g = ");  big.print(gg); big.print(" b = ");  big.println(bb);

  }
 
  big.flush();


}

void write_leds(char led, int brightness)
{
  if (led == 'r')
  {
    analogWrite(red_led, 255 - brightness);
    Serial.println(255 - brightness);
    return;
  }
  if (led == 'g') {
    analogWrite(green_led, 255 - brightness);
    Serial.println(255 - brightness);
    return;
  }
  if (led == 'b') {
    analogWrite(blue_led, 255 - brightness);
    Serial.println(255 - brightness);
    return;
  }


  return;
}

0 ความคิดเห็น:

แสดงความคิดเห็น

สมัครสมาชิก ส่งความคิดเห็น [Atom]

<< หน้าแรก