arduino在网页中查找文字

时间:2015-06-07 21:33:34

标签: arduino

我正试图从this website发出arduino天气警报 我需要在"天气"中找到引号的内容。之后"主要"。我找了一个文本查找器,但arduino website上有一个文本查找器,但它不那么具有描述性,以至于它不存在。

目前我的代码如下:

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "api.openweathermap.org";  

IPAddress ip(192,168,1,77);

EthernetClient client;

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

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
  }
  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /data/2.5/weather?q=Melbourne,au HTTP/1.1");
    client.println("Host: api.openweathermap.org");
    client.println("Connection: close");
    client.println();
  } 
  else {
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    client.stop();

    while(true);
  }
}

然后它返回:

HTTP/1.1 200 OK
Server: nginx
Date: Sun, 07 Jun 2015 21:17:44 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
X-Source: redis
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST

1d2
{"coord":{"lon":144.96,"lat":-37.81},"sys":{"message":0.0117,"country":"AU","sunrise":1433626204,"sunset":1433660872},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"stations","main":{"temp":284.532,"temp_min":284.532,"temp_max":284.532,"pressure":1011.27,"sea_level":1030.68,"grnd_level":1011.27,"humidity":80},"wind":{"speed":4.43,"deg":331.501},"clouds":{"all":0},"dt":1433711139,"id":2158177,"name":"Melbourne","cod":200}

0

对于此输出我希望它说:Clear

1 个答案:

答案 0 :(得分:1)

获取所需数据的一种非常简单的方法是使用Arduino游乐场的TextFinder。我相信这应该有效。请注意,我没有测试过,所以手指交叉。

在开头添加

#include <TextFinder.h>
#include <String.h>
String result = "";
TextFinder finder( client );

然后将你的loop()修改为

if (client.connected()){
  finder.find("\"weather\"");
  finder.find("\"main\":\"");
  char c = client.read();
  while(c != '\"'){
    result += c;
    c = client.read();
  }
  Serial.print(result);
}
if (!client.connected()) {
  Serial.println();
  client.stop();
  while(true);
}

如果您有兴趣,请在下方提供更多信息。

你得到的回应是json,要正确解释它你需要一个json解析器。我在github上找到了一个库:ArduinoJson解析了arduino上的json。它似乎也很容易使用。如果您需要帮助,可以浏览wiki

在开始对json进行分析之前,首先需要从响应中删除标题。要做到这一点,你可以继续读取字符,直到你获得双重CRLF(\ r \ n \ r \ n)