[SOLVED] Couldn't use IoT Cloud more than once with Arduino UNO R4 WIFI

Hello! I'm wondering if there are any bugs in my three devices Arduino UNO R4 WIFI, I've read many shares here but not quite the same as what is happening to me. I am using this arduino uno to make distance measurements, as well as saving the data in an SD along with the current date and time and then, send it to Arduino Cloud. The first time, I set up my variables in Things, linked them in just one of my three devices and show the results in the dashboard successfully without any inconvenience in my home. Hours later I tried to set it up using the wifi from a different site and that's when it went downhill. My device does connect to my wifi but cannot get access to the Cloud and just stays disconnected while still getting the measurements. It always shows the next statement:

23:55:45.659 -> ***** Arduino IoT Cloud - configuration info *****
23:55:45.659 -> Device ID: 4b1d122e-xxxxxxxxxx
23:55:45.659 -> MQTT Broker: iot.arduino.cc:8883
23:55:45.724 -> Inicializando reloj RTC...
23:55:45.724 -> RTC inicializado
23:55:45.724 -> Inicializando tarjeta SD...
23:55:45.926 -> SD inicializada
23:55:45.959 -> WiFi.status(): 0
23:55:45.993 -> Current WiFi Firmware: 0.4.1
23:56:19.372 -> Connected to "IZZI-6D0C"
23:56:20.523 -> TimeServiceClass::getRemoteTime cannot get time from NTP, fallback on connection handler
23:56:20.523 -> TimeServiceClass::getRemoteTime cannot get time from connection handler
23:56:22.890 -> 2024/10/9 23:55:52 Tirante: 0.84 m Gasto: 2361.64 l/s Temperatura: 21.50 °C Humedad: 49.00 %

Like a couple of times tops the next error occurs:

ArduinoIoTCloudTCP::handle_ConnectMqttBroker could not connect to iot.arduino.cc:8883 Error: -2

I tried to set it up several times from the very start as the manual indicates, verified that the libraries used and the firmware are updated ... also tried reset, I tried uploading my sketch from the Cloud online and from Arduino IDE .... and then I tried to set up my other two arduinos with different wifi networks, and the same thing keeps happening. Any feedback will be highly appreciated!

I will add the script in case the problem is there. I'm making measurements in a channel every minute. (in my first try was every 10 seconds just to test how often I could receive the data in the Cloud and had no problem!)

#include "arduino_secrets.h"
/* 
  Sketch generated by the Arduino IoT Cloud Thing "Untitled"
  https://create.arduino.cc/cloud/things/05e1ad63-5005-47ae-800a-9cc53e1d9f82 

  Arduino IoT Cloud Variables description

  The following variables are automatically generated and updated when changes are made to the Thing

  CloudFlowRate gasto;
  CloudTemperatureSensor temperatura_atm;
  CloudLength tirante;
  CloudRelativeHumidity humedad_atm;
  CloudTime date;

  Variables which are marked as READ/WRITE in the Cloud Thing will also have functions
  which are called when their values are changed from the Dashboard.
  These functions are generated with the Thing and added at the end of this sketch.
*/

#include "thingProperties.h"
#include <Adafruit_Sensor.h> //para el sensor DHT
#include <DHT.h> //para el sensor DHT
#include <SD.h>  //para el SD
#include <SPI.h> //para el SD
#include <Wire.h> //para el reloj
#include <RTClib.h> //para el reloj

#define trigPin 6
#define echoPin 5
#define DHTPIN 2
#define DHTTYPE DHT11

const int chipSelect = 10;

DHT dht(DHTPIN, DHTTYPE); 
RTC_DS3231 rtc;

String ano;
String dia;
String mes;
String horas;
String minutos;
String segundos;
String Fecha;
String Hora;
String Nombrearchivo;
String Imprimir;

float n_canal = 0.015; 
float S_canal = 0.010205; 
float H_canal = 110.000; 
float tirante2 = -9999.00;
float Q2 = -9999.00;


void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500); 

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  
  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
 */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.println("Inicializando reloj RTC...");
  if(! rtc.begin())
  { Serial.println("No se encontró RTC");
  Serial.flush();
  while (1) delay(10);
  //abort();
  }
  if (rtc.lostPower())
  { Serial.println("RTC no está activado, colocar la hora");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); 
  }
  else
  { Serial.println("RTC inicializado");
  }
  
  Serial.println("Inicializando tarjeta SD...");
  if (!SD.begin(chipSelect))
  { Serial.println("No se pudo inicializar la SD, o no está conectada");
  }
  else
  { Serial.println("SD inicializada");
  }
  
  dht.begin();
  
}

void loop() {
  ArduinoCloud.update();
  delay (30000); //My way to give it time to update to the Cloud
    
  date = ArduinoCloud.getLocalTime();

  float h2 = dht.readHumidity();
  float t2 = dht.readTemperature();
  if (isnan(t2) || isnan(h2))   
  { Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
   
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  float duration = pulseIn(echoPin, HIGH);
  float d = (331/10000) * (duration/2.00);
  
  if (d<0) 
  {
    tirante2 = -9999.00;
    Q2 = -9999.00;
   }
  else
  { tirante2 = (H_canal - d)/100; //en metros
    if (tirante2<0)
    {
      tirante2 = -9999.00;
      Q2 = -9999.00;
    }
    else
    {
    float Ah = (0.6515 * tirante2 * tirante2) + (0.0301 * tirante2) + 0.00001; 
    float Pm = (2.4746 * tirante2) + 0.0259; 
    float Rh = Ah/Pm; 
    Q2 =  pow(Rh, 2/3) * sqrt(S_canal)  * Ah * 1000.00 / n_canal;
    }
  }
  
  DateTime now = rtc.now();
  ano = String(now.year());
  mes = String(now.month());
  dia = String(now.day());
  horas = String(now.hour());
  minutos = String(now.minute());
  segundos = String(now.second());
  Fecha = ano + "/" + mes + "/" + dia;
  Hora = horas + ":" + minutos + ":" + segundos;
  Nombrearchivo = ano + mes + dia + ".csv";

  Imprimir = Fecha;
  Imprimir += " ";
  Imprimir += Hora;
  Imprimir += " Tirante: ";
  Imprimir += tirante2;
  Imprimir += " m Gasto: ";
  Imprimir += Q2;
  Imprimir += " l/s Temperatura: ";
  Imprimir += t2;
  Imprimir += " °C Humedad: ";
  Imprimir += h2;
  Imprimir += " %";
  
  File dataFile = SD.open(Nombrearchivo, FILE_WRITE);
  //Si el archivo está disponible, escribir en él:
  if (dataFile)
  { dataFile.println(Imprimir);
    dataFile.close();
    Serial.println(Imprimir);
  }
  else
  { Serial.println("Error al intentar escribir en el archivo!");
  }

  tirante = tirante2;
  gasto = Q2;
  humedad_atm = h2;
  temperatura_atm = t2;
 
  delay(30000); //1 minute between readings
}

I don't edit the other scripts that are automatically created, except to write the wifi name and password when I upload the program through Arduino IDE.

I had a similar problem with a NANO 33 IoT and in my case it got fixed by deleting my device from Arduino Cloud and then set it up again entirely :thinking: In the best case maybe that could help you

1 Like

Thank you, but yes, I have also done that several times, always verifying that the device id in the Devices configuration were the same as what was stated in the Serial Monitor while the program was running.

1 Like

Hi @itainvr, you should not block the loop() flow with delay() when using ArduinoIoTCloud because you are not feeding the ArduinoIoTCloud state machine and in case of operations that must be done by an amount of time they fail. Try to time your logic using this

uint32_t lastSensorRead = 0; //declare as global variable (outside the function loop)
//In the loop() replace delay with
if(millis()-lastSensorRead >30000){
  date = ArduinoCloud.getLocalTime();

  float h2 = dht.readHumidity();
  float t2 = dht.readTemperature();
  if (isnan(t2) || isnan(h2))   
  { Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
   
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  float duration = pulseIn(echoPin, HIGH);
  float d = (331/10000) * (duration/2.00);
  
  if (d<0) 
  {
    tirante2 = -9999.00;
    Q2 = -9999.00;
   }
  else
  { tirante2 = (H_canal - d)/100; //en metros
    if (tirante2<0)
    {
      tirante2 = -9999.00;
      Q2 = -9999.00;
    }
    else
    {
    float Ah = (0.6515 * tirante2 * tirante2) + (0.0301 * tirante2) + 0.00001; 
    float Pm = (2.4746 * tirante2) + 0.0259; 
    float Rh = Ah/Pm; 
    Q2 =  pow(Rh, 2/3) * sqrt(S_canal)  * Ah * 1000.00 / n_canal;
    }
  }
  
  DateTime now = rtc.now();
  ano = String(now.year());
  mes = String(now.month());
  dia = String(now.day());
  horas = String(now.hour());
  minutos = String(now.minute());
  segundos = String(now.second());
  Fecha = ano + "/" + mes + "/" + dia;
  Hora = horas + ":" + minutos + ":" + segundos;
  Nombrearchivo = ano + mes + dia + ".csv";

  Imprimir = Fecha;
  Imprimir += " ";
  Imprimir += Hora;
  Imprimir += " Tirante: ";
  Imprimir += tirante2;
  Imprimir += " m Gasto: ";
  Imprimir += Q2;
  Imprimir += " l/s Temperatura: ";
  Imprimir += t2;
  Imprimir += " °C Humedad: ";
  Imprimir += h2;
  Imprimir += " %";
  
  File dataFile = SD.open(Nombrearchivo, FILE_WRITE);
  //Si el archivo está disponible, escribir en él:
  if (dataFile)
  { dataFile.println(Imprimir);
    dataFile.close();
    Serial.println(Imprimir);
  }
  else
  { Serial.println("Error al intentar escribir en el archivo!");
  }

  tirante = tirante2;
  gasto = Q2;
  humedad_atm = h2;
  temperatura_atm = t2;
}

You must remove also the first delay: delay (30000); //My way to give it time to update to the Cloud

1 Like

Thanks! I’ll try it. Actually, I added those delays because after the first try using Cloud and started failing connecting to IoT Cloud I still kept making measurements every 10 seconds and someone recommended me giving it more time between readings to see if that helped and in the field the project just needs the reading every 1-5 minutes, so I will give it a go!

So this is what I got from the lines changed in the script:

***** Arduino IoT Cloud - configuration info *****
Device ID: 08cc8213-xxxxxxxxxxxxxxxxxxxxxxxx
MQTT Broker: iot.arduino.cc:8883
Inicializando reloj RTC...
RTC no está activado, colocar la hora
Inicializando tarjeta SD...
SD inicializada
WiFi.status(): 0
Current WiFi Firmware: 0.4.1
Connected to "Movil"
TimeServiceClass::getRemoteTime cannot get time from NTP, fallback on connection handler
TimeServiceClass::getRemoteTime cannot get time from connection handler
ArduinoIoTCloudTCP::handle_SyncTime could not get valid time. Retrying now.

So I kept the old script to avoid the new error, but repeating my loop every 30 seconds so my connection to IoT Clould doesn't get lost although in Things configuration I just ask for the values every 1-2 minutes. I am not sure how to increase the time in my loop haha but that's another topic.

In case this helps others, I also did another consultation outside this forum to check if it had something to do with my computer or the wifi connection and the IP. What the person who helped me gathered is that the server and IoT Cloud is sensitive to the IP. You have to keep the same IP throughout the test you're doing with your project, so when I switch from my home to another place and just try to change the wifi configuration, it didn't work. In the other place I am trying to set my project, it is configured to keep changing IP regularly, so there it wouldn't work either. Since I am going to keep my projects in the same area, he reserved an static IP number for my devices and after that, I could get access to the IoT Cloud again!

I am not sure if it is mentioned in the Arduino documentation but I believe it is worth it to mention it here.

A post was split to a new topic: Problem with Arduino Cloud IoT project

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.