Quick tinkering of an NTP clock with the ESP32

I spent a little time today trying to make the bare minimum code necessary for the ESP32 to connect to my WiFi network and synchronizing the time using NTP. It’s not really that amazing, but required a tiny bit of snooping around to figure out how to make it work. Archived here, just for fun.

[source lang=”cpp”]
/*
* tinkering a basic wifi shell/framework together
* duplicating work that I had done for the esp8266
* but which doesn’t appear to work on the ESP32.
*/

#include <NTPClient.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <SSD1306.h>

SSD1306 display(0x3c, 5, 4);

const char *ssid = "**********" ;
const char *pass = "**********" ;

const char *ntp_server = "0.us.pool.ntp.org" ;

WiFiUDP ntpUDP ;
NTPClient timeClient(ntpUDP, ntp_server, -8*60*60, 5*60*1000) ;

void
wifievent(WiFiEvent_t event)
{
switch (event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println() ;
Serial.print("CONNECTED ") ;
Serial.println(WiFi.localIP()) ;
Serial.println("CONTACTING NTP SERVER") ;
timeClient.begin() ;
timeClient.update() ;
break ;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("DISCONNECTED") ;
break ;
}
}

void
setup()
{
Serial.begin(115200) ;
delay(500) ;
Serial.println("ESP32 harness.") ;

WiFi.disconnect(true) ;

WiFi.onEvent(wifievent) ;

WiFi.begin(ssid, pass) ;
Serial.println("CONNECTING") ;

display.init() ;
display.setFont(ArialMT_Plain_24);
}

void
loop()
{
delay(1000) ;

Serial.print(‘.’) ;

display.clear() ;
display.setTextAlignment(TEXT_ALIGN_CENTER_BOTH);
display.drawString(64, 32, String(timeClient.getFormattedTime())) ;
display.display() ;
}
[/source]

Addendum: Here’s a quick video of it working, with a small extension to display the NTP address of the clock too.