#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define btnA 14 //pin del boton A
#define btnB 27 //pin del boton B
#define btnC 33 //pin del boton C
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
volatile bool btnA_pressed = false;
volatile bool btnB_pressed = false;
volatile bool btnC_pressed = false;
//interrupcion del boton A
void IRAM_ATTR interrupt_BA(){
btnA_pressed = true;
}
//interrupcion del boton B
void IRAM_ATTR interrupt_BB(){
btnB_pressed = true;
}
//interrupcion del boton C
void IRAM_ATTR interrupt_BC(){
btnC_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_BA(bool data)
{
payload = "";
payload = String(data);
mqttClient.publish("PabloRomero/Boton A", (char *)payload.c_str()); //PabloRomero/buttons es el topic
btnA_pressed = false;
}
void PublishMqtt_BB(bool data)
{
payload = "";
payload = String(data);
mqttClient.publish("PabloRomero/Boton B", (char *)payload.c_str()); //PabloRomero/buttons es el topic
btnB_pressed = false;
}
void PublishMqtt_BC(bool data)
{
payload = "";
payload = String(data);
mqttClient.publish("PabloRomero/Boton C", (char *)payload.c_str()); //PabloRomero/buttons es el topic
btnC_pressed = false;
}
void setup(void)
{
Serial.begin(115200);
pinMode(btnA, INPUT_PULLUP);
pinMode(btnB, INPUT_PULLUP);
pinMode(btnC, INPUT_PULLUP);
ConnectWiFi();
InitMqtt();
//INTERRUPCIONES DE LOS BOTONES
attachInterrupt(digitalPinToInterrupt(btnA),interrupt_BA, RISING);
attachInterrupt(digitalPinToInterrupt(btnB),interrupt_BB, RISING);
attachInterrupt(digitalPinToInterrupt(btnC),interrupt_BC, RISING);
}
void loop()
{
HandleMqtt();
PublishMqtt_BA(btnA_pressed);
PublishMqtt_BB(btnB_pressed);
PublishMqtt_BC(btnC_pressed);
delay(1000);
}