RTC: settaggio data e ora

Buongiorno avrei bisogno di capire se c'è un modo per settare la data e l'ora dell'RTC con quella attuale, in modo da mantenerla sembra aggiornata correttamente anche in caso di perdita di corrente. So che l'RTC ha una piccola batteria di supporto, ma ho notato che sfasa un po' in caso di perdita di corrente per lunghi periodi di tempo.
Qual è il metodo migliore per farlo?
E' possibile settarlo in automatico con la data e l'ora lette da internet?

Se il tuo Arduino (quale esattamente?) ha connessione internet, WiFi o Ethernet, si, tramite NTP, altrimenti ovviamente no.

Arduino Mega + Shield Ethernet 2 quindi tramite NTP si dovrebbe riuscire

Io in genere uso gli ESP8266 (come le WeMos) quindi non ho una Ethernet shield, ma tra gli esempi credo che dovresti avere anche un UdpNtpClient che puoi usare come spunto.

Si ho già testato quello sketch ma non stampa nulla sulla seriale...non so.

Molto strano, sei sicuro? Hai incluso nel setup la giusta Ethernet.init() con il pin CS del tuo shield? Possibile che non ti dà né errori né informazioni sul pacchetto ricevuto in risposta? Hai provato anche ad allungare il delay()?

Si

Si ho messo "Ethernet.init(10)"

Nessun errore e nessun pacchetto ricevuto...

Si, la situazione non cambia

Questo è il codice:

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

unsigned int localPort = 8888;       // local port to listen for UDP packets

const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start Ethernet and UDP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  Udp.begin(localPort);
}

void loop() {
  sendNTPpacket(timeServer); // send an NTP packet to a time server

  // wait to see if a reply is available
  delay(1000);
  if (Udp.parsePacket()) {
    // We've received a packet, read the data from it
    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    // the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, extract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if (((epoch % 3600) / 60) < 10) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ((epoch % 60) < 10) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
  Ethernet.maintain();
}

// send an NTP request to the time server at the given address
void sendNTPpacket(const char * address) {
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); // NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

Sul seriale non stampa nulla (Arduino Mega 2560 + Ethernet2 Shield)

Magari non c'entra nulla, ma la documentazione della libreria Ethernet dice chiaramente:

The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won’t work.

Ovvero il pin 53, sulla MEGA, va dichiarato OUTPUT e messo HIGH o, a quanto sembra, la SPI può dare problemi :roll_eyes:

Tentare non nuoce ...

Guglielmo

Ci ho provato ma nulla da fare...
Sul seriale non viene stampato nulla :frowning:

Prova a mettere un pò di Serial.println() nel programma, anche quando le cose vanno bene, esempio

Serial.begin(9600);
Serial.println("Avvio.");
while (!Serial) {

.......

  sendNTPpacket(timeServer); // send an NTP packet to a time server
  Serial.println("send ntp req");
  // wait to see if a reply is available
  delay(1000);

Ho già provato e credo che non riesca ad entrare in if (Udp.parsePacket()), probabilmente perché non si riceve nulla. Ho cambiato anche server const char timeServer[] = "time.nist.gov";...
Nulla da fare non capisco.

Allora a questo punto sospetto che sia un problema di networking.
Tu chiami un NTP su internet ("time.nist.gov", ma ti consiglierei di usare il pool italiano " 0.it.pool.ntp .org") ed aspetti sulla porta 8888 i pacchetti di risposta: in genere vedo negli esempi che usa la 2390, ma comunque non è che magari devi aprire sul tuo firewall quella porta UDP in ingresso?

Ci ho provato ma niente

@chris_ino: hai un problema hardware ... ho sia la MEGA che una Ethernet Shield, le ho semplicemente montate a sandwich, caricato il codice:

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

unsigned int localPort = 8888;       // local port to listen for UDP packets

const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
   delay ( 500 );
   // MEGA SS pin
   pinMode ( 53, OUTPUT );
   digitalWrite ( 53, HIGH );
   // You can use Ethernet.init(pin) to configure the CS pin
   Ethernet.init ( 10 ); // Most Arduino shields
   //Ethernet.init(5);   // MKR ETH shield
   //Ethernet.init(0);   // Teensy 2.0
   //Ethernet.init(20);  // Teensy++ 2.0
   //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
   //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

   // Open serial communications and wait for port to open:
   Serial.begin ( 115200 );
   while ( !Serial ) {
      ; // wait for serial port to connect. Needed for native USB port only
   }

   // start Ethernet and UDP
   if ( Ethernet.begin ( mac ) == 0 ) {
      Serial.println ( "Failed to configure Ethernet using DHCP" );
      // Check for Ethernet hardware present
      if ( Ethernet.hardwareStatus() == EthernetNoHardware ) {
         Serial.println ( "Ethernet shield was not found.  Sorry, can't run without hardware. :(" );
      } else if ( Ethernet.linkStatus() == LinkOFF ) {
         Serial.println ( "Ethernet cable is not connected." );
      }
      // no point in carrying on, so do nothing forevermore:
      while ( true ) {
         delay ( 1 );
      }
   }
   Udp.begin ( localPort );
}

void loop() {
   sendNTPpacket ( timeServer ); // send an NTP packet to a time server

   // wait to see if a reply is available
   delay ( 1000 );
   if ( Udp.parsePacket() ) {
      // We've received a packet, read the data from it
      Udp.read ( packetBuffer, NTP_PACKET_SIZE ); // read the packet into the buffer

      // the timestamp starts at byte 40 of the received packet and is four bytes,
      // or two words, long. First, extract the two words:

      unsigned long highWord = word ( packetBuffer[40], packetBuffer[41] );
      unsigned long lowWord = word ( packetBuffer[42], packetBuffer[43] );
      // combine the four bytes (two words) into a long integer
      // this is NTP time (seconds since Jan 1 1900):
      unsigned long secsSince1900 = highWord << 16 | lowWord;
      Serial.print ( "Seconds since Jan 1 1900 = " );
      Serial.println ( secsSince1900 );

      // now convert NTP time into everyday time:
      Serial.print ( "Unix time = " );
      // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
      const unsigned long seventyYears = 2208988800UL;
      // subtract seventy years:
      unsigned long epoch = secsSince1900 - seventyYears;
      // print Unix time:
      Serial.println ( epoch );


      // print the hour, minute and second:
      Serial.print ( "The UTC time is " );    // UTC is the time at Greenwich Meridian (GMT)
      Serial.print ( ( epoch  % 86400L ) / 3600 ); // print the hour (86400 equals secs per day)
      Serial.print ( ':' );
      if ( ( ( epoch % 3600 ) / 60 ) < 10 ) {
         // In the first 10 minutes of each hour, we'll want a leading '0'
         Serial.print ( '0' );
      }
      Serial.print ( ( epoch  % 3600 ) / 60 ); // print the minute (3600 equals secs per minute)
      Serial.print ( ':' );
      if ( ( epoch % 60 ) < 10 ) {
         // In the first 10 seconds of each minute, we'll want a leading '0'
         Serial.print ( '0' );
      }
      Serial.println ( epoch % 60 ); // print the second
   }
   // wait ten seconds before asking for the time again
   delay ( 10000 );
   Ethernet.maintain();
}

// send an NTP request to the time server at the given address
void sendNTPpacket ( const char * address ) {
   // set all bytes in the buffer to 0
   memset ( packetBuffer, 0, NTP_PACKET_SIZE );
   // Initialize values needed to form NTP request
   // (see URL above for details on the packets)
   packetBuffer[0] = 0b11100011;   // LI, Version, Mode
   packetBuffer[1] = 0;     // Stratum, or type of clock
   packetBuffer[2] = 6;     // Polling Interval
   packetBuffer[3] = 0xEC;  // Peer Clock Precision
   // 8 bytes of zero for Root Delay & Root Dispersion
   packetBuffer[12]  = 49;
   packetBuffer[13]  = 0x4E;
   packetBuffer[14]  = 49;
   packetBuffer[15]  = 52;

   // all NTP fields have been given values, now
   // you can send a packet requesting a timestamp:
   Udp.beginPacket ( address, 123 ); // NTP requests are to port 123
   Udp.write ( packetBuffer, NTP_PACKET_SIZE );
   Udp.endPacket();
}

... ed ottenuto questo sul monitor seriale:

Seconds since Jan 1 1900 = 3889758504
Unix time = 1680769704
The UTC time is 8:28:24
Seconds since Jan 1 1900 = 3889758515
Unix time = 1680769715
The UTC time is 8:28:35
Seconds since Jan 1 1900 = 3889758526
Unix time = 1680769726
The UTC time is 8:28:46
Seconds since Jan 1 1900 = 3889758537
Unix time = 1680769737
The UTC time is 8:28:57
Seconds since Jan 1 1900 = 3889758548
Unix time = 1680769748
The UTC time is 8:29:08
Seconds since Jan 1 1900 = 3889758560
Unix time = 1680769760
The UTC time is 8:29:20
Seconds since Jan 1 1900 = 3889758571
Unix time = 1680769771
The UTC time is 8:29:31
Seconds since Jan 1 1900 = 3889758582
Unix time = 1680769782
The UTC time is 8:29:42
Seconds since Jan 1 1900 = 3889758593
Unix time = 1680769793
The UTC time is 8:29:53
Seconds since Jan 1 1900 = 3889758604
Unix time = 1680769804
The UTC time is 8:30:04
Seconds since Jan 1 1900 = 3889758615
Unix time = 1680769815
The UTC time is 8:30:15

... quindi ... :roll_eyes:

Guglielmo

Quali sono i problemi hardware che potrebbero provocare questo problema?

Mah ... può essere di tutto ... schede guaste, schede infilate male (occhio hai pin del connettore ICSP), cavo ethernet, router a cui ti colleghi che non fa passare i pacchetti, e altri problemi che ora non mi vengono in mente, comunque ...

... come hai visto, una vecchia MEGA, un vecchio shield Ethernet e ha funzionato al primo colpo, quindi ... il problema non è nel codice ... :roll_eyes:

Guglielmo

Ok, il problema diventa ancora più complicato allora.
Grazie comunque :+1:t3:

Ok, ci hai provato, ma a fare cosa? Hai aperto sul tuo router la porta 8888 o hai aperto la 2390 (cambiandola anche nel codice)? Hai fatto passare la porta dalla rete esterna così com'è o hai fatto un Port Mapping? E hai cambiato il server NTP mettendo quello del pool italiano? O, giusto per vedere se hai problemi di DNS, anche direttamente l'IP di "time.nist.gov" ossia "128.138.141.172"?

Giusto per completezza, io ho un Fritz!Box 7583 e non ho fatto nulla ... è andato così al primo colpo ... come vedi nel codice, ho solo aggiunto, al suo programma, l'impostazione del pin 53 in OUTPUT e HIGH. :wink:

Guglielmo

A seguire i tuoi consigli.
Considera che con un ESP32 WiFi sono riuscito a farlo tranquillamente, quindi boh.
Il problema è che io ho il vincolo di dover usare per forza questo Arduino Mega 2560 + Ethernet 2 Shield (che a quanto pare sembra essere difettoso).