Skip to content

Instantly share code, notes, and snippets.

@CelliesProjects
Created March 31, 2021 19:43
Show Gist options
  • Save CelliesProjects/d275de06983074dbd5192f7c9ef0d360 to your computer and use it in GitHub Desktop.
Save CelliesProjects/d275de06983074dbd5192f7c9ef0d360 to your computer and use it in GitHub Desktop.
#include <WiFi.h>
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#
// https://github.com/espressif/esp-idf/blob/master/examples/protocols/sntp/main/sntp_example_main.c
const char* WIFI_NETWORK = "xxx";
const char* WIFI_PASSWORD = "xxx";
const char* NTP_POOL = "nl.pool.ntp.org";
const char* TIMEZONE = "CET-1CEST,M3.5.0/2,M10.5.0/3"; /* Central European Time - see http://www.remotemonitoringsystems.ca/time-zone-abbreviations.php */
void print_time(struct timeval *tv)
{
struct tm localTime;
localtime_r(&tv->tv_sec, &localTime);
// https://www.cplusplus.com/reference/ctime/strftime/
char strftime_buf[64];
strftime(strftime_buf, sizeof(strftime_buf), "%T", &localTime);
ESP_LOGI(TAG, "ntp sync at %s:%i", strftime_buf, tv->tv_usec);
}
void setup() {
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
WiFi.setSleep(false);
while (!WiFi.isConnected())
delay(10);
ESP_LOGI(TAG, "connected to '%s' as %s - syncing NTP", WIFI_NETWORK, WiFi.localIP().toString().c_str());
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html
/* set a callback function on ntp sync */
sntp_set_time_sync_notification_cb(print_time);
/* sync the clock with ntp */
configTzTime(TIMEZONE, NTP_POOL);
}
void loop() {
//struct timeval tv_now;
//gettimeofday(&tv_now, NULL);
//print_time(&tv_now);
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment