#include <WiFi.h>
#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/topic36"; // Topic to subscribe to
WiFiClient espClient;
PubSubClient client(espClient);
// Function to connect to Wi-Fi
void connectWiFi() {
// Serial.println("Connecting to WiFi...");
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.println("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");
// Subscribe to the topic
client.subscribe(mqtt_topic);
} else {
Serial.print("Failed to connect, state: ");
Serial.println(client.state());
delay(5000); // Retry after 5 seconds
}
}
}
// MQTT Callback to handle incoming messages
void callback(char* topic, byte* payload, unsigned int length) {
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Received message: ");
Serial.println(message);
}
void setup() {
Serial.begin(115200); // Initialize Serial Monitor
connectWiFi(); // Connect to Wi-Fi
client.setServer(mqtt_server, 1883); // Set MQTT broker address and port
client.setCallback(callback); // Set the callback function to handle messages
connectMQTT(); // Ensure MQTT connection is established
}
void loop() {
if (!client.connected()) {
connectMQTT(); // Reconnect if the connection is lost
}
client.loop(); // Keep the connection alive and listen for messages
delay(100); // Small delay for stability
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK