Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This sketch will set your ESP32 RTC using an NTP server
- * The "time_t" NTP functions are now part of the ESP32 WiFi library.
- *
- * The "ESP32Time.h" library is used to set the ESP32's RTC from the NTP UNIX time update
- * Once the RTC has been set all Serial Monitor Clock Print's are
- * generated from the ESP32's RTC.
- *
- * In it's current form the sketch has been configured to print a time stamp every second
- * and then resync to NTP on the hour change
- *
- * List of TZ strings here <https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv>
- * Time print formatting options <https://cplusplus.com/reference/ctime/strftime/>
- *
- */
- #define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3" //NZST/NZDT UTC +12/+13
- #include <WiFi.h>
- #include <ESP32Time.h>
- ESP32Time rtc;
- time_t now;
- const char ssid[] = "Your_SSID";
- const char password[] = "Your_Password";
- const int32_t DEFAULT_TIME = 1609459200; //1st Jan 2021 00:00:00
- int lastHour, lastSecond;
- void NTPupdate(void){
- volatile int32_t epoch = 0;
- Serial.println("\nConnecting to WiFi.....");
- WiFi.begin(ssid, password);
- WiFi.setAutoReconnect(false);
- while(WiFi.status() != WL_CONNECTED);
- Serial.print("IP address: ");Serial.println(WiFi.localIP());
- Serial.println("WiFi Connected.....");
- Serial.println("Getting NTP Time Update");
- while(epoch < DEFAULT_TIME){ //Wait till the NTP server reponds
- epoch = time(&now); //Gets the current Unix time
- }
- rtc.setTime(epoch); //Sets RTC using UNIX Time (EPOCH)
- Serial.println(rtc.getTime("NTP Update Success!!.....\n%a %d-%B-%Y %T UTC: %z"));
- if(WiFi.status() == WL_CONNECTED){
- WiFi.disconnect(true, false);
- Serial.println("[WiFi] Disconnected from WiFi!!\n");
- }
- lastHour = rtc.getHour();
- lastSecond = rtc.getSecond();
- return;
- }
- void setup(void) {
- Serial.begin(115200);
- while(!Serial);
- configTime(0, 0, "pool.ntp.org", "time.nist.gov");
- setenv("TZ", TZ_INFO, 1); tzset();
- NTPupdate();
- }
- void loop(void) {
- if(lastSecond != rtc.getSecond()){ //When RTC second is 10, 30 or 50 a resync
- lastSecond = rtc.getSecond(); //with the time Server is actioned
- Serial.println(rtc.getTime("(%Z) Local Time %I:%M:%S (%p)")); //Creates our Clock
- if(lastHour != rtc.getHour()){
- NTPupdate();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement