Arduino通过服务器打开/关闭LED

时间:2016-11-06 19:48:14

标签: arduino-esp8266

我对Arduino / ESP8266很安静。我想制作一个简单的程序,通过HTTP请求打开和关闭内置LED。 HTTP请求正常工作,JSON反序列化也是如此。我到达我想要的if分支(取决于GET请求响应),但LED没有响应。问题是LED不断打开。我错过了重要的事吗?我试图通过互联网搜索,但我找不到我需要的东西。

ESP8266,NodeMCU 0.9

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>

const char* ssid     = "SSID";
const char* password = "password";

const char* host = "host.com";
const char* streamId   = "....................";
const char* privateKey = "....................";
StaticJsonBuffer<200> jsonBuffer;

void setup()
{
    Serial.begin(115200);
    delay(10);

    // Initialize LED, setting it to off
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

int value = 0;

void loop()
{
    delay(2);
    ++value;

    Serial.print("connecting to ");
    Serial.println(host);

    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

    String url = "/hrnem-brnem-api/index.php/entries/127";

    Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }

    String line;
    // Read all the lines of the reply from server and print them to Serial
    while (client.available()) {
        line = client.readStringUntil('\r');
        Serial.print(line);
    }

    JsonObject& root = jsonBuffer.parseObject(line);

    int value = root["value"];

    Serial.print(value);
    if (value == 1) {
        // turn LED on:
        Serial.print("LED is ON.");
        digitalWrite(LED_BUILTIN, HIGH);
    }
    else {
        // turn LED off:
        Serial.print("LED is OFF.");
        digitalWrite(LED_BUILTIN, LOW);
    }

    Serial.println();
    Serial.println("closing connection");
}

1 个答案:

答案 0 :(得分:0)

所以你需要投射你收集的JSON属性,使它具有意义和可比性。

使用此:

int value = root["value"].as<int>();