#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define BUTTON_RED 26
#define BUTTON_YELLOW 27
#define BUTTON_GREEN 14
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
// constantes del MQTT
// direccion broker, puerto, y nombre cliente
const char *MQTT_BROKER_ADRESS = "test.mosquitto.org";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "ESP32_pub_buttons";
// instanciar objetos
WiFiClient espClient;
PubSubClient mqttClient(espClient);
volatile bool button_red_pressed = false;
volatile bool button_yellow_pressed = false;
volatile bool button_green_pressed = false;
String payload;
String content = "";
void buttonRedCallback(){
button_red_pressed = true;
}
void buttonYellowCallback(){
button_yellow_pressed = true;
}
void buttonGreenCallback(){
button_green_pressed = true;
}
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 PublishRed(String data)
{
mqttClient.publish("/red_button", (char *)data.c_str());
}
void PublishYellow(String data)
{
mqttClient.publish("/yellow_button", (char *)data.c_str());
}
void PublishGreen(String data)
{
mqttClient.publish("/green_button", (char *)data.c_str());
}
void setup(void)
{
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(BUTTON_RED), buttonRedCallback, RISING);
attachInterrupt(digitalPinToInterrupt(BUTTON_YELLOW), buttonYellowCallback, RISING);
attachInterrupt(digitalPinToInterrupt(BUTTON_GREEN), buttonGreenCallback, RISING);
ConnectWiFi();
InitMqtt();
}
void loop()
{
HandleMqtt();
if (button_red_pressed){
PublishRed("Button red pressed");
button_red_pressed = false;
}
if (button_yellow_pressed){
PublishYellow("Button yellow pressed");
button_yellow_pressed = false;
}
if (button_green_pressed){
PublishGreen("Button green pressed");
button_green_pressed = false;
}
delay(100);
}