Hello, I have the following code for my NodeMCU which had been working ok for a few days:
#include <PubSubClient.h>
#include <UbidotsESPMQTT.h>
#include <DHT.h>
#define DHTPIN 13 //what pin we're connected to
#define DHTPIN2 5
#define DHTPIN3 4
#define DHTPIN4 0`1
#define DHTTYPE DHT21 //DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE); //Initialize DHT sensor for normal 16mhz Arduino
DHT dht2(DHTPIN2, DHTTYPE);
DHT dht3(DHTPIN3, DHTTYPE);
float hum; //Stores humidity value
float temp; //Stores temperature value
float hum2; //Stores humidity value
float temp2; //Stores temperature value
float hum3; //Stores humidity value
float temp3; //Stores temperature valu
#define TOKEN "......" // Your Ubidots TOKEN
#define WIFINAME "..." //Your SSID
#define WIFIPASS "..." // Your Wifi Pass
Ubidots client(TOKEN);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void setup() {
dht.begin();
dht2.begin();
dht3.begin();
// put your setup code here, to run once:
client.ubidotsSetBroker("industrial.api.ubidots.com");
client.setDebug(true);
Serial.begin(9600);
client.wifiConnection(WIFINAME, WIFIPASS);
client.begin(callback);
}
void loop() {
// put your main code here, to run repeatedly:
if(!client.connected()){
client.reconnect();
}
hum = dht.readHumidity()-3.5;
temp= dht.readTemperature();
hum2 = dht2.readHumidity();
temp2= dht2.readTemperature();
hum3 = dht3.readHumidity()-1;
temp3= dht3.readTemperature();
client.add("temperature", temp);
client.add("temperature2", temp2);
client.add("temperature3", temp3);
client.ubidotsPublish("Node_Home");
delay(60000);
client.add("humidity", hum);
client.add("humidity2", hum2);
client.add("humidity3", hum3);
client.ubidotsPublish("Node_Home");
client.loop();
delay(60000);
}
Initially, the code worked but after some hours (never for a whole day) sending the data through MQTT I get this error: “Attempting MQTT connection…failed, rc=-2 try again in 3 seconds” and the only way to solve it was resetting my NodeMCU. Sometimes also, after re uploading the same code, I get the same error and it won’t send data as it can’t connect through MQTT. My Ubidots account is STEM. Any help would be appreciated.