· 5 years ago · Nov 03, 2020, 05:06 AM
1#include <DHT.h> // Including library for dht
2#include <ESP8266WiFi.h>
3
4String apiKey = "0545PNPVBZ4DF6FZ"; // Enter your Write API key from ThingSpeak
5const char *ssid = "wifi gratisan"; // replace with your wifi ssid and wpa2 key
6const char *pass = "kadatahu2";
7const char *server = "api.thingspeak.com";
8
9#define DHTPIN 13 //pin where the dht11 is connected
10DHT dht(DHTPIN, DHT11);
11WiFiClient client;
12
13void setup() {
14 Serial.begin(115200);
15 delay(10);
16 dht.begin();
17
18 Serial.println("Connecting to ");
19 Serial.println(ssid);
20
21 WiFi.begin(ssid, pass);
22 while (WiFi.status() != WL_CONNECTED) {
23 delay(500);
24 Serial.print(".");
25 }
26 Serial.println("");
27 Serial.println("WiFi connected");
28
29}
30
31void loop()
32{
33 float h = dht.readHumidity();
34 float t = dht.readTemperature();
35
36 if (isnan(h) || isnan(t)) {
37 Serial.println("Failed to read from DHT sensor!");
38 return;
39 }
40
41 if (client.connect(server,80)) {
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 Celcius, Humidity: ");
62 Serial.print(h);
63 Serial.println("%. Send to Thingspeak.");
64 }
65 client.stop();
66 Serial.println("Waiting...");
67 // thingspeak needs minimum 15 sec delay between updates
68 delay(5000);
69}