#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define botonA 27
#define botonB 26
#define botonC 25
#define botonD 14
volatile bool botonA_pressed = false;
volatile bool botonB_pressed = false;
volatile bool botonC_pressed = false;
volatile bool botonD_pressed = false;
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
void IRAM_ATTR botonA_pulsado() {
botonA_pressed = true;
}
void IRAM_ATTR botonB_pulsado() {
botonB_pressed = true;
}
void IRAM_ATTR botonC_pulsado() {
botonC_pressed = true;
}
void IRAM_ATTR botonD_pulsado() {
botonD_pressed = true;
}
// constantes del MQTT
// direccion broker, puerto, y nombre cliente
const char *MQTT_BROKER_ADRESS = "mqtt.eclipseprojects.io";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "PabloRomero_pub_test";
// instanciar objetos
WiFiClient espClient;
PubSubClient mqttClient(espClient);
String payload;
String content = "";
void ConnectWiFi()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
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.print("Client connected");
}
else
{
Serial.print("Failed MQTT connection, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void HandleMqtt()
{
if (!mqttClient.connected())
{
ConnectMqtt();
}
mqttClient.loop();
}
void PublishMqtt_BLeds(String data)
{
payload = "";
payload = String(data);
mqttClient.publish("Interfaz/input", (char *)payload.c_str());
}
void PublishMqtt_BAlarma(String data)
{
payload = "";
payload = String(data);
mqttClient.publish("Interfaz/alarma", (char *)payload.c_str());
}
void setup() {
Serial.begin(115200);
pinMode(botonA, INPUT_PULLUP);
pinMode(botonB, INPUT_PULLUP);
pinMode(botonC, INPUT_PULLUP);
pinMode(botonD, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(botonA), botonA_pulsado, RISING);
attachInterrupt(digitalPinToInterrupt(botonB), botonB_pulsado, RISING);
attachInterrupt(digitalPinToInterrupt(botonC), botonC_pulsado, RISING);
attachInterrupt(digitalPinToInterrupt(botonD), botonD_pulsado, RISING);
ConnectWiFi();
InitMqtt();
}
void loop()
{
HandleMqtt();
if(botonA_pressed){
PublishMqtt_BLeds("A");
botonA_pressed = false;
}
else if(botonB_pressed){
PublishMqtt_BLeds("B");
botonB_pressed = false;
}
else if(botonC_pressed){
PublishMqtt_BLeds("C");
botonC_pressed = false;
}
else if(botonD_pressed){
PublishMqtt_BAlarma("Alarma");
botonD_pressed = false;
}
delay(10); // this speeds up the simulation
}