-
Notifications
You must be signed in to change notification settings - Fork 0
/
DHT_ESP_NodeRED.ino
104 lines (85 loc) · 2.85 KB
/
DHT_ESP_NodeRED.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
/*****************************************************************************************************************************
********************************** Author : Ehab Magdy Abdullah *************************************
********************************** Linkedin: https://www.linkedin.com/in/ehabmagdyy/ *************************************
********************************** Youtube : https://www.youtube.com/@EhabMagdyy *************************************
******************************************************************************************************************************/
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
/* Digital pin connected to the DHT sensor */
#define DHT_PIN 4
/* I'm using DHT22, if you use DHT11 you can change DHT22 to DHT11 */
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
const char* ssid = "2001"; /* Your Wifi SSID */
const char* password = "19821968"; /* Your Wifi Password */
const char* mqtt_server = "test.mosquitto.org"; /* Mosquitto Server URL */
WiFiClient espClient;
PubSubClient client(espClient);
float humidity;
float temperature;
void setup_wifi()
{
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.print(ssid);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect()
{
while(!client.connected())
{
Serial.println("Attempting MQTT connection...");
if(client.connect("ESPClient"))
{
Serial.println("Connected");
client.subscribe("Ehab/DHT/Humidity");
client.subscribe("Ehab/DHT/Temp");
}
else
{
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
dht.begin();
}
void loop()
{
if(!client.connected()) { reconnect(); }
humidity = dht.readHumidity();
temperature = dht.readTemperature();
char h[3] = {0};
char t[3] = {0};
h[0] = (uint8_t)humidity / 10 + '0';
h[1] += (uint8_t)humidity % 10 + '0';
t[0] += (uint8_t)temperature / 10 + '0';
t[1] += (uint8_t)temperature % 10 + '0';
/* Sending Data to Node-Red */
client.publish("Ehab/DHT/Humidity", h, false);
client.publish("Ehab/DHT/Temp", t, false);
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% - Temperature: ");
Serial.print(temperature);
Serial.println("°C");
delay(2000);
}