无法将节点MCU esp8266连接到Thingspeak

时间:2017-02-09 18:08:56

标签: nodemcu arduino-esp8266

我正在使用this tutorial。我也使用相同的节点MCU ESP8266。我把它连接到我的家庭网络。本地IP地址也会显示,但它没有连接到我的thingpeak频道,而是等待客户端。

我还检查过我的thingpeak API是否正确,我的家庭网络也正常工作。

enter image description here

2 个答案:

答案 0 :(得分:0)

使用ESP8266HTTPClient HTTP lib通过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;
}

答案 1 :(得分:0)

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

以下是我tutorial的相关行:

在设置之前添加以下行:

#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);
相关问题