Json 如何处理?
我对从Arduino到Processing的JSON的简单解析有一些问题,以下是代码 ARDUINO代码Json 如何处理?,json,serial-port,arduino,processing,accelerometer,Json,Serial Port,Arduino,Processing,Accelerometer,我对从Arduino到Processing的JSON的简单解析有一些问题,以下是代码 ARDUINO代码 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 =
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);
}
处理代码
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);
}
}
}
在串行监视器上,我有正确的字符串:
{"accel":{"x":451,"y":-118}}
但是,在加工草图上,我有以下错误:
{ 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,
如果有人能在调试当前问题时给我一些帮助,我将非常感激
多谢各位 我建议将其作为二进制数据传输,您可以在处理端解包。它应该可以解决json问题,而且效率会更高。像这样的东西应该适合你 阿杜伊诺代码
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);
处理代码
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];
字节Tx_数据[4];
if(Serial.available()==4){
对于(int i=0;iHey,是的,我最终选择了该选项:)这是我通常的做法,但代码中可能会有一些混乱。因此我想知道JSON是否可以更好,但显然不是!无论如何,谢谢你的回答!