Hello
I am trying to send a sensor reading in packets of 100 data in Json format. Everything works very well but only for a certain time, suddenly I stopped receiving data from the broker
(HiveMQ). I am using an Arduino Nano 33 Iot card, for the Mqtt connection I tried the PubSubClient and ArduinoMqttClient libraries and with both I had the same problem.
This is the code:
#include <StreamUtils.h>
#include <StreamUtils.hpp>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <ArduinoJson.hpp>
#include <SPI.h>
#include <WiFiNINA.h>
#include <WiFiSSLClient.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "###"; // your network SSID (name)
char pass[] = "###"; // your network password (use for WPA, or use as key for WEP)
WiFiSSLClient wifiSSLClient;
PubSubClient client(wifiSSLClient);
const char broker[] = "###########s2.eu.hivemq.cloud";
int port = 8883;
const char topic[] = "myTopic";
String Cov = "";
//const long interval = 500;
//unsigned long previousMillis = 0;
StaticJsonDocument<4096> doc;
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect("arduinoClient")) {
// Once connected, publish an announcement...
client.publish("StatusSensor", "Reconnecting");
// ... and resubscribe
client.subscribe("topic");
}
return client.connected();
}
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// attempt to connect to WiFi network:
Serial.print(F("Attempting to connect to WPA SSID: "));
Serial.println(F(ssid));
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(3000);
}
Serial.println(F("You're connected to the network"));
Serial.println();
client.setServer(broker, port);
client.connect(broker, "Name", "Password");
Serial.print(client.state());
lastReconnectAttempt = 0;
}
void loop() {
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected
JsonArray ArSensor1 = doc.createNestedArray("Sensor_1");
for (int i = 0; i < 99; i++) {
int var = analogRead(A0);
for (int x = 0; x <= 1; x++) {
ArSensor1.add(var);
}
}
WriteBufferingStream bufferedWifiClient(wifiSSLClient, 64);
serializeJson(doc, Serial);
client.beginPublish(topic, measureJson(doc), 1);
serializeJson(doc, bufferedWifiClient);
bufferedWifiClient.flush();
client.endPublish();
doc.clear();
Serial.println();
delay(10);
client.loop();
}
}