#include <WiFi.h> // For ESP8266, use <WiFi.h> for ESP32
#include <PubSubClient.h>
#include <DHT.h>
// DHT22 Settings
#define DHTPIN 25 // Pin where DHT11 is connected
#define DHTTYPE DHT22 // DHT 22
DHT dht(DHTPIN, DHTTYPE);
// Wi-Fi Settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Settings
const char* mqtt_server = "test.mosquitto.org";// This is the free MQTT broker we will use.
const int mqtt_port = 1883;
const char* mqtt_user = "your-MQTT-username"; // Optional
const char* mqtt_pass = "your-MQTT-password"; // Optional
const char* topic_temperature = "home/livingroom/temperature";
const char* topic_humidity = "home/livingroom/humidity";
WiFiClient espClient;
PubSubClient client(espClient);
float t, h;
void setup() {
Serial.begin(9600);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
client.setServer(mqtt_server, mqtt_port);
t=23.5; // testing============
h=35; // testing============
}
void reconnect() {
while (!client.connected()) {
if (client.connect("DHT22Client", mqtt_user, mqtt_pass)) {
Serial.println("Connected to MQTT broker");
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
////////======= float h = dht.readHumidity();
////////// float t = dht.readTemperature();
// t=23.5;
Serial.println(t);
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Publish data
client.publish(topic_temperature, String(t).c_str());
client.publish(topic_humidity, String(h).c_str());
delay(2000); // Wait for 2 seconds
}