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