Arduino发布到web api

时间:2017-06-09 13:03:24

标签: c++ arduino esp8266 nodemcu

对于c ++,我是一个绝对的初学者。现在我需要编写一些代码来从我的DHT11传感器读取值,并通过http get将它们发送到服务器。我所能做的就是查看arduino示例代码并将内容放在一起,所以我确定它并不漂亮。但我希望有人可以通过告诉我为什么它不起作用来帮助一个菜鸟。

这是代码

#include <ESP8266WiFi.h>
#include "DHT.h";
#include <string>
#include <iostream>

// Pin für DHT11 Sensor festlegen
#define DHTPIN 4

// Typ definieren
#define DHTTYPE DHT11

const char* ssid     = "mySSID";
const char* password = "myWiFiPW";

const char* host = "IP";
const char* myDev     = "deviceNAME";
const char* myUsr     = "me";
const char* myPwd     = "myPW";

// folgende Variabeln __nicht__ ändern
char urlHum[80];
char urlTem[80];
char str_temp[8];
char str_hum[8];

// Namen des Sensors definieren
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  delay(10); 
  }



void loop() {
  int value = 0;
  dht.begin();
  delay(5000);
  ++value;

  // Luftfeuchtigkeit auslesen und als "Luftfeuchte" speichern
  float feuchte = dht.readHumidity();
  dtostrf(feuchte, 2, 4, str_hum);

  // Temperatur auslesen und als "Tempe" speichern
  float tempe = dht.readTemperature();
  dtostrf(feuchte, 2, 4, str_temp);


  // Verbindung mit WiFi herstellen
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  sprintf(urlHum,"http://%s:%s@%s/api/device/%s/changeHumidityTo=humidity=%s", myUsr, myPwd, host, myDev, str_hum);
  sprintf(urlTem,"http://%s:%s@%s/api/device/%s/changeTemperatureTo=temperatue=%s", myUsr, myPwd, host, myDev, str_temp);


  //Serial.print("Requesting URL: ");
  //Serial.println(urlHum);

  // This will send the request to the server
  client.print(String("GET ") + urlHum + " HTTP/1.1\r\n" +
          // "Host: " + host + "\r\n" + 
           "Connection: close\r\n\r\n");
  client.print(String("GET ") + urlTem + " 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;
    }
  }



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

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

这应该只是将读取值添加到两个URL,然后将它们作为HTTP GET发送到我的服务器。但事实并非如此。它只会创建一个错误日志方式太长而无法在此处粘贴。在此先感谢您的帮助:)

0 个答案:

没有答案