Pregunta

I'm having some issue with simple parsing of JSON from Arduino to Processing, here is the following code.

ARDUINO CODE

int x,y;

void setup()
{
Serial.begin(9600);
}

void loop()
{
sendJSON();
delay(500);
}

void sendJSON(){
String json;

json = "{\"accel\":{\"x\":";
json = json + x;
json = json + ",\"y\":";
json = json + y;
json = json + "}}";

Serial.println(json);
}

PROCESSING CODE

 import processing.serial.*;

 Serial myPort; 
 JSONObject json;
 int x,y;

 void setup () {
 size(200, 200);        

  myPort = new Serial(this, Serial.list()[5], 9600);
  myPort.bufferUntil('\n');
  }

  void draw () {
  }

  void serialEvent (Serial myPort) {

  while (myPort.available() > 0) {
  String inBuffer = myPort.readString();   
  if (inBuffer != null) {
  json = loadJSONObject(inBuffer);
  JSONObject acc = json.getJSONObject("accel");
  int x = acc.getInt("x");
  int y = acc.getInt("y");

  println(x + ", " + y);
  }
}
}

On the serial monitor i'm having the right string :

{"accel":{"x":451,"y":-118}}

However on the Processing sketch i'm having the following error :

{ does not exist or could not be read
Error, disabling serialEvent() for /dev/tty.usbmodem1421
null

or sometime even :

{"":{"x":456,"y":-123}} does not exist or could not be read Error, 

I would be very grateful if someone could give me some help in debugging this current issue !

Thank you very much !

¿Fue útil?

Solución

I would recommend transmitting this as binary data which you can unpack on the processing side. It should solve your json problem and will be much more efficient. Something like this should work for you...

Arduino code

byte Rx_Data[4];
Tx_Data[0] = accelX >> 8 & 0xff;
Tx_Data[1] = accelX& 0xff;
Tx_Data[2] = accelY >> 8 & 0xff;
Tx_Data[3] = accelY& 0xff;
Serial.write(Data_Packet);

Processing code

byte Tx_Data[4];

if(Serial.available() == 4) {
  for(int i=0;i<4;i++){
    Tx_Data[i] = Serial.read();
  }
}

int accelX = Tx_Data[0] << 8 | Tx_Data[1];
int accelY = Tx_Data[2] << 8 | Tx_Data[3];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top