#include <WiFi.h>
#include <PubSubClient.h>
// WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* topicLED1 = "esp32/led1";
const char* topicLED2 = "esp32/led2";
WiFiClient espClient;
PubSubClient client(espClient);
// Pin Push Buttons
const int button1 = 12;
const int button2 = 14;
// Button States
bool lastStateButton1 = HIGH;
bool lastStateButton2 = HIGH;
void setup() {
Serial.begin(115200);
// Setup button pins
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32_B")) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed with state ");
Serial.println(client.state());
delay(2000);
}
}
}
void loop() {
// Read button states
bool currentStateButton1 = digitalRead(button1);
bool currentStateButton2 = digitalRead(button2);
// Check for button1 state change
if (currentStateButton1 != lastStateButton1) {
if (currentStateButton1 == LOW) { // Button pressed
client.publish(topicLED1, "ON");
} else { // Button released
client.publish(topicLED1, "OFF");
}
lastStateButton1 = currentStateButton1;
delay(50); // Debounce
}
// Check for button2 state change
if (currentStateButton2 != lastStateButton2) {
if (currentStateButton2 == LOW) { // Button pressed
client.publish(topicLED2, "ON");
} else { // Button released
client.publish(topicLED2, "OFF");
}
lastStateButton2 = currentStateButton2;
delay(50); // Debounce
}
client.loop();
}