#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 = "240686446"; // 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:1
esp:2
esp:3
esp:4
esp:5
esp:6
esp:7
esp:8
esp:9
esp:10
esp:18
esp:19
esp:GND.1
esp:3V3.1
esp:3V3.2
esp:GND.2
esp:RST
esp:GND.3
esp:GND.4
esp:5V.1
esp:5V.2
esp:GND.5
esp:GND.6
esp:GND.7
esp:GND.8
esp:GND.9
esp:RX
esp:TX
esp:GND.10