Home

HTMA Week 11: Networking

Published: 2023-11-15

Getting Time

This week will remain fairly simple. For my final project, I am building a clock device, which means I need a way to retrieve the current time of day. While a more typical and lower level approach is to hook up an external oscillator to the device and use that to maintain a Real-Time Clock (RTC), the ESP32 development framework makes this process much easier. Following ESP’s Documentation, as long as the device is connected to the internet, we can make use of a Simple Network Time Protocol (SNTP) server to retrieve the current time from the internet and initialize our device with it, then display the correct time. Here’s my code snippet for retrieving time:

time_t now;
struct tm timeinfo;

setenv("TZ", "UTC-5", 1);
tzset();

esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
esp_netif_sntp_init(&config);
if (esp_netif_sntp_sync_wait(pdMS_TO_TICKS(10000)) != ESP_OK) {
    ESP_LOGE("NETIF SNTP", "Failed to update system time within 10s timeout");
}
while (1)
{
  time(&now);
  localtime_r(&now, &timeinfo);
  digits_to_display[0] = timeinfo.tm_min / 10;
  digits_to_display[1] = timeinfo.tm_min % 10;
  digits_to_display[2] = timeinfo.tm_sec / 10;
  digits_to_display[3] = timeinfo.tm_sec % 10;
  vTaskDelay(100); 
}

Source Files

Code Repository

Bowen Wu