Attempt to write more readable examples

This commit is contained in:
hsaturn
2021-05-13 03:19:51 +02:00
parent b228d35ab0
commit 25a721e06a

View File

@@ -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) * 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) * pro - small memory footprint (both ram and flash)
* - very simple to setup and use * - very simple to setup and use
@@ -30,7 +32,8 @@
const char* BROKER = "broker.emqx.io"; const char* BROKER = "broker.emqx.io";
const uint16_t BROKER_PORT = 1883; const uint16_t BROKER_PORT = 1883;
#include <my_credentials.h> const char* ssid = "";
const char* password = "";
static float temp=19; static float temp=19;
static MqttClient client; static MqttClient client;
@@ -39,7 +42,10 @@ void setup()
{ {
Serial.begin(115200); Serial.begin(115200);
delay(500); delay(500);
Serial << "Simple clients with wifi " << endl; Serial << "Simple clients with wifi " << endl;
if (strlen(ssid)==0)
Serial << "****** PLEASE MODIFY ssid/password *************" << endl;
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); WiFi.begin(ssid, password);
@@ -54,15 +60,28 @@ void setup()
void loop() 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;
if (not client.connected())
{
Serial << millis() << ": Not connected to broker" << endl;
return;
}
auto rnd=random(100); auto rnd=random(100);
if (rnd > 66) temp += 0.1; if (rnd > 66) temp += 0.1;
else if (rnd < 33) temp -= 0.1; else if (rnd < 33) temp -= 0.1;
client.publish("sensor/temperature", String(temp)); Serial << "--> Publishing a new sensor/temperature value: " << temp << endl;
client.publish("sensor/temperature", String(temp));
}
} }