#include <WiFi.h>
#include <PubSubClient.h>
const int RELAY_PIN = 4;
const int SWITCH_PIN = 5;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const char* topic_command = "myUniqueSwitch123/command";
const char* topic_state = "myUniqueSwitch123/state";
WiFiClient espClient;
PubSubClient client(espClient);
int relayState = LOW;
int currentSwitchState;
int lastSwitchState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Cloud Command Received: ");
Serial.println(message);
// If the cloud says ON, and we are currently OFF, turn it ON
if (message == "ON" && relayState == LOW) {
relayState = HIGH;
digitalWrite(RELAY_PIN, relayState);
client.publish(topic_state, "ON"); // Confirm back to cloud
}
// If the cloud says OFF, and we are currently ON, turn it OFF
else if (message == "OFF" && relayState == HIGH) {
relayState = LOW;
digitalWrite(RELAY_PIN, relayState);
client.publish(topic_state, "OFF"); // Confirm back to cloud
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
// Create a random client ID
String clientId = "ESP32Client-";
clientId += String(random(0, 0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected to Cloud!");
// Subscribe to our command topic so we can listen to the App
client.subscribe(topic_command);
// Publish our initial state
client.publish(topic_state, relayState ? "ON" : "OFF");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("started");
pinMode(RELAY_PIN, OUTPUT);
pinMode(SWITCH_PIN, INPUT_PULLUP);
digitalWrite(RELAY_PIN, relayState);
// Connect to simulated Wi-Fi
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
// Setup MQTT
client.setServer(mqtt_server, 1883);
client.setCallback(mqttCallback);
}
void loop() {
// 1. Maintain Cloud Connection
if (!client.connected()) {
reconnect();
}
client.loop(); // Keeps the MQTT connection alive
// 2. Read Physical Wall Switch (Edge Detection)
int reading = digitalRead(SWITCH_PIN);
if (reading != lastSwitchState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != currentSwitchState) {
currentSwitchState = reading;
// EDGE DETECTED: Flip the relay state
relayState = !relayState;
digitalWrite(RELAY_PIN, relayState);
Serial.print("Wall Switch Flipped! Light is now: ");
Serial.println(relayState ? "ON" : "OFF");
// CRITICAL: Tell the cloud that the physical switch changed the light!
client.publish(topic_state, relayState ? "ON" : "OFF");
}
}
lastSwitchState = reading;
}