Skip to content

Instantly share code, notes, and snippets.

@gsampallo
Created July 21, 2020 14:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gsampallo/274542038b4df31b6ee430c39a2d5487 to your computer and use it in GitHub Desktop.
DPRE - Suscribirse a un tema con MQTT
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//Reemplace por los datos de la red iot
const char* ssid = "Nombre_red";
const char* password = "password";
const char* mqtt_server = "mqtt_server";
WiFiClient espClient;
PubSubClient client(espClient);
/*
* LED/BOTON
* Reemplace por el nro. de GPIO correcto
*/
int pinLed1 = 5;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Conectando");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("Conectado");
Serial.print("Direccion: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
/*
* A continuacion especifique el modo de operacion
* de los GPIO
*/
}
void callback(char* topic, byte* payload, unsigned int length) {
//Se converte topic a un String
String tema = String(topic);
//Se convierte la cadena de bytes en un String
String mensaje = String((char*)payload).substring(0,length);
Serial.println(tema+":"+mensaje);
if(mensaje == "LED1") {
digitalWrite(pinLed1,HIGH);
digitalWrite(pinLed2,LOW);
digitalWrite(pinLed3,LOW);
}
}
void reconectar() {
while(!client.connected()) {
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("conectado a "+String(mqtt_server));
client.subscribe("LED");
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconectar();
}
client.loop();
delay(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment