#include <WiFi.h>
#include <PubSubClient.h>
const char *ssid = "mySSID"; // Replace with real SSID
const char *password = "myPassword"; // Replace with real password
const char *mqttbroker = "broker.hivemq.com";
const char *clientID = "blk5_u05-100";
int portno = 8884;
WiFiClient espClient;
PubSubClient client(espClient);
// Pin assignments based on Wokwi diagram
#define RELAY_PIN 23
#define LIGHT_LED_PIN 2
#define PRESENCE_LED_PIN 4
#define BUTTON_PIN 5
#define PIR_PIN 18
int light = 0; // 0 = OFF, 1 = ON
int prese = 0; // 0 = ABSENT, 1 = PRESENT
void callback(const char *topic, byte* payload, unsigned int length) {
// No subscriptions
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
pinMode(LIGHT_LED_PIN, OUTPUT);
pinMode(PRESENCE_LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Button pulled high by default
pinMode(PIR_PIN, INPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
client.setServer(mqttbroker, portno);
client.setCallback(callback);
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect(clientID)) {
Serial.println(" connected!");
} else {
Serial.print(" failed, rc=");
Serial.println(client.state());
delay(1000);
}
}
}
void loop() {
client.loop();
// Read button state (LOW = pressed)
light = (digitalRead(BUTTON_PIN) == LOW) ? 1 : 0;
// Read PIR sensor
prese = digitalRead(PIR_PIN);
// Control LED and relay output
digitalWrite(LIGHT_LED_PIN, light);
digitalWrite(RELAY_PIN, light);
digitalWrite(PRESENCE_LED_PIN, prese);
// Publish MQTT messages
client.publish("estate/blk5/flr05/u05-100/living/light", String(light).c_str());
client.publish("estate/blk5/flr05/u05-100/living/prese", String(prese).c_str());
Serial.printf("Published -> Light: %d | Presence: %d\n", light, prese);
delay(2000); // Wait before next publish
}