-
Notifications
You must be signed in to change notification settings - Fork 0
/
wemos-dht22.ino
101 lines (74 loc) · 2.32 KB
/
wemos-dht22.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <DHT.h>
#include <ESP8266WiFi.h>
const char* ssid = "DANIEL-IOT";
const char* password = "passwordgoeshere";
#define DHTPIN D4 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
byte mac[6];
float hum; //Stores humidity value
float temp; //Stores temperature value
// Time to sleep (in seconds):
const int sleepTimeS = 20;
// Host
const char* host = "dan.sh";
void setup()
{
// Serial
Serial.begin(115200);
Serial.println("ESP8266 in normal mode");
dht.begin();
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
hum = dht.readHumidity();
temp= dht.readTemperature();
// TODO: Set a max retry count before skipping and going back to sleep!
while(isnan(hum) || isnan(temp)) {
Serial.println("Failed reading sensor. Trying again in 1 second...");
delay(1000);
hum = dht.readHumidity();
temp= dht.readTemperature();
}
Serial.print("Humidity: ");
Serial.println(hum);
Serial.print("Temp: ");
Serial.println(temp);
// Print the IP address
Serial.println(WiFi.localIP());
// Logging data to cloud
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
WiFi.macAddress(mac);
String macString = String(mac[0], HEX) + ":" + String(mac[1], HEX) + ":" + String(mac[2], HEX) + ":" + String(mac[3], HEX) + ":" + String(mac[4], HEX) + ":" + String(mac[5], HEX);
// This will send the request to the server
client.print(String("GET /iot/record?temp=") + String(temp, 2) + "&hum=" + String(hum, 2) + "&mac=" + macString + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
// Sleep
Serial.println("ESP8266 in sleep mode");
ESP.deepSleep(sleepTimeS * 1000000);
}
void loop()
{
}