#include <DHT.h>
#include <ESP32Servo.h>
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST"; // Using Wokwi's default virtual WiFi
const char* pwd = "";
const char* broker = "broker.hivemq.com";
// MQTT Topics
const char* topic_sensors = "IOT-G9/blinds/sensors";
const char* topic_control = "IOT-G9/blinds/control";
// Pin Definitions
const int dhtPin = 4;
const int servoPin = 18;
const int ldrPin = 34;
DHT dht(dhtPin, DHT22);
Servo blindServo;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastPublish = 0;
void callback(char* topic, byte* payload, unsigned int len) {
String msg = String((char*)payload, len);
int angle = msg.toInt();
if (angle >= 0 && angle <= 180) {
blindServo.write(angle);
}
}
void setup() {
ESP32PWM::allocateTimer(0);
blindServo.setPeriodHertz(50);
blindServo.attach(servoPin, 500, 2400);
blindServo.write(90);
dht.begin();
WiFi.begin(ssid, pwd);
while (WiFi.status() != WL_CONNECTED) delay(50);
client.setServer(broker, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
if (client.connect("SmartBlinds_ESP32")) {
client.subscribe(topic_control);
}
delay(500);
} else {
client.loop();
unsigned long now = millis();
// Publish sensor data every 3 seconds
if (now - lastPublish > 3000) {
lastPublish = now;
float t = dht.readTemperature();
int lightVal = analogRead(ldrPin); // ESP32 ADC reads 0 to 4095
if (!isnan(t)) {
String payload = "{\"temp\":" + String(t) +
",\"light\":" + String(lightVal) + "}";
client.publish(topic_sensors, payload.c_str());
}
}
}
}