· 6 years ago · Nov 22, 2019, 03:42 AM
1#include <DHT.h> // Including library for dht
2
3#include <ESP8266WiFi.h>
4
5String apiKey = "Created By Alif Firdi"; // Enter your Write API key from ThingSpeak
6
7const char *ssid = "Hotspot SMK AL-MUFTI (UniFi)"; // replace with your wifi ssid and wpa2 key
8const char *pass = "";
9const char* server = "192.168.43.22/api.php";
10
11#define DHTPIN 0 //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 IPAddress ip(192,168,43,200);
30 IPAddress gateway(192,168,43,22);
31 IPAddress subnet(255,255,255,0);
32
33 WiFi.config(ip, gateway, subnet);
34
35 while (WiFi.status() != WL_CONNECTED)
36 {
37 delay(500);
38 Serial.print(".");
39 }
40 Serial.println("");
41 Serial.println("WiFi connected");
42
43}
44
45void loop()
46{
47
48 float h = dht.readHumidity();
49 float t = dht.readTemperature();
50
51 if (isnan(h) || isnan(t))
52 {
53 Serial.println("Failed to read from DHT sensor!");
54 return;
55 }
56
57 if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
58 {
59
60 String postStr = apiKey;
61 postStr +="&temp=";
62 postStr += String(t);
63 postStr +="&humidity=";
64 postStr += String(h);
65 postStr += "\r\n\r\n";
66
67 client.print("POST /update HTTP/1.1\n");
68 client.print("Host: 192.168.43.22/api.php\n");
69 client.print("Connection: close\n");
70 client.print("X-ALIFAPIKEY: "+apiKey+"\n");
71 client.print("Content-Type: application/x-www-form-urlencoded\n");
72 client.print("Content-Length: ");
73 client.print(postStr.length());
74 client.print("\n\n");
75 client.print(postStr);
76
77 Serial.print("Temperature: ");
78 Serial.print(t);
79 Serial.print(" degrees Celcius, Humidity: ");
80 Serial.print(h);
81 Serial.println("%. Send to Thingspeak.");
82 }
83 client.stop();
84
85 Serial.println("Waiting...");
86
87 // thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
88 delay(2000);
89}