### Full Demo of GyverNTP Usage (C++) Source: https://github.com/gyverlibs/gyverntp/blob/main/README.md This snippet provides a complete example demonstrating how to initialize and use the GyverNTP library on an Arduino-compatible board. It includes connecting to WiFi, setting up handlers for errors and second ticks, starting the NTP client with a specified timezone, and showing various ways to access and compare time data within the loop. ```C++ #include #include void setup() { Serial.begin(115200); WiFi.begin("WIFI_SSID", "WIFI_PASS"); while (WiFi.status() != WL_CONNECTED) delay(100); Serial.println("Connected"); // обработчик ошибок NTP.onError([]() { Serial.println(NTP.readError()); Serial.print("online: "); Serial.println(NTP.online()); }); // обработчик секунды (вызывается из тикера) NTP.onSecond([]() { Serial.println("new second!"); }); // обработчик синхронизации (вызывается из sync) // NTP.onSync([](uint32_t unix) { // Serial.println("sync: "); // Serial.print(unix); // }); NTP.begin(3); // запустить и указать часовой пояс // NTP.setPeriod(30); // период синхронизации в секундах // NTP.setHost("ntp1.stratum2.ru"); // установить другой хост // NTP.setHost(IPAddress(1, 2, 3, 4)); // установить другой хост // NTP.asyncMode(false); // выключить асинхронный режим // NTP.ignorePing(true); // не учитывать пинг до сервера // NTP.updateNow(); // обновить прямо сейчас } void loop() { // тикер вернёт true каждую секунду в 0 мс секунды, если время синхронизировано if (NTP.tick()) { // вывод даты и времени строкой Serial.print(NTP.toString()); // NTP.timeToString(), NTP.dateToString() Serial.print(':'); Serial.println(NTP.ms()); // + миллисекунды текущей секунды. Внутри tick всегда равно 0 // вывод в Datime Datime dt = NTP; // или Datime dt(NTP) dt.year; dt.second; dt.hour; dt.weekDay; dt.yearDay; // ... и прочие методы и переменные Datime // чтение напрямую, медленнее чем вывод в Datime NTP.second(); NTP.minute(); NTP.year(); // ... и прочие методы StampConvert // сравнение NTP == DaySeconds(12, 35, 0); // сравнение с DaySeconds (время равно 12:35:00) NTP == 1738237474; // сравнение с unix NTP == Datime(2025, 1, 30, 14, 14, 30); // сравнение с Datime } if (NTP.newSecond()) { // новую секунду можно поймать и здесь } // изменился онлайн-статус if (NTP.statusChanged()) { Serial.print("STATUS: "); Serial.println(NTP.online()); } } ``` -------------------------------- ### Using Gyverntp Methods C++ Source: https://github.com/gyverlibs/gyverntp/blob/main/README_EN.md Provides a comprehensive list of the public methods available in the Gyverntp library for starting/stopping synchronization, configuring settings, retrieving various time components, getting formatted date/time strings, and checking the synchronization status and server ping. ```C++ Bool Begin ();// Launch VOID end ();// Stop VOID Setgmtminute (Int16_T GMT);// Install an hourly belt in minutes VOID Setgmt (Int8_T GMT);// Install an hourly waist in the watch VOID Setperiod (Uint16_T PRD);// set the update period in seconds VOID Sethost (Char* Host);// Install the host (by default "" Pool.ntp.org ") Void asyncmode (Bool F);// asynchronous regime (on the silence, turned on, true) VOID ignoreping (bool f);// Do not take into account the ping of the connection (silence. FALSE) uint8_t tick ();// Tiker, updates the time by its timer.Will return True if there is an attempt to update uint8_t updatatenow ();// Manually request and update the time from the server.Will return the status (see below) uint32_t unix ();// Unix Time uint16_t ms ();// milliseconds of the current second uint8_t second ();// Get second uint8_t minute ();// Get minutes uint8_t hor ();// Get a clock uint8_t day ();// Get the day of the month uint8_t month ();// Get a month uint16_t year ();// Get a year uint8_t Dayweek ();// Get the day of the week (Mon .. BC = 1 .. 7) String Timestring ();// Get a line of time of the format of hhch: mm: ss String Datestring ();// Get the line of the date of the format DD.MM.YYYY Bool Synced ();// Get the status of the current time, True - synchronized Bool Busy ();// will return True if Tick expects a server response in asynchronous mode int16_t ping ();// Get server ping uint8_t status ();// Get the status of the system // 0 - everything is ok // 1 - not launched UDP // 2 - not connected to wifi // 3 - error error to the server // 4 - error sending a package // 5 - server response timeout // 6 - the incorrect server response was obtained ``` -------------------------------- ### Integrating GyverNTP with RTC (C++) Source: https://github.com/gyverlibs/gyverntp/blob/main/README.md This example shows how to connect the GyverNTP library to an external RTC module to provide time synchronization. It demonstrates attaching a GyverDS3231Min RTC and also includes a template for creating a custom `VirtualRTC` class to integrate with other RTC hardware by implementing `setUnix` and `getUnix` methods. ```C++ #include #include // GyverDS3231 поддерживает работу с GyverNTP #include GyverDS3231Min rtc; // можно написать свой класс и использовать любой другой RTC class RTC : public VirtualRTC { public: void setUnix(uint32_t unix) { Serial.print("SET RTC: "); Serial.println(unix); } uint32_t getUnix() { return 1738015299ul; } }; RTC vrtc; void setup() { Serial.begin(115200); WiFi.begin("WIFI_SSID", "WIFI_PASS"); // while (WiFi.status() != WL_CONNECTED) delay(100); Serial.println("Connected"); // GyverDS3231 Wire.begin(); rtc.begin(); NTP.begin(3); // запустить и указать часовой пояс // подключить RTC // NTP.attachRTC(vrtc); NTP.attachRTC(rtc); } void loop() { if (NTP.tick()) { Serial.println(NTP.toString()); } } ``` -------------------------------- ### Synchronizing Time and Blinking LED with GyverNTP (C++) Source: https://github.com/gyverlibs/gyverntp/blob/main/README_EN.md This example demonstrates connecting an ESP8266 to WiFi, initializing the GyverNTP library, and using it to fetch time from an NTP server. It periodically updates the time using `ntp.tick()` and triggers actions based on the millisecond value, specifically blinking the built-in LED and printing the current time and date strings twice per second. Requires WiFi credentials and the GyverNTP library. ```C++ // An example takes time every second // And also twice a second flashes LED // can be flashed on several boards - they will blink synchronously #include // ESP8266 //#include // ESP32 #include Gyverntp NTP (3); // List of servers if "Pool.ntp.org" does not work //"ontp1.stratum2.ru " //"ontp2.stratum2.ru " //"ontp.msk-ig.ru " VOID setup () { Pinmode (LED_BUILTIN, OUTPUT); Serial.Begin (115200); Wifi.begin ("wifi_ssid", "wifi_pass"); While (wifi.status ()! = Wl_ConNECTED) DELAY (100); Serial.println ("connected"); ntp.begin (); //NTP.ASYNCMODE(False);// turn off the asynchronous regime //ntp.ignoreping(true);// not to take into account the ping before the server } VOID loop () { ntp.tick (); if (ntp.ms () == 0) { DELAY (1); digitalWrite (LED_BUILTIN, 1); } if (ntp.ms () == 500) { DELAY (1); digitalWrite (LED_BUILTIN, 0); Serial.println (ntp.timestring ()); Serial.println (ntp.datestestring ()); Serial.println (); } } ``` -------------------------------- ### Initializing Gyverntp C++ Source: https://github.com/gyverlibs/gyverntp/blob/main/README_EN.md Demonstrates different ways to initialize the Gyverntp object, allowing configuration of the GMT offset and the time synchronization update period. ```C++ Gyverntp NTP;// default parameters (GMT 0, period 3600 seconds (1 hour)) Gyverntp NTP (GMT);// hourly belt in watches (for example, Moscow 3) Gyverntp NTP (GMT, Period);// Tax belt in the clock and the renewal period in seconds ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.