-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmqtt-wifi-dht11-deep-sleep.ino
112 lines (86 loc) · 1.98 KB
/
mqtt-wifi-dht11-deep-sleep.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
102
103
104
105
106
107
108
109
110
111
112
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// The NodeMCU pin (D2) for the data output from DHT11
#define DHT11_PIN 2
DHT DHT(DHT11_PIN, DHT11);
// Broker port
#define MQTT_PORT 1884
// Baud rate
#define BAUD_RATE 115200
// Update these with values suitable for your network.
const char* ssid = "SSD";
const char* password = "PASSWORD";
// Broker address (Raspberry Pi address)
const char *mqtt_server = "192.168.1.132";
// Publish topic
const char* publish_topic = "NODEMCUDHTHOME01";
// Wi-Fi client
WiFiClient espClient;
// MQTT client
PubSubClient client(espClient);
// String for sending the data
char msg[100];
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
randomSeed(micros());
// NodeMCU address
// Serial.println(WiFi.localIP());
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
// Create a random client ID
String clientId = "NODEMCUHOME01-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (!client.connect(clientId.c_str()))
{
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void processData()
{
// Connect the MQTT client
if (!client.connected())
{
reconnect();
}
client.loop();
// Read temperature in celsius
float T = DHT.readTemperature();
// Read humidity
float H = DHT.readHumidity();
snprintf(msg, 50, "{\"humidity\": %2.2f, \"temperature\": %2.2f}", H, T);
Serial.println(msg);
client.publish(publish_topic, msg);
delay(2000);
}
void setup()
{
Serial.begin(BAUD_RATE);
// Init DHT
DHT.begin();
// Configure Wi-Fi connection
setup_wifi();
// Configure broker server
client.setServer(mqtt_server, MQTT_PORT);
// Read sensors, send data, etc
processData();
// Time the device should sleep (10 * 1000000us = 10s)
ESP.deepSleep(10 * 1000000);
}
void loop()
{
}