解析来自串行窗口的 JSON 响应

parsing json response from serial window

本文关键字:窗口 JSON 响应      更新时间:2023-10-16

嗨,我正在尝试从我的arduino中的网络服务器解析JSON响应,以便打开和关闭LED灯。我正在使用 wifi 客户端重复示例向我的服务器发出 get 请求:

http://arduino.cc/en/Tutorial/WiFiWebClientRepeating

这是我运行时从串行端口打印回来的内容

WiFiClient client;
   char c = client.read();
    Serial.write(c);

串口结果

connecting...
HTTP/1.1 200 OK
Date: Sun, 06 Apr 2014 01:14:37 GMT
Server: Apache
X-Powered-By: PHP/5.5.10
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json
19
{"lightstatus":"on"}
0

如何仅解析此响应的 JSON 部分,以便可以使用它来控制我的 LED?

谢谢

好吧,即使是JSON也"很难"解析arduino。因此,您应该考虑尽可能简单地使用响应,例如使用 1/0 整数而不是"on"

你需要运行的,基本上是一个状态图:

if ('{' == client.read())
  if ('"' == client.read())
    if ('l' == client.read())
      if ('i' == client.read())
        if ('g' == client.read())
          if ('h' == client.read())
            if ('t' == client.read())
              if ('s' == client.read())
                if ('t' == client.read())
                  if ('a' == client.read())
                    if ('t' == client.read())
                      if ('u' == client.read())
                        if ('s' == client.read())
                          if ('"' == client.read())
                            if (':' == client.read()) {
                               char c = client.read();
                               if (c == '1')
                                 // TURN LIGHT ON
                               else if (c == '0')
                                 // TURN LIGHT OFF
                            }

这可以通过使用字符串并将状态保留在索引变量中来改进:

const char* VAL="{"lightstatus":"
int parse_value(char c) {
    static int val_idx=0;
    // end of parsing condition, the index reached string length
    if (strlen(VAL) == val_idx) {
        // if the value is '1', return >0, if the value is '0', return 0
        if ('1' == c) return 1;
        else if ('0' == c) return 0;
    }
    // otherwise let's check if we're still in string
    if (c == VAL[val_idx]) {
        // if we do, increment the index variable
        ++val_idx;
    } else {
        // or reset it
        val_idx = 0;
    }
    // return -1 while we're still parsing the string
    return -1;
}

要使用该代码,请执行以下操作:

char val=-1;
while (val < 0)
    val = parse_value(Serial.read())

我没有测试它,但我希望你得到算法的想法!