From 5b315cd274fa942597c3dab874da8b8705112acc Mon Sep 17 00:00:00 2001 From: andrespm Date: Sun, 3 Jul 2022 17:41:13 -0500 Subject: [PATCH] mqtt cliente arduino --- mqtt_BBB.ino | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 mqtt_BBB.ino diff --git a/mqtt_BBB.ino b/mqtt_BBB.ino new file mode 100644 index 0000000..2a61a64 --- /dev/null +++ b/mqtt_BBB.ino @@ -0,0 +1,71 @@ +#include +#include + +const char* ssid = "Familia 2.4G"; +const char* password = "rr20072015"; +const char* mqttServer = "192.168.1.17"; +const int mqttPort = 1883; +const char* mqttUser = ""; +const char* mqttPassword = ""; + +WiFiClient espClient; +PubSubClient client(espClient); + +void OnMqttReceived(char *topic, byte *payload, unsigned int length) +{ + Serial.print("Received on "); + Serial.print(topic); + Serial.print(": "); + String content = ""; + for (size_t i = 0; i < length; i++) + { + content.concat((char)payload[i]); + } + Serial.print(content); + Serial.println(); +} + +void setup() +{ Serial.begin(115200); + WiFi.begin(ssid, password); + Serial.println("..................................."); + + Serial.print("Connecting to WiFi."); + while (WiFi.status() != WL_CONNECTED) + { delay(500); + Serial.print(".") ; + } + Serial.println("Connected to the WiFi network"); + + client.setServer(mqttServer, mqttPort); +while (!client.connected()) +{ Serial.println("Connecting to MQTT..."); + if (client.connect("prueba", mqttUser, mqttPassword )) + {Serial.println("connected"); + client.subscribe("prueba/xd"); + client.setCallback(OnMqttReceived); + } + else + { Serial.print("failed with state "); + Serial.print(client.state()); + delay(2000); + } +} +} + +void loop() + { client.loop(); + char str[16]; + +if(Serial.read()>0) +{ +sprintf(str, "%u", random(100)); + +client.publish("prueba/xd", str); +Serial.println(str); +delay(100); +} + + + + }