#include <WiFi.h>
#include <PubSubClient.h>
#include <DHTesp.h>
// -------------------- SENSOR PINS --------------------
#define DHT_PIN 15
#define TRIG_PIN 5
#define ECHO_PIN 18
#define GAS_PIN 34
#define LDR_PIN 35
#define PIR_PIN 14
#define LED_PIN 23
DHTesp dht;
// -------------------- WIFI --------------------
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// -------------------- MQTT BROKER --------------------
const char* mqttServer = "broker.emqx.io";
const int mqttPort = 1883;
const char* topicData = "IOT";
const char* topicLed = "IOT/led";
WiFiClient espClient;
PubSubClient client(espClient);
// -------------------- SETUP --------------------
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(GAS_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
dht.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("\nWiFi Connected");
client.setServer(mqttServer, mqttPort);
client.setCallback(mqttCallback);
}
// -------------------- RECONNECT MQTT --------------------
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("esp32ClientWokwi_LED23")) {
Serial.println("connected");
// subscribe for LED control
client.subscribe(topicLed);
Serial.println(String("Subscribed to: ") + topicLed);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" retrying in 2 sec");
delay(2000);
}
}
}
// -------------------- MQTT CALLBACK --------------------
void mqttCallback(char* topic, byte* message, unsigned int length) {
String msg = "";
for (unsigned int i = 0; i < length; i++) {
msg += (char)message[i];
}
Serial.print("MQTT in [");
Serial.print(topic);
Serial.print("] ");
Serial.println(msg);
// LED control: accept "1"/"0" or "LED_ON"/"LED_OFF"
if (String(topic) == topicLed) {
if (msg == "1" || msg.equalsIgnoreCase("LED_ON")) {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED -> ON");
} else if (msg == "0" || msg.equalsIgnoreCase("LED_OFF")) {
digitalWrite(LED_PIN, LOW);
Serial.println("LED -> OFF");
} else {
Serial.println("Unknown LED command");
}
}
}
// -------------------- GET ULTRASONIC DISTANCE --------------------
long getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // timeout 30ms
if (duration == 0) return 0; // no reading
return (long)(duration * 0.034 / 2);
}
// ===================================================================
// MAIN LOOP
// ===================================================================
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// -------- DHT SENSOR --------
TempAndHumidity d = dht.getTempAndHumidity();
float temp = d.temperature;
float hum = d.humidity;
if (isnan(temp)) temp = 0;
if (isnan(hum)) hum = 0;
// -------- DISTANCE SENSOR --------
long distance = getDistance();
// -------- PIR --------
int motion = digitalRead(PIR_PIN);
// -------- GAS SENSOR --------
int gasValue = analogRead(GAS_PIN); // raw analog 0..4095
// optionally derive gasDetected boolean threshold:
int gasDetectedBool = (gasValue > 1800) ? 1 : 0;
// -------- LDR SENSOR --------
int ldrValue = analogRead(LDR_PIN); // raw analog 0..4095
int ldrBool = (ldrValue < 2000) ? 0 : 1;
// ------------------ CLEAN SERIAL PRINT ------------------
Serial.println("------ SENSOR STATUS ------");
Serial.print("Motion : "); Serial.println(motion ? "Detected" : "No Motion");
Serial.print("Distance : "); Serial.print(distance); Serial.println(" cm");
Serial.print("Temperature : "); Serial.print(temp); Serial.println(" °C");
Serial.print("Humidity : "); Serial.print(hum); Serial.println(" %");
Serial.print("Gas (raw) : "); Serial.print(gasValue); Serial.print(" bool: "); Serial.println(gasDetectedBool);
Serial.print("LDR (raw) : "); Serial.print(ldrValue); Serial.print(" bool: "); Serial.println(ldrBool);
Serial.println("---------------------------\n");
// ------------------ JSON DATA FOR NODE-RED ------------------
String json = "{";
json += "\"temp\":" + String(temp, 1) + ",";
json += "\"hum\":" + String(hum, 1) + ",";
json += "\"dist\":" + String(distance) + ",";
json += "\"motion\":" + String(motion) + ",";
json += "\"gas\":" + String(gasValue) + ",";
json += "\"ldr\":" + String(ldrValue);
json += "}";
client.publish(topicData, json.c_str());
Serial.print("Published to ");
Serial.print(topicData);
Serial.print(": ");
Serial.println(json);
delay(2000);
}