// code for temperature and humidity monitoring using nodered dashboard
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// connect to the router, use the credentials of your router, for simulation
// we use these values
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// In case you are using a Raspberry Pi use its IP address so as to connect to
// the MQTT broker, for simulation we use this
const char* mqtt_server = "test.mosquitto.org";// MQTT broker
char* my_topic2 = "/IoT1/temp";// topic2: sensor-temerature
char* my_topic3 = "/IoT1/hum";// topic3: sensor-humidity
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(4, DHT22);
void setup() {
Serial.begin(115200); // Initialize serial communication for debugging
//myservo.attach(5); // Attach the servo to GPIO pin 5
setup_wifi();
client.setServer(mqtt_server, 1883); // Set the MQTT broker server and port
//client.setCallback(callback); // Set the callback function for incoming MQTT messages
dht.begin();
delay(2000);
}
// Connect to the Wi-Fi network using the provided credentials
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP()); // Print the local IP address of the ESP32 once connected
}
// Process incoming MQTT message and control the servo motor
//void callback(char* topic, byte* payload, unsigned int length) {
//if (topic = my_topic2){
//}
//}
// Attempt to reconnect to the MQTT broker if the connection is lost
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESPClient")) {
Serial.println("connected");
client.subscribe(my_topic2);
client.subscribe(my_topic3);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
// Check MQTT connection and process incoming messages
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100); // Add a delay to avoid flooding the MQTT broker with messages
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.print("Temp : ");
Serial.print(temp);
Serial.println(" C ");
Serial.print("Humidity : ");
Serial.print(humidity);
Serial.println(" % ");
String messaget = String(temp);
String messageh = String(humidity);
client.publish("/IoT1/temp", messaget.c_str());
client.publish("/IoT1/hum", messageh.c_str());
delay(200);
}