1

我正在使用本教程。我也在使用相同的 Node MCU ESP8266。我将它连接到我的家庭网络。本地 ip 地址也显示了,但它没有连接到我的 thingspeak 频道,它卡在等待客户端。

我还检查了我的 thingspeak API 是否正确,并且我的家庭网络也在工作。

在此处输入图像描述

4

2 回答 2

0

看起来您正在使用 Arduino IDE 对 NodeMCU 进行编程。如果是这种情况,那么您所要做的就是创建一个 WiFiClient,然后构造一个 HTTP POST 请求,并使用客户端将其发送到 ThingSpeak。

以下是我教程中的相关行:

在设置之前添加以下行:

#include <ESP8266WiFi.h>
WiFiClient client;
const char* server = "api.thingspeak.com";
String writeAPIKey = "XXXXXXXXXXXXXXXX";

在您的循环中,添加以下行以读取 A0 并将其发送到 ThingSpeak:

if (client.connect(server, 80)) {

    // Measure Analog Input (A0)
    int valueA0 = analogRead(A0);

    // Construct API request body
    String body = "field1=";
           body += String(valueA0);

    Serial.print("A0: ");
    Serial.println(valueA0); 

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(body.length());
    client.print("\n\n");
    client.print(body);
    client.print("\n\n");

}
client.stop();

// wait 20 seconds and post again
delay(20000);
于 2017-02-22T19:27:29.557 回答
0

使用 ESP8266HTTPClient HTTP 库通过 ESP8266 发布到 ThingSpeak。这是一个示例函数。使用数据参数调用它以写入您的 ThingSpeak 频道:

#include <ESP8266HTTPClient.h>

#define TSPEAK_HOST       "http://api.thingspeak.com"
#define TSPEAK_API_KEY    "YOUR_THINGSPEAK_API_KEY"
#define LEN_HTTP_PATH_MAX 256

HTTPClient http;

unsigned short postThingSpeak(char* data)
{
  boolean httpCode = 0;
  char httpPath[LEN_HTTP_PATH_MAX];
  memset(httpPath, 0, LEN_HTTP_PATH_MAX);
  snprintf(httpPath, LEN_HTTP_PATH_MAX, "%s/update?api_key=%s&field1=%s", TSPEAK_HOST, TSPEAK_API_KEY, data);
  Serial.printf("Path to post : %s\n", httpPath);

  http.begin(httpPath);
  httpCode = http.GET();

  Serial.printf("Return  : %d\n", httpCode);
  Serial.printf("Incoming Body : %s\n", http.getString().c_str());
  http.end();

  return httpCode;
}
于 2017-02-22T10:03:36.277 回答