From 25a721e06ac9db968ec4517a642fa786ff7910e4 Mon Sep 17 00:00:00 2001 From: hsaturn Date: Thu, 13 May 2021 03:19:51 +0200 Subject: [PATCH] Attempt to write more readable examples --- examples/simple-client/simple-client.ino | 35 ++++++++++++++++++------ 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/examples/simple-client/simple-client.ino b/examples/simple-client/simple-client.ino index 7ee7f5b..12ebf87 100644 --- a/examples/simple-client/simple-client.ino +++ b/examples/simple-client/simple-client.ino @@ -16,8 +16,10 @@ * | | * +-----------------+ * - * 1 - edit my_credentials.h to setup wifi essid/password + * 1 - change the ssid/password * 2 - change BROKER values (or keep emqx.io test broker) + * 3 - you can use mqtt-spy to connect to the same broker and + * see the sensor/temperature updated by the client. * * pro - small memory footprint (both ram and flash) * - very simple to setup and use @@ -30,7 +32,8 @@ const char* BROKER = "broker.emqx.io"; const uint16_t BROKER_PORT = 1883; -#include +const char* ssid = ""; +const char* password = ""; static float temp=19; static MqttClient client; @@ -39,7 +42,10 @@ void setup() { Serial.begin(115200); delay(500); + Serial << "Simple clients with wifi " << endl; + if (strlen(ssid)==0) + Serial << "****** PLEASE MODIFY ssid/password *************" << endl; WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); @@ -54,15 +60,28 @@ void setup() void loop() { - client.loop(); + client.loop(); // Don't forget to call loop() for each broker and client - delay(1000); + // delay(1000); please avoid usage of delay (see below how this done using next_send and millis()) + static auto next_send = millis(); + + if (millis() > next_send) + { + next_send += 1000; - auto rnd=random(100); + if (not client.connected()) + { + Serial << millis() << ": Not connected to broker" << endl; + return; + } - if (rnd > 66) temp += 0.1; - else if (rnd < 33) temp -= 0.1; + auto rnd=random(100); - client.publish("sensor/temperature", String(temp)); + if (rnd > 66) temp += 0.1; + else if (rnd < 33) temp -= 0.1; + Serial << "--> Publishing a new sensor/temperature value: " << temp << endl; + + client.publish("sensor/temperature", String(temp)); + } }