#include <WiFi.h>
#include <PubSubClient.h>
// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPin = 2; // Onboard LED (output)
const int ledPin1 = 16; // Switch 1 (input)
const int ledPin2 = 17; // Switch 2 (input)
const char* topic = "buet/cse/2105065"; // Subscribe topic (receive ON/OFF from Python)
const char* topic2 = "buet/cse/nigga"; // Publish topic (send switch state to Python)
void callback(char* topic, byte* payload, unsigned int length) {
String message;
for (unsigned int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Received [");
Serial.print(topic);
Serial.print("] : ");
Serial.println(message);
if (message == "ON") {
digitalWrite(ledPin, HIGH);
Serial.println("LED turned ON");
} else if (message == "OFF") {
digitalWrite(ledPin, LOW);
Serial.println("LED turned OFF");
} else if (message == "Switched") {
Serial.println("Switch 1 was pressed (Python notified us)");
} else if (message == "Un-switched") {
Serial.println("Switch 2 was pressed (Python notified us)");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("ESP32_Wokwi_LED")) {
Serial.println("connected");
client.subscribe(topic); // Listen for ON/OFF commands from Python
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" — retrying in 5s");
delay(5000);
}
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ledPin1, INPUT);
pinMode(ledPin2, INPUT);
digitalWrite(ledPin, LOW);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Wi-Fi connected!");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Publish to topic2 when a physical switch is pressed
if (digitalRead(ledPin1) == HIGH) {
client.publish(topic2, "Switched-1");
Serial.println("Switch 1 On Sent");
delay(500); // simple debounce
}
if (digitalRead(ledPin1) == LOW) {
client.publish(topic2, "Un-Switched-1");
Serial.println("Switch 1 Off Sent");
delay(500); // simple debounce
}
if (digitalRead(ledPin2) == HIGH) {
client.publish(topic2, "Switched-2");
Serial.println("Switch 2 On Sent");
delay(500); // simple debounce
}
if (digitalRead(ledPin2) == LOW) {
client.publish(topic2, "Un-switched-2");
Serial.println("Switch 2 Off Sent");
delay(500); // simple debounce
}
}