Notifications
Clear all

[Solved] NTP sync *interval* does not work?


wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  

I'm a bit ashamed for my lack of understanding of the whole Arduino 'time' concept so I try to use examples to get it working.
It does work except it does not sync time every 'set' time.

I saw one can use setSyncProvider and setSyncInterval OR the method I now tried when calling the NTPClient object:

NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 10000);

But in both cases the time will set once and then no updates?

These are the libraries I use:

[env:nano_33_iot]
platform = atmelsam
board = nano_33_iot
framework = arduino
lib_deps =
arduino-libraries/WiFiNINA@^1.8.13
arduino-libraries/NTPClient@^3.1.0
paulstoffregen/Time@^1.6.1
jchristensen/Timezone@^1.2.4
bxparks/AceButton@^1.9.1
mprograms/SimpleRotary@^1.1.2
bodmer/TFT_eSPI@^2.3.73

 

Here's my sketch, note the large ascii art text headers but it's easier to navigate when using PlatformIO that way 😉

Thanks for any help!

 

#include 
// Wifi
#include 
#include 
// Includes for Time
#include 
#include 
#include 
//#include "timeRules.h"
//
#include 

//Wifi
int status = WL_AP_CONNECTED;

#include "wifi_secrets.h"
char ssid[] = WIFI_SSID;     // your network SSID (name)
char pass[] = WIFI_PASSWORD; // your network password (use for WPA, or use as key for WEP)

// A UDP instance to let us send and receive packets over UDP
// Wifi Objects
WiFiUDP ntpUDP;

// Time Objects
//NTPClient timeClient(ntpUDP);
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 10000);

// Loop timer
unsigned long loop_interval = 1000L;
unsigned long main_prev_millis = 0;

//  8888888b.                    888 8888888888
//  888  "Y88b                   888 888
//  888    888                   888 888
//  888    888  .d88b.   .d8888b 888 8888888 888  888 88888b.   .d8888b
//  888    888 d8P  Y8b d88P"    888 888     888  888 888 "88b d88P"
//  888    888 88888888 888      888 888     888  888 888  888 888
//  888  .d88P Y8b.     Y88b.    888 888     Y88b 888 888  888 Y88b.
//  8888888P"   "Y8888   "Y8888P 888 888      "Y88888 888  888  "Y8888P
//
//
// declare functions. In the Arduino IDE this is done also
// but in the background.
void printWifiStatus();
void wifiStatus();
void wifiConnect();
time_t syncNTPTime();

//   .d8888b.           888                        .d88   88b.
//  d88P  Y88b          888                       d88P"   "Y88b
//  Y88b.               888                      d88P       Y88b
//   "Y888b.    .d88b.  888888 888  888 88888b.  888         888
//      "Y88b. d8P  Y8b 888    888  888 888 "88b 888         888
//        "888 88888888 888    888  888 888  888 Y88b       d88P
//  Y88b  d88P Y8b.     Y88b.  Y88b 888 888 d88P  Y88b.   .d88P
//   "Y8888P"   "Y8888   "Y888  "Y88888 88888P"    "Y88   88P"
//                                      888
//                                      888
//                                      888

void setup()
{

  // Open serial communications and wait for port to open:
  delay(2000);

  Serial.begin(115200);
  Serial.println(F("setup(): begin"));

  // Wifi
  wifiConnect();
  wifiStatus();

  // Time Setup
  timeClient.begin(0);
  syncNTPTime();

  // End of Setup
  Serial.println(F("setup(): ready"));
}

//  888                                  .d88   88b.
//  888                                 d88P"   "Y88b
//  888                                d88P       Y88b
//  888      .d88b.   .d88b.  88888b.  888         888
//  888     d88""88b d88""88b 888 "88b 888         888
//  888     888  888 888  888 888  888 Y88b       d88P
//  888     Y88..88P Y88..88P 888 d88P  Y88b.   .d88P
//  88888888 "Y88P"   "Y88P"  88888P"    "Y88   88P"
//                            888
//                            888
//                            888

void loop()
{

  //===> MAIN TIMER <=========================================================
  unsigned long main_current_millis = millis();
  if (main_current_millis - main_prev_millis >= 1000)
  {
    main_prev_millis = main_current_millis;
    // run everything here that needs to happen on
    // 1 second timer
    Serial.print(".");
  }
}

//  8888888b.          888    888       888 d8b  .d888 d8b  .d8888b.  888
//  888   Y88b         888    888   o   888 Y8P d88P"  Y8P d88P  Y88b 888
//  888    888         888    888  d8b  888     888        Y88b.      888
//  888   d88P 888d888 888888 888 d888b 888 888 888888 888  "Y888b.   888888
//  8888888P"  888P"   888    888d88888b888 888 888    888     "Y88b. 888
//  888        888     888    88888P Y88888 888 888    888       "888 888
//  888        888     Y88b.  8888P   Y8888 888 888    888 Y88b  d88P Y88b.
//  888        888      "Y888 888P     Y888 888 888    888  "Y8888P"   "Y888
//
//
//
void printWifiStatus()
{
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  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");
}

//  888       888 d8b  .d888 d8b  .d8888b.                                               888
//  888   o   888 Y8P d88P"  Y8P d88P  Y88b                                              888
//  888  d8b  888     888        888    888                                              888
//  888 d888b 888 888 888888 888 888         .d88b.  88888b.  88888b.   .d88b.   .d8888b 888888
//  888d88888b888 888 888    888 888        d88""88b 888 "88b 888 "88b d8P  Y8b d88P"    888
//  88888P Y88888 888 888    888 888    888 888  888 888  888 888  888 88888888 888      888
//  8888P   Y8888 888 888    888 Y88b  d88P Y88..88P 888  888 888  888 Y8b.     Y88b.    Y88b.
//  888P     Y888 888 888    888  "Y8888P"   "Y88P"  888  888 888  888  "Y8888   "Y8888P  "Y888
//
//
//
void wifiConnect()
{
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE)
  {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true)
      ;
  }

  String firmwareCurrent = WiFi.firmwareVersion();
  String firmwareLatest = WIFI_FIRMWARE_LATEST_VERSION;

  Serial.println("Current Wifi firmware: " + firmwareCurrent);
  Serial.println("Latest Wifi firmware:  " + firmwareLatest);

  if (firmwareCurrent < firmwareLatest)
  {
    Serial.println(" Please upgrade the firmware ");
  }

  // attempt to connect to Wifi network:
  while (status != 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:
    status = WiFi.begin(ssid, pass);
  }
}

//  888       888 d8b  .d888 d8b  .d8888b.  888             888
//  888   o   888 Y8P d88P"  Y8P d88P  Y88b 888             888
//  888  d8b  888     888        Y88b.      888             888
//  888 d888b 888 888 888888 888  "Y888b.   888888  8888b.  888888 888  888 .d8888b
//  888d88888b888 888 888    888     "Y88b. 888        "88b 888    888  888 88K
//  88888P Y88888 888 888    888       "888 888    .d888888 888    888  888 "Y8888b.
//  8888P   Y8888 888 888    888 Y88b  d88P Y88b.  888  888 Y88b.  Y88b 888      X88
//  888P     Y888 888 888    888  "Y8888P"   "Y888 "Y888888  "Y888  "Y88888  88888P'
//
//
//
void wifiStatus()
{
  Serial.println("Connected to wifi");
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  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");
}

//                                      888b    888 88888888888 8888888b.
//                                      8888b   888     888     888   Y88b
//                                      88888b  888     888     888    888
//  .d8888b  888  888 88888b.   .d8888b 888Y88b 888     888     888   d88P
//  88K      888  888 888 "88b d88P"    888 Y88b888     888     8888888P"
//  "Y8888b. 888  888 888  888 888      888  Y88888     888     888
//       X88 Y88b 888 888  888 Y88b.    888   Y8888     888     888
//   88888P'  "Y88888 888  888  "Y8888P 888    Y888     888     888
//                888
//           Y8b d88P
//            "Y88P"
// syncNTPTime();
// Called as a callback on a timer every sync_time seconds.
time_t syncNTPTime()
{
  unsigned long cur_time, update_time;
  unsigned int drift_time;
  cur_time = timeClient.getEpochTime();
  timeClient.update();
  update_time = timeClient.getEpochTime();
  drift_time = (update_time - cur_time);
  Serial.println("NTP Time Sync <=====================================");
  Serial.print("NTP Epoch: ");
  Serial.println(timeClient.getEpochTime());
  Serial.print("NTP Time : ");
  Serial.println(timeClient.getFormattedTime());
  Serial.print("Epoch Pre Sync:  ");
  Serial.println(cur_time);
  Serial.print("Epoch Post Sync: ");
  Serial.println(update_time);
  Serial.print("Drift Correct:   ");
  Serial.println(drift_time);

  return timeClient.getEpochTime();
}

 


Quote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 

@wwjd777

This may be a stupid question, but what do you expect to happen when you run this ?

Your main loop appears to just look for 1000 millis or more to elapse and then celebrates that event by printing a dot, resetting to the last millis and then starting over.


ReplyQuote
wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  

@will 

yes it seems stupid but I did expect to see on the Serial Monitor the output when the sync function is called

so I expected to see this every x seconds:

NTP Time Sync <=====================================
NTP Epoch: 1638472314
NTP Time : 1954
Epoch Pre Sync: 3605
Epoch Post Sync: 1638472314
Drift Correct: 1638468709

This output is after startup but after that no resync:

setup(): begin
Current Wifi firmware: 1.4.8
Latest Wifi firmware: 1.4.8
Attempting to connect to SSID: JezusHoudVanJe!
Connected to wifi
SSID: JezusHoudVanJe!
IP Address: 192.168.178.92
signal strength (RSSI):-52 dBm
NTP Time Sync <=====================================
NTP Epoch: 1638472314
NTP Time : 1954
Epoch Pre Sync: 3605
Epoch Post Sync: 1638472314
Drift Correct: 1638468709
setup(): ready
.........
--- exit ---


ReplyQuote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 

@wwjd777 

Sorry to be obtuse, what "synch function" and when/where is it called ?

If you mean synchNTPTime, it's called in setup() so it does appear once on the serial monitor, but it's not explicitly called anywhere else in your code.


wwjd777 liked
ReplyQuote
wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  

As I understand it, the line below has extra arguments of which the last one is the 'sync' parameter in seconds.

NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 10);

But I think it's best to start all over and look for a better example to work from. 
I don't want to waste your or anybody's time..

Thank you and if I succeed I will post is here so others may benfit

 


ReplyQuote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 

@wwjd777 

Ah, OK. So that is supposed to reinvoke the synch routine every 10 seconds (presumably); but how is it told which of your routines to call ? 


ReplyQuote
wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  

I AGAIN feel stupid!!  It seems that the example I copied has functions mixed up big-time.

I was so overwhelmed after the last 6 hours trying to get one step forward.

 

I was expecting to see the output of the time_t syncNTPTime() function on the serial monitor

But the NTPClient.cpp has it's own NTP calling function

So this is now how is FINALLY works:

in setup:

void setup()
{

  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  Serial.println(F("setup(): begin"));

  // Wifi
  wifiConnect();
  wifiStatus();

  // Time Setup
  timeClient.begin();
  timeClient.setUpdateInterval(10000L);
  timeClient.setTimeOffset(3600);

  // End of Setup
  Serial.println(F("setup(): ready"));
}

in the LOOP:

void loop()
{

  //===> MAIN TIMER <=========================================================
  unsigned long main_current_millis = millis();
  if (main_current_millis - main_prev_millis >= 1000)
  {
    main_prev_millis = main_current_millis;
    // run everything here that needs to happen on

    // Time keeping:
    // timeClient.update() has to be called in the loop. It will check if the
    // every 'setUpdateInterval time' has passed and then get a NTP update
    timeClient.update();
    // just print formatted time
    Serial.println(timeClient.getFormattedTime());
  }
}

 

whole sketch working now:

#include <Arduino.h>
// Wifi
#include <WiFiNINA.h>
#include <WiFiUdp.h>
// Includes for Time
#include <NTPClient.h>
#include <TimeLib.h>
#include <Timezone.h>
//#include "timeRules.h"
//
#include <SPI.h>

//Wifi
int status = WL_AP_CONNECTED;

#include "wifi_secrets.h"
char ssid[] = WIFI_SSID;     // your network SSID (name)
char pass[] = WIFI_PASSWORD; // your network password (use for WPA, or use as key for WEP)

// A UDP instance to let us send and receive packets over UDP
// Wifi Objects
WiFiUDP ntpUDP;

// Time Objects
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org");


// Loop timer
unsigned long loop_interval = 1000L;
unsigned long main_prev_millis = 0;

//  8888888b.                    888 8888888888
//  888  "Y88b                   888 888
//  888    888                   888 888
//  888    888  .d88b.   .d8888b 888 8888888 888  888 88888b.   .d8888b
//  888    888 d8P  Y8b d88P"    888 888     888  888 888 "88b d88P"
//  888    888 88888888 888      888 888     888  888 888  888 888
//  888  .d88P Y8b.     Y88b.    888 888     Y88b 888 888  888 Y88b.
//  8888888P"   "Y8888   "Y8888P 888 888      "Y88888 888  888  "Y8888P
//
//
// declare functions. In the Arduino IDE this is done also
// but in the background.
void printWifiStatus();
void wifiStatus();
void wifiConnect();

//   .d8888b.           888                        .d88   88b.
//  d88P  Y88b          888                       d88P"   "Y88b
//  Y88b.               888                      d88P       Y88b
//   "Y888b.    .d88b.  888888 888  888 88888b.  888         888
//      "Y88b. d8P  Y8b 888    888  888 888 "88b 888         888
//        "888 88888888 888    888  888 888  888 Y88b       d88P
//  Y88b  d88P Y8b.     Y88b.  Y88b 888 888 d88P  Y88b.   .d88P
//   "Y8888P"   "Y8888   "Y888  "Y88888 88888P"    "Y88   88P"
//                                      888
//                                      888
//                                      888

void setup()
{

  // Open serial communications and wait for port to open:
  delay(2000);

  Serial.begin(115200);
  Serial.println(F("setup(): begin"));

  // Wifi
  wifiConnect();
  wifiStatus();

  // Time Setup
  timeClient.begin();
  timeClient.setUpdateInterval(10000L);
  timeClient.setTimeOffset(3600);

  // End of Setup
  Serial.println(F("setup(): ready"));
}

//  888                                  .d88   88b.
//  888                                 d88P"   "Y88b
//  888                                d88P       Y88b
//  888      .d88b.   .d88b.  88888b.  888         888
//  888     d88""88b d88""88b 888 "88b 888         888
//  888     888  888 888  888 888  888 Y88b       d88P
//  888     Y88..88P Y88..88P 888 d88P  Y88b.   .d88P
//  88888888 "Y88P"   "Y88P"  88888P"    "Y88   88P"
//                            888
//                            888
//                            888

void loop()
{

  //===> MAIN TIMER <=========================================================
  unsigned long main_current_millis = millis();
  if (main_current_millis - main_prev_millis >= 1000)
  {
    main_prev_millis = main_current_millis;
    // run everything here that needs to happen on

    // Time keeping:
    // timeClient.update() has to be called in the loop. It will check if the
    // every 'setUpdateInterval time' has passed and then get a NTP update
    timeClient.update();
    // just print formatted time
    Serial.println(timeClient.getFormattedTime());
  }
}

//  8888888b.          888    888       888 d8b  .d888 d8b  .d8888b.  888
//  888   Y88b         888    888   o   888 Y8P d88P"  Y8P d88P  Y88b 888
//  888    888         888    888  d8b  888     888        Y88b.      888
//  888   d88P 888d888 888888 888 d888b 888 888 888888 888  "Y888b.   888888
//  8888888P"  888P"   888    888d88888b888 888 888    888     "Y88b. 888
//  888        888     888    88888P Y88888 888 888    888       "888 888
//  888        888     Y88b.  8888P   Y8888 888 888    888 Y88b  d88P Y88b.
//  888        888      "Y888 888P     Y888 888 888    888  "Y8888P"   "Y888
//
//
//
void printWifiStatus()
{
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  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");
}

//  888       888 d8b  .d888 d8b  .d8888b.                                               888
//  888   o   888 Y8P d88P"  Y8P d88P  Y88b                                              888
//  888  d8b  888     888        888    888                                              888
//  888 d888b 888 888 888888 888 888         .d88b.  88888b.  88888b.   .d88b.   .d8888b 888888
//  888d88888b888 888 888    888 888        d88""88b 888 "88b 888 "88b d8P  Y8b d88P"    888
//  88888P Y88888 888 888    888 888    888 888  888 888  888 888  888 88888888 888      888
//  8888P   Y8888 888 888    888 Y88b  d88P Y88..88P 888  888 888  888 Y8b.     Y88b.    Y88b.
//  888P     Y888 888 888    888  "Y8888P"   "Y88P"  888  888 888  888  "Y8888   "Y8888P  "Y888
//
//
//
void wifiConnect()
{
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE)
  {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true)
      ;
  }

  String firmwareCurrent = WiFi.firmwareVersion();
  String firmwareLatest = WIFI_FIRMWARE_LATEST_VERSION;

  Serial.println("Current Wifi firmware: " + firmwareCurrent);
  Serial.println("Latest Wifi firmware:  " + firmwareLatest);

  if (firmwareCurrent < firmwareLatest)
  {
    Serial.println(" Please upgrade the firmware ");
  }

  // attempt to connect to Wifi network:
  while (status != 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:
    status = WiFi.begin(ssid, pass);
  }
}

//  888       888 d8b  .d888 d8b  .d8888b.  888             888
//  888   o   888 Y8P d88P"  Y8P d88P  Y88b 888             888
//  888  d8b  888     888        Y88b.      888             888
//  888 d888b 888 888 888888 888  "Y888b.   888888  8888b.  888888 888  888 .d8888b
//  888d88888b888 888 888    888     "Y88b. 888        "88b 888    888  888 88K
//  88888P Y88888 888 888    888       "888 888    .d888888 888    888  888 "Y8888b.
//  8888P   Y8888 888 888    888 Y88b  d88P Y88b.  888  888 Y88b.  Y88b 888      X88
//  888P     Y888 888 888    888  "Y8888P"   "Y888 "Y888888  "Y888  "Y88888  88888P'
//
//
//
void wifiStatus()
{
  Serial.println("Connected to wifi");
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  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();
  timeClient.update();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


ReplyQuote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 

@wwjd777 

Glad it's working now.

No need to feel stupid, making mistakes and investigating them is how you learn things; I've found that I rarely learned anything by getting it right the first time. It's when you have to delve deeply into it that you really learn how it works by starting from how it doesn't work.

So now we've BOTH learned something 🙂


wwjd777 liked
ReplyQuote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 

@wwjd777 

By the way, you should check whether the update() function should only be called when you're interested (i.e. after each second) or every time through the loop.

Many classes require frequent calls because they're operating on some internal timing mechanism and so they require frequent calls to ensure proper operation.


wwjd777 liked
ReplyQuote
wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  
Posted by: @will

@wwjd777 

By the way, you should check whether the update() function should only be called when you're interested (i.e. after each second) or every time through the loop.

Many classes require frequent calls because they're operating on some internal timing mechanism and so they require frequent calls to ensure proper operation.

That is a very good point.  I checked and the update function must be checked frequently as it checks if the setUpdateInterval() time has passed. (I don't have the library code snippet here, I'm on another pc)

Yes I learned a lot by making many mistakes... The 'bat' on your Avatar has made the difference I think, made me look harder. 😉   thank you for your understanding!

 


ReplyQuote
Will
 Will
(@will)
Noble Member
Joined: 7 months ago
Posts: 1084
 
Posted by: @wwjd777

The 'bat' on your Avatar has made the difference I think, made me look harder. 😉

🙂


ReplyQuote
wwjd777
(@wwjd777)
Eminent Member
Joined: 2 months ago
Posts: 27
Topic starter  

To finish this post I want to show the other method of NTP Sync via the Time library.
(previous working example was using the NTPClient library)

I really appreciated the help from 'Will-with-the-daunting-bat', thank you!

 

So... I learned the hard way that copying a "working" example is not always a good idea.  I now is apparent that the code I copied to work from was mixing up two different methods of NTP time sync.

I was expecting the Serial output shown below, every 10 seconds a NTP update:

Transmit NTP Request
us.pool.ntp.org: 108.61.73.244
Receive NTP Response
1016 3.12.2021
1017 3.12.2021
1018 3.12.2021
1019 3.12.2021
1020 3.12.2021
1021 3.12.2021
1022 3.12.2021
1023 3.12.2021
1024 3.12.2021
1025 3.12.2021
Transmit NTP Request
us.pool.ntp.org: 108.61.73.244
Receive NTP Response
1027 3.12.2021
1028 3.12.2021
1029 3.12.2021
1030 3.12.2021
1031 3.12.2021
1032 3.12.2021

This is the 2nd -working- sketch, in this case using an Arduino Nano 33 IoT:

/*
 * TimeNTP_ESP8266WiFi.ino
 * Example showing time sync to NTP time source
 *
 */

#include <Arduino.h>
// Wifi
#include <WiFiNINA.h>
#include <WiFiUdp.h>
// Includes for Time
#include <NTPClient.h>
#include <TimeLib.h>
#include <Timezone.h>
//#include "timeRules.h"
//
#include <SPI.h>

//Wifi
int status = WL_AP_CONNECTED;

#include "wifi_secrets.h"
char ssid[] = WIFI_SSID;     // your network SSID (name)
char pass[] = WIFI_PASSWORD; // your network password (use for WPA, or use as key for WEP)

// NTP Servers:
static const char ntpServerName[] = "us.pool.ntp.org";
//static const char ntpServerName[] = "time.nist.gov";
//static const char ntpServerName[] = "time-a.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-b.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-c.timefreq.bldrdoc.gov";

const int timeZone = 1; // Central European Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)

WiFiUDP ntpUDP;

time_t getNtpTime();
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);

void setup()
{
  Serial.begin(9600);
  while (!Serial)
    ; // Needed for Leonardo only
  delay(250);
  Serial.println("TimeNTP Example");
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.print("IP number assigned by DHCP is ");
  Serial.println(WiFi.localIP());
  Serial.println("Starting UDP");
  ntpUDP.begin(0);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  setSyncInterval(10);
}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{
  if (timeStatus() != timeNotSet)
  {
    if (now() != prevDisplay)
    { //update the display only if time has changed
      prevDisplay = now();
      digitalClockDisplay();
    }
  }
}

void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(".");
  Serial.print(month());
  Serial.print(".");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits)
{
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int ntpPacketSize = 48;     // NTP time is in the first 48 bytes of message
byte packetBuffer[ntpPacketSize]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  IPAddress ntpServerIP; // NTP server's ip address

  while (ntpUDP.parsePacket() > 0)
    ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  // get a random server from the pool
  WiFi.hostByName(ntpServerName, ntpServerIP);
  Serial.print(ntpServerName);
  Serial.print(": ");
  Serial.println(ntpServerIP);
  sendNTPpacket(ntpServerIP);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500)
  {
    int size = ntpUDP.parsePacket();
    if (size >= ntpPacketSize)
    {
      Serial.println("Receive NTP Response");
      ntpUDP.read(packetBuffer, ntpPacketSize); // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 = (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, ntpPacketSize);
  // 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:
  ntpUDP.beginPacket(address, 123); //NTP requests are to port 123
  ntpUDP.write(packetBuffer, ntpPacketSize);
  ntpUDP.endPacket();
}

 

 


ReplyQuote