#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
#define BUTTON1 14
#define BUTTON2 27
#define BUTTON3 26
#define BUTTON4 25
#define BUTTONRST 21
const char *MQTT_BROKER_ADRESS = "test.mosquitto.org";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "mario_pub";
volatile bool button1Pressed = false;
volatile bool button2Pressed = false;
volatile bool button3Pressed = false;
volatile bool button4Pressed = false;
volatile bool buttonRSTPressed = false;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void IRAM_ATTR button1ISR() { button1Pressed = true; }
void IRAM_ATTR button2ISR() { button2Pressed = true; }
void IRAM_ATTR button3ISR() { button3Pressed = true; }
void IRAM_ATTR button4ISR() { button4Pressed = true; }
void IRAM_ATTR buttonRSTISR() { buttonRSTPressed = true; }
void ConnectWiFi() {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
}
void InitMqtt() {
mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
}
void ConnectMqtt() {
while (!mqttClient.connected()) {
Serial.print("Starting MQTT connection...");
if (mqttClient.connect(MQTT_CLIENT_NAME)) {
Serial.println("Client connected");
} else {
Serial.print("Failed, rc=");
Serial.println(mqttClient.state());
delay(5000);
}
}
}
void HandleMqtt() {
if (!mqttClient.connected()) {
ConnectMqtt();
}
mqttClient.loop();
}
void PublishMqtt(int data) {
mqttClient.publish("encender/led", String(data).c_str());
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON1, INPUT_PULLUP);
pinMode(BUTTON2, INPUT_PULLUP);
pinMode(BUTTON3, INPUT_PULLUP);
pinMode(BUTTON4, INPUT_PULLUP);
pinMode(BUTTONRST, INPUT_PULLUP);
attachInterrupt(BUTTON1, button1ISR, FALLING);
attachInterrupt(BUTTON2, button2ISR, FALLING);
attachInterrupt(BUTTON3, button3ISR, FALLING);
attachInterrupt(BUTTON4, button4ISR, FALLING);
attachInterrupt(BUTTONRST, buttonRSTISR, FALLING);
ConnectWiFi();
InitMqtt();
}
void loop() {
HandleMqtt();
if (button1Pressed) {
button1Pressed = false;
PublishMqtt(1);
}
if (button2Pressed) {
button2Pressed = false;
PublishMqtt(2);
}
if (button3Pressed) {
button3Pressed = false;
PublishMqtt(3);
}
if (button4Pressed) {
button4Pressed = false;
PublishMqtt(4);
}
if(buttonRSTPressed) {
buttonRSTPressed = false;
PublishMqtt(0);
}
delay(10);
}