Created
July 20, 2020 19:12
-
-
Save gsampallo/5759ef48447cd848bf59135f83a586d0 to your computer and use it in GitHub Desktop.
DPRE - Publicar datos en un tema
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <ESP8266WiFi.h> | |
| #include <PubSubClient.h> | |
| //Reemplace por los datos de la red iot | |
| const char* ssid = "Nombre_red"; | |
| const char* password = "Clave_red"; | |
| const char* mqtt_server = "Servidor_MQTT"; | |
| WiFiClient espClient; | |
| PubSubClient client(espClient); | |
| /* | |
| * Boton | |
| * Reemplace por el nro. de GPIO correcto | |
| */ | |
| int pinBoton = XXX | |
| void setup() { | |
| Serial.begin(115200); | |
| pinMode(pinBoton,INPUT); | |
| 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); | |
| } | |
| void callback(char* topic, byte* payload, unsigned int length) { | |
| //Aun no utilizamos esta funcion | |
| } | |
| void reconectar() { | |
| while (!client.connected()) { | |
| String clientId = "ESP8266Client-"; | |
| clientId += String(random(0xffff), HEX); | |
| if (client.connect(clientId.c_str()) { | |
| Serial.println("conectado"); | |
| } else { | |
| delay(5000); | |
| } | |
| } | |
| } | |
| void loop() { | |
| if (!client.connected()) { | |
| reconectar(); | |
| } | |
| client.loop(); | |
| if(digitalRead(pinBoton) == LOW) { | |
| client.publish("MQTT1", "Este es un mensaje"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment