#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// LDR pin
#define ldrPin 34
// Pin where the DHT22 sensor is connected
#define DHTPIN 15 // GPIO 15
#define DHTTYPE DHT22 // DHT22 sensor
// Replace with your Wi-Fi credentials
const char* ssid = "Wokwi-GUEST"; // Your Wi-Fi SSID
const char* password = ""; // Your Wi-Fi password
// MQTT Broker settings
const char* mqtt_server = "test.mosquitto.org"; // Use the public test MQTT broker
const int mqtt_port = 1883; // Standard MQTT port
// MQTT Topics
#define TEMP_TOPIC "home/dht22/temperature"
#define HUMIDITY_TOPIC "home/dht22/humidity33"
//====== #define Test33 "home/dht22/test33"
#define Test33 "home/T123"
#define LDRvalue "home/LDR123"
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Wi-Fi and MQTT clients
WiFiClient espClient;
PubSubClient client(espClient);
// Function to connect to Wi-Fi
void setup_wifi() {
delay(10);
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
// Reconnect to MQTT if disconnected
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
// Start the Serial Monitor
Serial.begin(115200);
pinMode(LDR_PIN,INPUT);
// Connect to Wi-Fi
setup_wifi();
// Initialize the DHT sensor
dht.begin();
// Set MQTT server
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
if (!client.connected()) {
reconnect(); // Reconnect if the connection to MQTT is lost
}
// Read temperature and humidity from the DHT22 sensor
float temperature = dht.readTemperature(); // Temperature in Celsius
float humidity33 = dht.readHumidity(); // Humidity in percentage
float ldrValue = analogRead(ldrPin); // Read the LDR value
Serial.println(ldrValue);
float test33=70.9;
// Check if readings are valid
if (isnan(temperature) || isnan(humidity33)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print readings to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity33);
Serial.println(" %");
// Publish temperature and humidity to MQTT broker on separate topics
client.publish(HUMIDITY_TOPIC, String(humidity33).c_str());
client.publish(TEMP_TOPIC, String(temperature).c_str());
client.publish(Test33, String(test33).c_str());
client.publish(LDRvalue, String(ldrValue).c_str()); //delay(5000);
//delay(5000);
// Wait before publishing again
delay(5000); // Publish every 5 seconds
}