Getting Started with ESP32 and Arduino (Part 3): Connecting to WiFi and Retrieving Current Time

The ESP32 has a built-in WiFi module, making it very simple and convenient to connect to WiFi.

The code is as follows:

#include <WiFi.h>

const char* ssid = "WIFI_NAME";
const char* password = "WIFI_PASSWORD";

void setup()
{
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        // statement
        delay(500);
        Serial.println("Connecting to WiFi...");
    }

    Serial.println("Connected to the WiFi network");
}

void loop()
{

}

This session shares a case of displaying the current time on an OLED screen.

It requires the NTPClient.

You need to install this library first.

Getting Started with ESP32 and Arduino (Part 3): Connecting to WiFi and Retrieving Current Time
image-20250410151043063

The NTPClient is a client program that uses the Network Time Protocol (NTP) to obtain the current time from a network time server.

The Network Time Protocol (NTP): NTP is an internet protocol used to synchronize clocks between computer systems.

NTPClient timeClient(ntpUDP, "pool.ntp.org", 28800, 60000); // GMT+8 timezone, update interval 60 seconds
  • <span>pool.ntp.org</span> is a public NTP server pool that redirects your requests to nearby NTP servers. This is a convenient and commonly used option since you do not need to select a specific NTP server.
  • <span>28800</span>: This is an integer representing the timezone offset in seconds. In this case, <span>28800</span> seconds equals 8 hours (28800 / 3600 = 8). This indicates that the code is configured to use the GMT+8 timezone, such as China Standard Time (CST).
  • <span>60000</span>: This is an integer representing the time update interval in milliseconds. In this case, <span>60000</span> milliseconds equals 60 seconds. This means the <span>timeClient</span> object is configured to update the time from the NTP server every 60 seconds.

You also need to install a Time library.

Getting Started with ESP32 and Arduino (Part 3): Connecting to WiFi and Retrieving Current Time
image-20250410151431919

In the Arduino environment, Time is a lightweight library primarily used for handling timestamps and datetime calculations, formatting, and synchronization.

The complete code is as follows:

#include <U8g2lib.h>
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
// WiFi settings
const char* ssid = "TP-LINK_C5A2";
const char* password = "15750849198yy";
// NTP settings
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 28800, 60000); // GMT+8, updates every 60 seconds
// OLED settings
U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /*SCL=*/0, /*SDA=*/1, /*RESET=*/U8X8_PIN_NONE);
void setup() {
  Serial.begin(115200);

// Initialize OLED
  u8g2.begin();
  u8g2.enableUTF8Print();
  u8g2.setFont(u8g2_font_wqy12_t_gb2312);

// Connect to WiFi
  Serial.print("Connecting to WiFi...");
  WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
// Initialize NTP
  timeClient.begin();
while (!timeClient.update()) {
    delay(500);
    Serial.print(".");
  }
  setTime(timeClient.getEpochTime());
  Serial.println("NTP time synced");
}
void loop() {
static unsigned long lastNtpUpdate = 0;
unsigned long now = millis();
// Sync NTP time every minute
if (now - lastNtpUpdate >= 60000) {
    timeClient.update();
    setTime(timeClient.getEpochTime());
    lastNtpUpdate = now;
  }
// Get current time
t = now();
char timeStr[20]; // Sufficient to store "2023年12月31日 23:59:59"

// Format time string
snprintf(timeStr, sizeof(timeStr), 
           "%04d年%02d月%02d日 %02d:%02d:%02d",
           year(t), month(t), day(t),
           hour(t), minute(t), second(t));
// Display time
  u8g2.clearBuffer();
  u8g2.setCursor(0, (32 + u8g2.getMaxCharHeight()) / 2);
  u8g2.print(timeStr);
  u8g2.sendBuffer();

  delay(200); // Reduce refresh rate to minimize flicker
}

Effect:

Getting Started with ESP32 and Arduino (Part 3): Connecting to WiFi and Retrieving Current Time

Leave a Comment