NTP clock not being able to get in sync

I've been triyng for the past ours to make a functioning clock, that get updated once every hour for an automated greenhouse I've been building.
The problem is that once I connect to the NTP server and get the time, if I want to get it in sync after same time(otherwise it drift dramaticcally over time), I can't get to make the timeClient.update(); function to work.

Here I'll provide the source code, the interesting part should be the syncTimeFromNTP() function:

void syncTimeFromNTP() {
  // Check WiFi connection before attempting to update time
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("- WiFi not connected, skipping NTP sync");
    return;
  }

  // Update time from NTP server
  Serial.println("- Attempting to synchronize NTP time...");

  timeClient.forceUpdate();
  
  if (timeClient.forceUpdate() == 1) {  // Ensure time was successfully updated
    Serial.println("- NTP time synchronized successfully");

    // Get the current date and time from an NTP server and convert
    // it to UTC +2 by passing the time zone offset in hours.
    // You may change the time zone offset to your local one.
    auto timeZoneOffsetHours = 2;
    auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
    Serial.print("Unix time = ");
    Serial.println(unixTime);
    RTCTime timeToSet = RTCTime(unixTime);
    RTC.setTime(timeToSet);

    // Retrieve the date and time from the RTC and print them
    RTCTime currentTime;
    RTC.getTime(currentTime); 
    Serial.println("The RTC was just set to: " + String(currentTime));

  } else {
    Serial.println("- Failed to synchronize NTP time");
  }
}

and the set up and loop parts about the clock.

while (!Serial);

  connectToWiFi();
  RTC.begin();
  Serial.println("\nStarting connection to server...");
  timeClient.begin();
  timeClient.update();

  // Get the current date and time from an NTP server and convert
  // it to UTC +2 by passing the time zone offset in hours.
  // You may change the time zone offset to your local one.
  auto timeZoneOffsetHours = 2;
  auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
  Serial.print("Unix time = ");
  Serial.println(unixTime);
  RTCTime timeToSet = RTCTime(unixTime);
  RTC.setTime(timeToSet);

  // Retrieve the date and time from the RTC and print them
  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println("The RTC was just set to: " + String(currentTime));

Here's the source code.

#include "DHT.h" 
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
#include "Arduino_LED_Matrix.h"
ArduinoLEDMatrix matrix;

//tutta la roba per l'orologio
#include "RTC.h"
#include <NTPClient.h>
#if defined(ARDUINO_PORTENTA_C33)
#include <WiFiC3.h>
#elif defined(ARDUINO_UNOWIFIR4)
#include <WiFiS3.h>
#endif

#include <WiFiUdp.h>
#include "arduino_secrets.h" 

  //display base 
  uint8_t Frame[8][12] = {
  { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
  byte Digits[6][33] = {
  {1,1,1, 0,0,1, 1,1,1, 1,1,1, 1,0,0, 1,1,1, 1,1,1, 1,1,1, 1,1,1, 1,1,1, 1,0,0},  
  {1,0,1, 0,0,1, 0,0,1, 0,0,1, 1,0,0, 1,0,0, 1,0,0, 0,0,1, 1,0,1, 1,0,1, 1,0,0},
  {1,0,1, 0,0,1, 1,1,1, 0,1,1, 1,0,0, 1,1,1, 1,0,0, 0,0,1, 1,1,1, 1,1,1, 0,1,0},
  {1,0,1, 0,0,1, 1,0,0, 0,0,1, 1,0,1, 0,0,1, 1,1,1, 0,0,1, 1,0,1, 0,0,1, 0,1,0},
  {1,0,1, 0,0,1, 1,0,0, 0,0,1, 1,1,1, 0,0,1, 1,0,1, 0,0,1, 1,0,1, 0,0,1, 0,0,1},
  {1,1,1, 0,0,1, 1,1,1, 1,1,1, 0,0,1, 1,1,1, 1,1,1, 0,0,1, 1,1,1, 1,1,1, 0,0,1},
  };

int AirValue = 560;
int WaterValue = 240;
int soilMoistureValue = 0;
int soilmoisturepercent = 0;
int sensorStatusReset = 7; 
bool sensorReset = 0;

bool sensorOn0 = 1;  //attivano o meno i vari sensori
bool sensorOn1 = 1;
bool sensorOn2 = 1;

int valoriSensoriUmidity[3];
int s = 0;  //somma valori dell'array
int mediaValori; 

int counterStatus = 100; //per fare il check ogni 100 letture

int checkHS1;    //primo dato di comparazione soil humidity sensor
int checkHS2;    //secondo dato di comparazione soil humidity sensor
int resoult;     //differenza tra checkHS 1 e 2 

int debugLed = 8; 
int debugLedButton = 0; //per poi leggere il valore del bottone

int pinPompa = 10;      //pin che manda poi il segnale al relay
int bottonePompa = 12;   //bottone manuale per attivare la pompa
int varBottonePompa = 0;  //serve per leggere il valore del bottone e assegnarlo da qualche parte
int counterPompa = 0; //per dare il tempo alla terra di assorbire l'acqua e non darla nuovamente dopo 1 ciclo


//roba per l'orologio
char ssid[] = "FASTWEB-1-70E8EF-EXT";        // your network SSID (name)
char pass[] = "babbalussi";    // your network password (use for WPA, or use as key for WEP)

int wifiStatus = WL_IDLE_STATUS;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
NTPClient timeClient(Udp);


//illuminazione
int pinLampada = 11; 

//bottone lampada
int pinBottoneLampada = 6; 
int varBottoneLampada = 0; //contiene il valore(HIGH-LOW) 
bool switchLampada = false;  //gestisce se attivare o meno la mod. in automatico della lampada, quando è false serra in auto, quando è true serra in manual



void displayDigits(int d,int px,int py){
  for (int i=0; i<6; i++)
    for (int j=0; j<3; j++)
      Frame[i+py][j+px]= Digits[i][j+d*3]; 

  matrix.renderBitmap(Frame, 8, 12);
}

void soilMoistureCheck(){
  Serial.println("-troubleshooting...");
  counterStatus = 0;
  for (int j=0; j<4; j++){
    switch(j){
      case 0: 
      checkHS1 = analogRead(A0);
      delay(200);
      checkHS2 = analogRead(A0);
      resoult = checkHS1 - checkHS2;       //check the difference beetwin the last two readings to see if they are consistant (when a sensor is disconnected the analog in pin trows random numbers)
      Serial.println(abs(resoult));
      Serial.println(checkHS1);
      if(abs(resoult) > 300 || checkHS2 > 610){
        sensorOn0 = 0;
        Serial.println("-0: no consistent data, check connection");
      }else{
        Serial.println("-sensor 0 working!");
      }
      break;
      case 1:
      checkHS1 = analogRead(A1);
      delay(200);                                      
      checkHS2 = analogRead(A1);
      resoult = checkHS1 - checkHS2;       
      Serial.println(abs(resoult));
      Serial.println(checkHS1);
      if(abs(resoult) > 300 || checkHS2 > 610){
        sensorOn1 = 0;
        Serial.println("-1: no consistent data, check connection");
      }else{
        Serial.println("-sensor 1 working!");
      }
      break;
      case 2:
      checkHS1 = analogRead(A2);
      delay(200);
      checkHS2 = analogRead(A2);
      resoult = checkHS1 - checkHS2;       
      Serial.println(abs(resoult));
      Serial.println(checkHS1);
      if(abs(resoult) > 300 || checkHS2 > 610){
        sensorOn2 = 0;
        Serial.println("-2: no consistent data, check connection");
      }else{
        Serial.println("-sensor 2 working!");
      }
      break;
    }
  }
    
}

void soilMoistureSensor(){

  s = 0; //resetta la somma ogni volta che viene eseguita la lettura



  for (int i=0; i<3; i++){
    
    switch (i) {
      case 0:
        if(sensorOn0 == 1){
          soilMoistureValue = analogRead(A0);  
          //Serial.println(soilMoistureValue);
          soilmoisturepercent = map(soilMoistureValue, AirValue, WaterValue, 0, 100);  
          Serial.println(soilmoisturepercent);  
          valoriSensoriUmidity[0] = soilmoisturepercent;
        }   
        break;
      case 1:
        if(sensorOn1 == 1){
          soilMoistureValue = analogRead(A1);
          //Serial.println(soilMoistureValue);
          soilmoisturepercent = map(soilMoistureValue, AirValue, WaterValue, 0, 100);
          Serial.println(soilmoisturepercent);
          valoriSensoriUmidity[1] = soilmoisturepercent;
        }
        break;
      case 2:
        if(sensorOn2 == 1){
          soilMoistureValue = analogRead(A2);
          //Serial.println(soilMoistureValue);
          soilmoisturepercent = map(soilMoistureValue, AirValue, WaterValue, 0, 100);
          Serial.println(soilmoisturepercent);
          valoriSensoriUmidity[2] = soilmoisturepercent;
        }  
        break;
    }
  }


 for (int j=0; j< 3; j++){
    s += valoriSensoriUmidity[j];
 }

 mediaValori = s / 3; 
 Serial.print("Soil Humidity: "); 
 Serial.print(mediaValori);
 Serial.println("%"); 

}

void attivaPompa(){
  digitalWrite(pinPompa, LOW);
  Serial.println("-activating pump..."); 
  delay(5000); 
  digitalWrite(pinPompa, HIGH);
  Serial.println("-plants watered successfully."); 
}

void printWifiStatus(){
  // print the SSID of the network you're attached to:
  Serial.print("SSID: FASTWEB-1-70E8EF-EXT ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void connectToWiFi(){
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (wifiStatus != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    wifiStatus = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  Serial.println("Connected to WiFi");
  printWifiStatus();
}

void syncTimeFromNTP() {
  // Check WiFi connection before attempting to update time
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("- WiFi not connected, skipping NTP sync");
    return;
  }

  // Update time from NTP server
  Serial.println("- Attempting to synchronize NTP time...");

  timeClient.forceUpdate();
  
  if (timeClient.forceUpdate() == 1) {  // Ensure time was successfully updated
    Serial.println("- NTP time synchronized successfully");

    // Get the current date and time from an NTP server and convert
    // it to UTC +2 by passing the time zone offset in hours.
    // You may change the time zone offset to your local one.
    auto timeZoneOffsetHours = 2;
    auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
    Serial.print("Unix time = ");
    Serial.println(unixTime);
    RTCTime timeToSet = RTCTime(unixTime);
    RTC.setTime(timeToSet);

    // Retrieve the date and time from the RTC and print them
    RTCTime currentTime;
    RTC.getTime(currentTime); 
    Serial.println("The RTC was just set to: " + String(currentTime));

  } else {
    Serial.println("- Failed to synchronize NTP time");
  }
}

void setup() {
  Serial.begin(9600);

  //roba per l'orologio
  while (!Serial);

  connectToWiFi();
  RTC.begin();
  Serial.println("\nStarting connection to server...");
  timeClient.begin();
  timeClient.update();

  // Get the current date and time from an NTP server and convert
  // it to UTC +2 by passing the time zone offset in hours.
  // You may change the time zone offset to your local one.
  auto timeZoneOffsetHours = 2;
  auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
  Serial.print("Unix time = ");
  Serial.println(unixTime);
  RTCTime timeToSet = RTCTime(unixTime);
  RTC.setTime(timeToSet);

  // Retrieve the date and time from the RTC and print them
  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println("The RTC was just set to: " + String(currentTime));


  //altra roba
  Serial.println(F("DHTxx test!"));
  dht.begin();
  matrix.begin();
  pinMode(sensorStatusReset, INPUT); 
  pinMode(debugLed, OUTPUT); 
  pinMode(bottonePompa, INPUT);
  pinMode(pinPompa, OUTPUT);
  digitalWrite(pinPompa, HIGH);  //la pompa è disattivata quando do 5v al relay 
  pinMode(pinLampada, OUTPUT);
  pinMode(pinBottoneLampada, INPUT);
}









void loop() {
  delay(2000);


  // Fetch current time values
  int currentHour = timeClient.getHours();
  int currentMin = timeClient.getMinutes();
  int currentSec = timeClient.getSeconds();

  if(currentMin == 0 && currentSec < 3){
  syncTimeFromNTP();
  }


  if(currentMin % 2 == 0 && currentSec < 3){
    Serial.println("-syncronizing the clock...");
    syncTimeFromNTP();
  }


  //soil moisture sensor error reset button
  debugLedButton = digitalRead(sensorStatusReset);
  if(debugLedButton == HIGH){
    sensorReset = 1;
    digitalWrite(debugLed, LOW);
    Serial.println("-al sensors resetted succesfully");
  }

  if(sensorReset == 1){
    Serial.println("-all sensor set to 1");
    sensorOn0 = 1;
    sensorOn1 = 1;
    sensorOn2 = 1;
    sensorReset = 0; 
  }


  if(sensorOn0 == 1 & sensorOn1 == 1 & sensorOn2 == 1){
    soilMoistureSensor();
  }else {
    digitalWrite(debugLed, HIGH);
    Serial.println("-soil moisture sensors non working properly");
  }
  


  
  if(counterStatus == 100){
   soilMoistureCheck(); 
  }
  counterStatus ++;  //aggiunge uno al counter per capire quando eseguire il check
  Serial.print("Counter status: "); 
  Serial.println(counterStatus); 



  if(currentHour > 5 && currentHour < 18){
    if(counterPompa >= 100 && mediaValori < 80){  
    attivaPompa();
    counterPompa = 0; 
    }
  }

  varBottonePompa = digitalRead(bottonePompa);
  if(varBottonePompa == HIGH){
    attivaPompa();
  }
  counterPompa ++; 
  Serial.print("Counter pompa: "); 
  Serial.println(counterPompa); 



  //roba per la luce
  varBottoneLampada = digitalRead(pinBottoneLampada);
  if(varBottoneLampada == HIGH){
    digitalWrite(pinLampada, LOW);
    if(switchLampada == false){
      switchLampada = true;
      Serial.println("-luce impostata su accensione manuale");
    }else{
      switchLampada = false;
      Serial.println("-luce impostata su accensione automatica");
    }
  }

  if(switchLampada == false){
    if(currentHour > 4 && currentHour < 18){   //non riesco ad aggiungere 2 per aggiustare la time zone, quindi semplicemente porto 2 ore prima da qui
      digitalWrite(pinLampada, HIGH);
    }else{
      digitalWrite(pinLampada, LOW);
    }
  }


  



  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("-failed to read from DHT sensor!"));
    displayDigits(10,5,1);
    displayDigits(10,9,1);
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));

  int primaCifra = static_cast<int>(f) / 10;  // Cast a int per ottenere solo la parte intera
  int secondaCifra = static_cast<int>(f) % 10;  // Utilizza l'operatore modulo per ottenere la cifra delle unità

  Serial.print(currentHour);
  Serial.print(", ");
  Serial.print(currentMin);
  Serial.print(", ");
  Serial.println(currentSec);

  if(currentHour > 4 && currentHour < 21){
    displayDigits(primaCifra,5,1);
    displayDigits(secondaCifra,9,1);
    matrix.renderBitmap(Frame, 8, 12);
 }


  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println(String(currentTime));
}

Please I am desperate...

Hi @andreamalagugini

welcome to the arduino-forum

Well done to post your code as a code-section in your first posting.
You should provide more detail information about your project:

what exact type of microcontroller are you using?
ESP32 is not exact enough

ESP32 ?
ESP32S2 ?
ESP32S3 ?
ESP32C3 ?

ESP32-Arduino ?

The code you have posted has some

#if defined 

for different microcontrollers

If it is an ESP32 that keeps connected to your WiFi the time gets updated automatically.

For ESP8266 / ESP32 much less code is nescessary to make it work
Here is a small Demo-Code for ESP32

#include <WiFi.h>

unsigned long MyTestTimer = 0;                   // variables MUST be of type unsigned long
const byte    OnBoard_LED = 2;

//const char *ssid     = ""; 
const   char *ssid     = "";

const char *password = "";

// a lot of home-wlan-routers can be used as a NTP-server too
const char* ntpServer = "fritz.box"; 
const long  gmtOffset_sec = 0;
const int   daylightOffset_sec = 7200;

#include <time.h>                   // time() ctime()
time_t now;                         // this is the epoch
tm myTimeInfo;                      // the structure tm holds time information in a more convient way

void showTime() {
  time(&now);                       // read the current time
  localtime_r(&now, &myTimeInfo);           // update the structure tm with the current time
  Serial.print("year:");
  Serial.print(myTimeInfo.tm_year + 1900);  // years since 1900
  Serial.print("\tmonth:");
  Serial.print(myTimeInfo.tm_mon + 1);      // January = 0 (!)
  Serial.print("\tday:");
  Serial.print(myTimeInfo.tm_mday);         // day of month
  Serial.print("\thour:");
  Serial.print(myTimeInfo.tm_hour);         // hours since midnight  0-23
  Serial.print("\tmin:");
  Serial.print(myTimeInfo.tm_min);          // minutes after the hour  0-59
  Serial.print("\tsec:");
  Serial.print(myTimeInfo.tm_sec);          // seconds after the minute  0-61*
  Serial.print("\twday");
  Serial.print(myTimeInfo.tm_wday);         // days since Sunday 0-6
  if (myTimeInfo.tm_isdst == 1)             // Daylight Saving Time flag
    Serial.print("\tDST");
  else
    Serial.print("\tstandard");
    
  Serial.println();
}

void connectToWifi() {
  Serial.print("Connecting to "); 
  Serial.println(ssid);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    BlinkHeartBeatLED(OnBoard_LED, 333);
    delay(332);
    Serial.print(".");
  }
  Serial.print("\n connected.");
  Serial.println(WiFi.localIP() );

}

void synchroniseWith_NTP_Time() {
  Serial.print("configTime uses ntpServer ");
  Serial.println(ntpServer);
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  Serial.print("synchronising time");
  
  while (myTimeInfo.tm_year + 1900 < 2000 ) {
    time(&now);                       // read the current time
    localtime_r(&now, &myTimeInfo);
    BlinkHeartBeatLED(OnBoard_LED, 100);
    delay(100);
    Serial.print(".");
  }
  Serial.print("\n time synchronsized \n");
  showTime();    
}


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println(__FILE__);
  Serial.print( F("  compiled ") );
  Serial.print(__DATE__);
  Serial.print( F(" ") );
  Serial.println(__TIME__);  
}

boolean TimePeriodIsOver (unsigned long &periodStartTime, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();  
  if ( currentMillis - periodStartTime >= TimePeriod )
  {
    periodStartTime = currentMillis; // set new expireTime
    return true;                // more time than TimePeriod) has elapsed since last time if-condition was true
  } 
  else return false;            // not expired
}


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);
  
  if ( TimePeriodIsOver(MyBlinkTimer,BlinkPeriod) ) {
    digitalWrite(IO_Pin,!digitalRead(IO_Pin) ); 
  }
}


void setup() {
  Serial.begin(115200);
  Serial.println("\n Setup-Start \n");
  PrintFileNameDateTime();
  
  connectToWifi();
  synchroniseWith_NTP_Time();
}

void loop() {
  BlinkHeartBeatLED(OnBoard_LED,100);

  if ( TimePeriodIsOver(MyTestTimer,1000) ) {
    showTime();    
  }  
}
1 Like

I'll echo what Stefan says -we need to know EXACTLY what you are using
the best way is to provide links to the source of your parts - like this

This looks suspicious: call it, but don't check the return value; then immediately call it again. What if it works the first time, but not the second?

This is not the first time I have seen this usage. If the collective wisdom is that you have to call it twice to work :person_shrugging: then wouldn't it be better to do

if (timeClient.forceUpdate() || timeClient.forceUpdate()) {

Hi, thank you for your help.
In the first place the device I am using is an Arduino Uno R4 WiFi, so it has incorporated an ESP32-S3-MINI-1.

The exact bord I am using is this one.

https://www.amazon.it/dp/B0C8V88Z9D?ref=nb_sb_ss_w_as-reorder_k4_1_8&amp=&crid=37X7ZA8HU85&amp=&sprefix=arduino+

Also I tried the code you provided but I ran in some issues, with this two functions:

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

and then this one.

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

This is the error log.

C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino: In function 'void connectToWifi()':
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino:49:8: error: 'class CWifi' has no member named 'persistent'
   WiFi.persistent(false);
        ^~~~~~~~~~
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino:50:8: error: 'class CWifi' has no member named 'mode'
   WiFi.mode(WIFI_STA);
        ^~~~
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino:50:13: error: 'WIFI_STA' was not declared in this scope
   WiFi.mode(WIFI_STA);
             ^~~~~~~~
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino:50:13: note: suggested alternative: 'PIN_SDA'
   WiFi.mode(WIFI_STA);
             ^~~~~~~~
             PIN_SDA
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino: In function 'void synchroniseWith_NTP_Time()':
C:\Users\User\AppData\Local\Temp\.arduinoIDE-unsaved202497-1616-1ch11kb.g85jh\sketch_oct7b\sketch_oct7b.ino:67:3: error: 'configTime' was not declared in this scope
   configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
   ^~~~~~~~~~

exit status 1

Compilation error: 'class CWifi' has no member named 'persistent'

I don't know if it is because the board I am using, or I am doing something wrong.

I applied the modification that suggested @kenb4 and for now is working, but considering that yesterday I had already tried to recall the timeClient.update(); function only once, and didn't work, I don't know how reliable this method is.

Tomorrow i'll run some more tests and I'll see the resoult, thank you for the help and I'll keep you updated.

edit: I ran a lot of tests, and it mostly didn't work, it was super unreliable. Also i noticed that when i powered the arduino from the 12 volt input, it 100% didn't work, when it was connected to my pc via USB, it was more reliable. Doesn't make sense to me, but this are the resoult... :person_shrugging:

I have zero kowledge how this ESP32-S3 is connected to the renesas microcontroller.

From a distant look it seems pretty complicated to have two microcontrollers connected in this way.

A singular and solely ESP32 can do a lot of things. It might be that this renesas R4-microcontroller can do more things like lot's of high resolution timers, hardware-encoder analysis etc. but how often are they needed?

The fact that it is from "arduino" doesn't make it better.
In regard of libraries the pure ESP32-board family is years ahead of this Uno R4
This Uno R4 is not compatibel with the pure ESP32.

Thanks guys for all the help, I somehow found a solution, it doesn't work 100% of times but is good enough. I eliminated some usless code, and added a bunch of redunducy to the part that reguards the check for sync and connection to the internet. However I still don't understand the couse of the problems... probably as @StefanL38 sed is because of the two microcontrollers. Here's the code, if somebody that find this artical wants to replicate.

//clock stuff
#include "RTC.h"
#include <NTPClient.h>
#include <WiFiS3.h>


#include <WiFiUdp.h>
#include "arduino_secrets.h" 




//clock stuff
char ssid[] = "FASTWEB-1-70E8EF-EXT";        // your network SSID (name)
char pass[] = "babbalussi";    // your network password (use for WPA, or use as key for WEP)

int wifiStatus = WL_IDLE_STATUS;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
NTPClient timeClient(Udp);




//led NTP clock not able to che sync
int pinLedNTP = 5; 


//to compare when the ip is not valid
IPAddress zeroIP(0, 0, 0, 0);




void printWifiStatus(){
  // print the SSID of the network you're attached to:
  Serial.print("SSID: FASTWEB-1-70E8EF-EXT ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  if(ip == zeroIP){
    WiFi.disconnect();  // Se vuoi disconnettere, fallo qui
    delay(1000);        // Attendi un secondo
    WiFi.begin(ssid, pass);  // Riconnetti con le credenziali
    return;
  }

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void connectToWiFi(){
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (wifiStatus != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    wifiStatus = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  Serial.println("Connected to WiFi");
  printWifiStatus();
}

void syncTimeFromNTP() {
  // Check WiFi connection before attempting to update time
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("- WiFi not connected, skipping NTP sync");
    // Disconnect if already connected
    WiFi.disconnect();  // Se vuoi disconnettere, fallo qui
    delay(1000);        // Attendi un secondo
    WiFi.begin(ssid, pass);  // Riconnetti con le credenziali
    printWifiStatus();
    return;
  }

  // Update time from NTP server
  Serial.println("- Attempting to synchronize NTP time...");


  if (timeClient.update()) {  // Ensure time was successfully updated
    Serial.println("- NTP time synchronized successfully");
    digitalWrite(pinLedNTP, LOW);  //se il led che segnava l'orologio non in sync, questo lo resetta

    // Get the current date and time from an NTP server and convert
    // it to UTC +2 by passing the time zone offset in hours.
    // You may change the time zone offset to your local one.
    auto timeZoneOffsetHours = 2;
    auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
    Serial.print("Unix time = ");
    Serial.println(unixTime);
    RTCTime timeToSet = RTCTime(unixTime);
    RTC.setTime(timeToSet);

    // Retrieve the date and time from the RTC and print them
    RTCTime currentTime;
    RTC.getTime(currentTime); 
    Serial.println("The RTC was just set to: " + String(currentTime));




  } else {
    Serial.println("- Failed to synchronize NTP time");
    int currentHour = timeClient.getHours();
    if(currentHour > 4 && currentHour < 21){
      digitalWrite(pinLedNTP, HIGH);
    }
    RTCTime currentTime;
    RTC.getTime(currentTime); 
    Serial.println("The RTC was just set to: " + String(currentTime));
  }
}







void setup() {
  Serial.begin(9600);

  //roba per l'orologio
  while (!Serial);
  connectToWiFi();
  RTC.begin();
  Serial.println("\nStarting connection to server...");
  timeClient.begin();
  timeClient.update();

  // Get the current date and time from an NTP server and convert
  // it to UTC +2 by passing the time zone offset in hours.
  // You may change the time zone offset to your local one.
  auto timeZoneOffsetHours = 2;
  auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
  Serial.print("Unix time = ");
  Serial.println(unixTime);
  RTCTime timeToSet = RTCTime(unixTime);
  RTC.setTime(timeToSet);

  // Retrieve the date and time from the RTC and print them
  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println("The RTC was just set to: " + String(currentTime));


  pinMode(pinLedNTP, OUTPUT);

}




void loop() {
  delay(2000);


  // Fetch current time values
  int currentHour = timeClient.getHours();
  int currentMin = timeClient.getMinutes();
  int currentSec = timeClient.getSeconds();



  if(currentMin % 10 == 0 && currentSec < 3){
    Serial.println("-syncronizing the clock...");
    syncTimeFromNTP();
  }

  Serial.print(currentHour);
  Serial.print(":");
  Serial.print(currentMin);
  Serial.print(":");
  Serial.println(currentSec);

  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println(String(currentTime));
}

Keep in mind that this code is estrapolated from a program I wrote that is much longer, because it needs to manage an automatic greenhouse, so something might not work. Also I am quite new to programming, so the code is all but optimized.

You can cut out all the NTP/UDP libraries in the next version of the code.
Because all the necessary NTP stuff already comes with the ESP core.
You only need one line in setup to replace about 20 lines in your code.
This does it all, including daylight savings.

void setup() {
  configTzTime("CET-1CEST,M3.5.0,M10.5.0/3", "it.pool.ntp.org"); // Rome
}

See post#4 here.
Leo..

Unfortunately not. @andreamalagugini is using an Arduino Uno R4 WiFi. The main processor on this board is a Renesas RA4M1 (ARM). The application code is written for that processor. The ESP32 is merely used as a WiFi Modem. I've dug around and did find the ESP32's code on GitHub. So, in theory you could load it with your own application code. But seems like more trouble than it's worth. Just get an ESP32 board.

EDIT:
Note ... I'm just saying you can't directly use the regular, built-in ESP32 APIs for this. That's not to say the the code already in the ESP32 on the Arduino Uno R4 WiFi doesn't provide equivalent APIs that are called by the application code on the ARM and cause equivalent functions to be run on the ESP. But, it all seems unneccessarily complex. @andreamalagugini, is there some reason you require this dual-processor board for a clock project?

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