esp8266从thingspeak获取数据

问题描述 投票:0回答:2

我是新来的,如果提前抱歉,我找不到相关的问题。

我编辑了一个代码来获取thingpeak频道的数据,用于在arduino uno上的频道8上使用led或中继。根据数据1或0,led将打开或关闭。我使用的是esp8266。

espSerial.find(“+ IPD,1:0”)块无法正常工作。

#include <SoftwareSerial.h>
SoftwareSerial espSerial(2, 3);   
#define DEBUG true
String mySSID = "ssid";
String myPWD = "pass"; 
String myAPI = "CV4YEARDB91GTOXM";   // API Key
String myHOST = "api.thingspeak.com";
String myPORT = "80";
String myFIELD = "field1";

void setup()
{
  pinMode(8,OUTPUT);
  Serial.begin(9600);
  espSerial.begin(115200);

  espData("AT+RST", 1000, DEBUG);                     
  espData("AT+CWMODE=1", 1000, DEBUG);                 
  espData("AT+CWJAP=\""+ mySSID +"\",\""+ myPWD +"\"", 1000, DEBUG);   
  delay(1000); }

void loop()
  {

    String sendData = "GET /channels/716457/fields/1/last?key=CV4YEARDB91GTOXM";
    espData("AT+CIPMUX=1", 1000, DEBUG);
    espData("AT+CIPSTART=0,\"TCP\",\""+ myHOST +"\","+ myPORT, 1000, DEBUG);
    espData("AT+CIPSEND=0," +String(sendData.length()+4),1000,DEBUG);
    espSerial.find(">");
    espSerial.println(sendData);

    espData("AT+CIPCLOSE=0",1000,DEBUG);
    delay(10000);
  }

String espData(String command, const int timeout, boolean debug)
{
Serial.print(command);
  Serial.println("     ");

  String response = "";
  espSerial.println(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (espSerial.available())
    {
      if (espSerial.find("+IPD,1:0")) {
        digitalWrite(8,LOW); }
      if (espSerial.find("+IPD,1:1")) {
        digitalWrite(8,HIGH); }
    }
    }

  if (debug)
  {
    Serial.print(response);
  }
  return response;
}
arduino iot esp8266
2个回答
0
投票

以下是我的意图的解决方案,即使用+ IPD答案从thingspeak频道获取数据:

    String espData(String command, const int timeout, boolean debug)
    {
    Serial.print(command);
      Serial.println("     ");

      String response = "";
      espSerial.println(command);
      long int time = millis();
      while ( (time + timeout) > millis())
      {
        if (espSerial.available()>0)
        {      
          if (espSerial.find("+IPD,0,1:")); {
            while (espSerial.available()>0) {
          String gelen = "";
          char serialdenokunan;

          serialdenokunan = espSerial.read();
          gelen += serialdenokunan;
          Serial.println(gelen);
          if (gelen.indexOf("0")>=0) {
            digitalWrite(8,LOW); }
          if (gelen.indexOf("1")>=0) {
            digitalWrite(8,HIGH); }
        }}}
        }

      if (debug)
      {
        Serial.print(response);
      }
      return response;
   }

如果单个连接AT + CIPMUX = 0,则IPD答案为+ IPD,0:数据而不是+ IPD,0,connectionnumber:data。比if(espSerial.find(“+ IPD,0:”))在这种情况下有效。

感谢所有通过邮件和帖子回复的人。


0
投票

有更简单的方法来做到这一点。 ThingSpeak在GitHub上创建了库,它可以处理向ThingSpeak通道写入数据和从ThingSpeak通道读取数据。您可以尝试一下库中包含的示例。

© www.soinside.com 2019 - 2024. All rights reserved.