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