通过Arduino以太网发送JSON数组 - 仅适用于0

时间:2015-04-30 00:04:57

标签: json tcp arduino ethernet

首先,我为任何没有技术意义的陈述道歉,我是第一年的EE学生,我不完全理解我正在做的一切。

对于机器人项目,我试图提供Arduino值来控制电机,我通过JSON数组发送Arduino值。 Arduino(带有以太网盾)充当客户端,我的笔记本电脑充当服务器。我用简单的值(X:400,Y:200,Z:0等)解析JSON数组,并通过连接发送它。我的问题是,对于除(X:0,Y:0,Z:0等)以外的任何一组值,连接都会滞后。连接没有停止(我有调试语句来捕获它),它只是挂在那里。在那之后没有任何事情发生 - 服务器和客户端只是永远等待。

我真的需要让这个工作,所以我希望有这种经验的人可以告诉我我做错了什么?以下是我正在使用的完整Arduino草图。

为了清楚起见,使用JSON的编码/解码发生在草图的循环中。

#include <QuadMotorShields.h>
#include <ArduinoJson.h>

#include <SPI.h>
#include <Ethernet.h>

QuadMotorShields md;

StaticJsonBuffer<100> jsonBuffer; //the JSON buffer we write/call from
StaticJsonBuffer<100> clearJson; //an empty JSON buffer

// To obtain server ip: Go to network settings->properties->IpV4 
// Make sure arduino's ip matches for first three numbers or else
// connections will fail.

byte server[] = {211, 255, 132, 121};
byte ip[] = {211, 255, 132, 49};

byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x40, 0x9F};
int port = 1900;

int x,y,z;  
String s = " ";
EthernetClient client;
int count = 0;


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

   Ethernet.begin(mac, ip);
   delay(1000);

   Serial.println("connecting...");

   // if you get a connection, report back via serial:
   client.connect(server, port);
}

/* loop()
 * Reads message from client char by char and saves to a string.
 * This string is parsed into a json object using ArduinoJson.
 * The values for various variables is then obtained from this object. 
 * Using these various variables we control the robot! */

void loop()
{
   count++;
   if (client.available()) {
      char c = client.read();
      if(c == '~') {
         int maxCommandLength = 70;
         char command[maxCommandLength];
         s.toCharArray(command, maxCommandLength);  
         JsonObject& root = jsonBuffer.parseObject(command);
         //Serial.print("JSON OBJECT: ");
         root.printTo(Serial);
         x = root["X"];
         y = root["Y"];
         //r = root["R"];
         z = root["Z"];

         md.setM1Speed(x);
         md.setM2Speed(y);
         md.setM3Speed(z);
         md.setM4Speed(z);
         jsonBuffer = clearJson;
         s = " ";
      }
      else {
         s += String(c);
      }
   }
   else { //client is no longer available
      client.connect(server, port);
   }
}

0 个答案:

没有答案