· 6 years ago · Sep 19, 2019, 10:36 AM
1#include <DHT.h> // Including library for dht
2#include <ESP8266WiFi.h>
3String apiKey = "Your ThingSpeak Write API Key"; // Enter your Write API key from ThingSpeak
4const char *ssid = "WiFi Name"; // replace with your wifi ssid and wpa2 key
5const char *pass = "WiFi Password";
6const char* server = "api.thingspeak.com";
7#define DHTPIN 13 //D7 pin where the dht11 is connected
8DHT dht(DHTPIN, DHT11);
9WiFiClient client;
10void setup() {
11 Serial.begin(115200);
12 delay(10);
13 dht.begin();
14 Serial.println("Connecting to ");
15 Serial.println(ssid);
16 WiFi.begin(ssid, pass);
17 while (WiFi.status() != WL_CONNECTED)
18 {
19 delay(500);
20 Serial.print(".");
21 }
22 Serial.println("");
23 Serial.println("WiFi connected");
24
25}
26
27void loop()
28{
29
30 float h = dht.readHumidity();
31 float t = dht.readTemperature();
32
33 if (isnan(h) || isnan(t))
34 {
35 Serial.println("Failed to read from DHT sensor!");
36 return;
37 }
38
39 if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
40 {
41
42 String postStr = apiKey;
43 postStr +="&field1=";
44 postStr += String(t);
45 postStr +="&field2=";
46 postStr += String(h);
47 postStr += "\r\n\r\n";
48
49 client.print("POST /update HTTP/1.1\n");
50 client.print("Host: api.thingspeak.com\n");
51 client.print("Connection: close\n");
52 client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
53 client.print("Content-Type: application/x-www-form-urlencoded\n");
54 client.print("Content-Length: ");
55 client.print(postStr.length());
56 client.print("\n\n");
57 client.print(postStr);
58
59 Serial.print("Temperature: ");
60 Serial.print(t);
61 Serial.print(" degrees Celsius, Humidity: ");
62 Serial.print(h);
63 Serial.println("%. Send to Thingspeak.");
64 }
65 client.stop();
66
67 Serial.println("Waiting...");
68
69 // thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
70 delay(15000);
71}