#include <WiFi.h> //Key parts to understand:
#include <PubSubClient.h>
// Wi-Fi Credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Broker Settings
const char* mqtt_server = "mqtt.eclipseprojects.io"; // Example public broker
const char* mqtt_topic = "esp32/test/topic"; // Topic to subscribe to
WiFiClient espClient;
PubSubClient client(espClient);
// Function to connect to Wi-Fi
void connectWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi Connected");
}
// Function to connect to the MQTT broker
void connectMQTT() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a unique client ID
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect, state ");
Serial.println(client.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200); // Initialize Serial Monitor
connectWiFi(); // Connect to Wi-Fi
client.setServer(mqtt_server, 1883); // Set MQTT broker address and port
connectMQTT();
}
void loop() {
if (!client.connected()) {
connectMQTT(); // Reconnect if the connection is lost
}
client.loop(); // Keep the connection alive
// Publish a test message every 5 seconds
String payload = "Hello from ESP32";
client.publish(mqtt_topic, payload.c_str());
Serial.println("Published: " + payload);
delay(5000); // Delay for 5 seconds before sending the next message
}