Advertisement
AlexShu

esp8266 w/ DHT11 data feed to thingspeak.com

Jun 1st, 2015
1,147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. /*
  2. This code sends data to thingspeak.com
  3. Hardware: esp8266, DHT11
  4. DHT11 data pin connected to GPIO2 on the esp8266
  5. Compiled on Arduino IDE by Arduino.cc
  6.  
  7. Alexshu.com
  8. DHT Library: https://github.com/adafruit/DHT-sensor-library
  9. */
  10.  
  11. #include "DHT.h"
  12. #include <ESP8266WiFi.h>
  13.  
  14. const char* ssid     = "SSID";      // CHANGE THIS
  15. const char* password = "PASSWORD";      // CHANGE THIS
  16.  
  17. const char* host = "api.thingspeak.com";
  18. const char* privateKey = "KEY";     // CHANGE THIS
  19.  
  20. DHT dht(2, DHT11, 20);
  21.  
  22. void setup() {
  23.   Serial.begin(115200);
  24.   dht.begin();
  25.   delay(10);
  26.  
  27.   // We start by connecting to a WiFi network
  28.  
  29.   Serial.println();
  30.   Serial.println();
  31.   Serial.print("Connecting to ");
  32.   Serial.println(ssid);
  33.  
  34.   WiFi.begin(ssid, password);
  35.  
  36.   while (WiFi.status() != WL_CONNECTED) {
  37.     delay(500);
  38.     Serial.print(".");
  39.   }
  40.  
  41.   Serial.println("");
  42.   Serial.println("WiFi connected");  
  43.   Serial.println("IP address: ");
  44.   Serial.println(WiFi.localIP());
  45. }
  46.  
  47. int value = 0;
  48.  
  49. void loop() {
  50.  
  51.   float h = dht.readHumidity();
  52.   float t = dht.readTemperature();
  53.   if (isnan(h) || isnan(t)) {
  54.     Serial.println("Failed to read from DHT sensor!");
  55.     return;
  56.   }
  57.  
  58.   Serial.print("connecting to ");
  59.   Serial.println(host);
  60.  
  61.   // Use WiFiClient class to create TCP connections
  62.   WiFiClient client;
  63.   const int httpPort = 80;
  64.   if (!client.connect(host, httpPort)) {
  65.     Serial.println("connection failed");
  66.     return;
  67.   }
  68.  
  69.   // We now create a URI for the request
  70.   String url = "/update";
  71.   url += "?key=";
  72.   url += privateKey;
  73.   url += "&field1=";
  74.   url += t;
  75.   url += "&field2=";
  76.   url += h;
  77.  
  78.   Serial.print("Requesting URL: ");
  79.   Serial.println(url);
  80.  
  81.   // This will send the request to the server
  82.   client.print(String("GET ") + url + " HTTP/1.1\r\n" +
  83.                "Host: " + host + "\r\n" +
  84.                "Connection: close\r\n\r\n");
  85.   delay(200);
  86.  
  87.   // Read all the lines of the reply from server and print them to Serial
  88.   while(client.available()){
  89.     String line = client.readStringUntil('\r');
  90.     Serial.print(line);
  91.   }
  92.  
  93.   Serial.println();
  94.   Serial.println("closing connection");
  95.   delay(60000);
  96.  
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement