#include <WiFi.h>
#include <PubSubClient.h>
#define LED_PIN 5
#define BUTTON_PIN 14
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;
const char* mqtt_topic = "led/control";
const char* random_topic = "button/randomnumber";
WiFiClient espClient;
PubSubClient client(espClient);
void setupWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void publishRandomNumber() {
int number = random(1, 101);
Serial.printf("Publishing Random Number: %d\n", number);
char payload[10];
snprintf(payload, sizeof(payload), "%d", number);
client.publish(random_topic, payload);
}
void messageHandler(char* topic, byte* payload, unsigned int length) {
Serial.printf("Message received on %s: ", topic);
String msg;
for (unsigned int i = 0; i < length; i++) {
msg += (char)payload[i];
}
Serial.println(msg);
if (msg.equals("ON")) {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED TURNED ON");
} else if (msg.equals("OFF")) {
digitalWrite(LED_PIN, LOW);
Serial.println("LED TURNED OFF");
}
}
void reconnectMQTT() {
while (!client.connected()) {
String clientId = "ESP32_Client_" + String(random(1000, 9999));
Serial.printf("Attempting MQTT Connection with ID: %s\n", clientId.c_str());
if (client.connect(clientId.c_str())) {
Serial.println("Connected to MQTT Broker!");
client.subscribe(mqtt_topic);
} else {
Serial.printf("Failed to connect, state: %d\n", client.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
setupWiFi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(messageHandler);
}
void loop() {
if (!client.connected()) {
reconnectMQTT();
}
client.loop();
static bool lastButtonState = HIGH;
bool currentButtonState = digitalRead(BUTTON_PIN);
if (currentButtonState == LOW && lastButtonState == HIGH) {
publishRandomNumber();
delay(500);
}
lastButtonState = currentButtonState;
}