Skip to content

Instantly share code, notes, and snippets.

@ironlungx
Last active September 5, 2024 17:23
Show Gist options
  • Save ironlungx/4dea185a3c9c3b7759c52187eea06887 to your computer and use it in GitHub Desktop.
Save ironlungx/4dea185a3c9c3b7759c52187eea06887 to your computer and use it in GitHub Desktop.
Arduino ESP32 set external RTC time using NTP

The following program sets a RTC with NTP time

#include <WiFi.h>
#include <RTCLib.h>

#include "time.h"

const char *ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 0;
const int daylightOffset_sec = 3600;

RTC_DS3231 rtc;

void setup () {
 //
 // WiFi setup ommited
 //
 
 
 configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

 if (!rtc.begin()) {
   Serial.println("Couldn't find RTC");
   Serial.flush();
   while (1)
     delay(10);
 }
 
 struct tm timeinfo; 
 getLocalTime(&timeinfo);

 char buf[sizeof "2011-10-08T07:07:09Z"];
 strftime(buf, sizeof buf, "%FT%TZ", &timeinfo);

 rtc.adjust(buf); // Adjust the time using ISO8601
}

void loop () {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment