#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiClient.h>
// =====================
// ** Wi-Fi Credentials **
// =====================
const char* ssid = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
const char* password = ""; // Replace with your Wi-Fi password
// =====================
// ** MQTT Credentials **
// =====================
const char* mqttServer = "broker.emqx.io"; // Public MQTT broker
const int mqttPort =1883 ;
const char* mqttTopic = "esp32/led"; // Topic for LED control
WiFiClient espClient;
PubSubClient client(espClient);
// =====================
// ** LED Configuration **
// =====================
#define LED_PIN 5 // GPIO5 connected to the LED
// =====================
// ** Callback Function **
// =====================
void callback(char* topic, byte* message, unsigned int length) {
String msg;
for (int i = 0; i < length; i++) {
msg += (char)message[i];
}
Serial.print("Message received on topic ");
Serial.print(topic);
Serial.print(": ");
Serial.println(msg);
if (msg == "ON") {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED turned ON");
} else if (msg == "OFF") {
digitalWrite(LED_PIN, LOW);
Serial.println("LED turned OFF");
}
}
// =====================
// ** Setup Function **
// =====================
void setup() {
// Initialize Serial Communication
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // Start with LED OFF
// Connect to Wi-Fi
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWi-Fi connected");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Setup MQTT
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect. Error: ");
Serial.print(client.state());
delay(2000);
}
}
// Subscribe to the LED control topic
client.subscribe(mqttTopic);
Serial.println("Subscribed to topic: esp32/led");
}
// =====================
// ** Loop Function **
// =====================
void loop() {
// Ensure the ESP32 stays connected to the MQTT broker
if (!client.connected()) {
reconnect();
}
client.loop(); // Process incoming messages
// Debugging MQTT connection status
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client")) {
Serial.println("connected");
client.subscribe(mqttTopic); // Subscribe to the topic once connected
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // Retry after 5 seconds
}
}
}