Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set system time #23

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions NTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
*/

#include "NTP.h"
#include <time.h>

NTP::NTP(UDP& udp) {
this->udp = &udp;
Expand Down Expand Up @@ -104,6 +105,11 @@ bool NTP::ntpUpdate() {
}
else return false;
#endif

// set the hardware clock to UTC
timeval tv = { epoch(), 0 };
settimeofday(&tv, nullptr);

return true;
}

Expand Down
46 changes: 46 additions & 0 deletions examples/CheckSystemClock/CheckSystemClock.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// example for WIFI based boards like ESP8266, ESP32, Nano RP2040 Connect, WiFi 101 shield or MKR1000

#include "Arduino.h"
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield or ESP32
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
//#include <WiFiNINA.h> // for e.g. Nano RP2040 Connect
#include "WiFiUdp.h" // not needed for WiFiNINA
#include "NTP.h"

char ssid[] = "yourSSID";
char password[] = "yourPASSWORD";

WiFiUDP wifiUdp;
NTP ntp(wifiUdp);

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting ...");
delay(500);
}
Serial.println("Connected");
ntp.ruleDST("CEST", Last, Sun, Mar, 2, 120); // last sunday in march 2:00, timetone +120min (+1 GMT + 1h summertime offset)
ntp.ruleSTD("CET", Last, Sun, Oct, 3, 60); // last sunday in october 3:00, timezone +60min (+1 GMT)
ntp.begin();
Serial.println("start NTP");
}

void loop() {
ntp.update();
Serial.println(ntp.formattedTime("%d. %B %Y")); // dd. Mmm yyyy
Serial.println(ntp.formattedTime("%A %T")); // Www hh:mm:ss

// Because the system clock was updated we can use the standard time() function to obtain UTC time.
time_t now = time(NULL);
char *systemtime = (char *)"System Clock Not Set";
if (now > 3600)
systemtime = ctime(&now);
Serial.print("System Clock (UTC): ");
Serial.println(systemtime);

delay(1000);
}