Internet Clock: Display Date and Time on OLED using ESP8266 NodeMCU with NTP

RTC Or Real Time Clock is the most commonly used module in Electronics and embedded devices to keep track of time. But the problem with RTC is that the microchips in computers are not that much accurate and they can only provide the time of local device. On the other hand, using the internet to fetch the time from NTP servers is better solution for getting time as it is more accurate and can provide the time of any geographical area in the world. We just need a Wi-Fi module and access to internet to get time of any location in the world by using NTP servers. In this tutorial, we will Use ESP8266 NodeMCU To Get Current Time And Date From NTP Servers And Display It On OLED Display.

Network Time Protocol (NTP)

NTP is one of the oldest networking Internet Protocol (IP) for synchronizing clocks between computer networks. It was designed by David L. Mills of the University of Delaware in 1981. This protocol can be used to synchronize many networks to Coordinated Universal Time (UTC) within few milliseconds. UTC is the primary time standard by which world regulates clock and time. UTC does not changes and vary for different geographical locations. NTP uses UTC as the time reference and provides accurate and synchronized time across the Internet.

NTP works on a hierarchical client-server model. Top model has reference clocks known as “Stratum0” like atomic clocks, radio waves, GPS, GSM which receives time from the satellite. The servers which receive time from stratum0 are called as “Stratum1” and servers which receive time from stratum1 are called “Stratum2” and so on. This goes on and the accuracy of time goes on decreasing after each stage. NTP automatically selects the best of several available time sources to synchronize which makes it fault-tolerant able protocol.

So here in this project, we are Getting Time From NTP Server Using ESP8266 NodeMCU And Showing It On OLED Display. This same kind of Internet Clock Is Built By Using ESP32 In Previous Tutorial.

Communication between UDP and NTP server

ESP8266 can access NTP servers using internet to get accurate time. Here NTP works in Client-Server mode, ESP8266 Works As Client Device and connects with NTP Servers using UDP (User Datagram Protocol). The client transmits a request packet to NTP servers and in return NTP sends a timestamp packet which consists information like accuracy, timezone, UNIX timestamp etc. Then client separates the date and time details which can be further used in applications according to requirement.

Components Required

  • Monochrome 7-pin SSD1306 0.96” OLED display
  • ESP8266 NodeMCU
  • Micro USB cable
  • Breadboard
  • Male to Male Jumper wires

Circuit Diagram And Connections

This 7-pin OLED display communicates with ESP8266 module using SPI protocol, below are the circuit diagram and connections table to Connect OLED SPI Pins With NodeMCU To Display Internet Time.

ESP8266 OLED Connections Circuit Diagram
No.OLED DisplayNodeMCU
1GNDGND
2VDD3.3V
3SCKD5
4MOSI (SPI) or SDA (I2C)D7
5RESETD3
6DCD2
7CSD8

To learn more this Monochrome 7-Pin OLED Display And Its Interfacing With ESP8266 NodeMCU, follow the link.

Code Explanation

First we have to download and install NTP library into ESP8266. There are many libraries available for NTP Client. You can install any of them from Arduino IDE. In this tutorial I have installed NTPClient Library By Taranais because it is easy to use and have functions to get date and time from NTP servers. ESP8266 NodeMCU Can Be Easily Programmed Using Arduino IDE.

Installing NTPClient Library in Arduino IDE

To install the NTP library, first download the library using above link and then install it using Arduino IDE. To install it go to Sketch > Include Library > Add .ZIP Library, then open the Zip folder by going to the location where you have downloaded the zip folder and restart the Arduino IDE.

Downloading NTPClient Library for Internet Clock
Adding NTPClient Library Zip into Arduino

NTPClient library comes with examples. Open Arduino IDE and Goto Examples > NTPClient > Advanced. The code given in this sketch displays the time from NTP server on the serial monitor. We will use this sketch to display current time and date on OLED display.

Successfully Added NTPClient Library for Internet Clock

Complete Code Is Available At The End Of This Tutorial, here I have explained few important part of the code.

ESP8266WiFi Library provides ESP8266 specific Wi-Fi routines to connect to network. WiFiUDP.H handles sending and receiving UDP packages. Since we are using SPI protocol to interface OLED with NodeMCU therefore we will import “SPI.h” library. And “Adafruit_GFX.h” and “Adafruit_SSD1306.h” are used for OLED Display.

#Include <NTPClient.H>
#Include <ESP8266WiFi.H> // Provides ESP8266 Specific Wi-Fi Routines We Are Calling To Connect To Network
#Include <WiFiUdp.H> //Handles Sending And Receiving Of UDP Packages
#Include <SPI.H> // SPI For Interfacing OLED With NodeMCU
#Include <Adafruit_GFX.H>
#Include <Adafruit_SSD1306.H>

Our OLED size is 128×64 so we are setting screen width and height as 128 and 64 respectively. So  define the variables for OLED pins connected to NodeMCU for SPI communication.

#Define SCREEN_WIDTH 128 // OLED Display Width, In Pixels
#Define SCREEN_HEIGHT 64 // OLED Display Height, In Pixels

// Declaration For SSD1306 Display Connected Using Software SPI (Default Case):
#Define OLED_MOSI   D7
#Define OLED_CLK   D5
#Define OLED_DC    D2
#Define OLED_CS    D8
#Define OLED_RESET D3

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

Replace “your_ssid” and “your_password” with your Wi-Fi SSID and password in the below lines of code.

Const Char *Ssid     = "Your_ssid";
Const Char *Password = "Your_password";

Set up WI-Fi connection by giving SSID and password to WiFi.begin function. The connection of ESP8266 takes some time to get connected to NodeMCU so we have to wait till it gets connected.

WiFi.Begin(Ssid, Password);
  While ( WiFi.Status() != WL_CONNECTED ) {
    Delay ( 500 );
    Serial.Print ( "." );
  }

To Request Date And Time, Initialize Time Client With Address Of NTP Servers. For better accuracy choose the address of NTP servers which are close to your geographical area. Here we use “Pool.Ntp.Org” which gives servers from worldwide. If you wish to choose servers from Asia you can use “asia.pool.ntp.org”. timeClient also takes UTC time offset in milliseconds of your timezone. For instance, UTC Offset For India Is +5:30 so we convert this offset in milliseconds which is equal to 5*60*60+30*60 = 19800.

AreaUTC time offset(hours and minutes)UTC time offset(seconds)
INDIA+5:3019800
LONDON0:000
NEW YORK-5:00-18000
WiFiUDP NtpUDP;
NTPClient TimeClient(NtpUDP, "Pool.Ntp.Org", 19800,60000);

SSD1306_SWITCHCAPVCC is given to generate 3.3V internally to initialize the display. When the OLED starts it displays “WELCOME TO CIRCUIT DIGEST” with text size 2 and color BLUE for 3 seconds.

If(!Display.Begin(SSD1306_SWITCHCAPVCC))
  {
    Serial.Println(F("SSD1306 Allocation Failed"));
    For(;;); // Don't Proceed, Loop Forever
  }
  Display.ClearDisplay();
  Display.SetTextSize(2); // Draw 2X-Scale Text
  Display.SetTextColor(BLUE);
  Display.SetCursor(5, 2);
  Display.Println("WELCOME TO");
  Display.Println("  CIRCUIT");
  Display.Println("  DIGEST");
  Display.Display();
  Delay(3000);

NTP Client Is Initialized Using  Begin() function to set date and time from NTP servers.

TimeClient.Begin();

Update() function is used to receive the date and time whenever we request to NTP servers.

TimeClient.Update();

Baud rate of 115200 is set to print the time on serial monitor.

Serial.Begin(115200);
Serial.Println(TimeClient.GetFormattedTime());

getHours(), getMinutes(), getSeconds(), getDay are the library function and gives the current hour, minutes, seconds and day from NTP server. Code below is used to differentiate time between AM and PM. If the hour we get using getHours() is greater than 12 then we set that time as PM else its AM.

Int Hh = TimeClient.GetHours();
Int Mm = TimeClient.GetMinutes();
Int Ss = TimeClient.GetSeconds();
Int Day = TimeClient.GetDay();

If(Hh>12)
  {
    Hh=Hh-12;
    Display.Print(Hh);
    Display.Print(":");
    Display.Print(Mm);
    Display.Print(":");
    Display.Print(Ss);
    Display.Println(" PM");
  }
  Else
  {
    Display.Print(Hh);
    Display.Print(":");
    Display.Print(Mm);
    Display.Print(":");
    Display.Print(Ss);
    Display.Println(" AM");  
  }
  Int Day = TimeClient.GetDay();
  Display.Println("'"+Arr_days[Day]+"'");

getFormattedDate() is used get date in “yyyy-mm-dd” format from NTP server. This function gives date and time in “yyyy-mm-dd T hh:mm:ss format. But we need only date so we have to split this string which is stored in date_time format till “T” which is done by substring() function and then store the date in “date” variable.

Date_time = TimeClient.GetFormattedDate();
  Int Index_date = Date_time.IndexOf("T");
  String Date = Date_time.Substring(0, Index_date);
  Serial.Println(Date);
  Display.Println(Date);
  Display.Display();     

This is how the OLED Internet Time Clock will look finally:

DIY ESP8266 Internet Clock

Code

#include <NTPClient.h>
#include <ESP8266WiFi.h> // provides ESP8266 specific Wi-Fi routines we are calling to connect to network
#include <WiFiUdp.h> //handles sending and receiving of UDP packages
#include <SPI.h> // SPI for interfacing OLED with NodeMCU
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for SSD1306 display connected using software SPI (default case):
#define OLED_MOSI   D7
#define OLED_CLK   D5
#define OLED_DC    D2
#define OLED_CS    D8
#define OLED_RESET D3
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

const char *ssid     = “CircuitLoop”;
const char *password = “circuitdigest101”;

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, “pool.ntp.org”, 19800,60000);
String arr_days[]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
String date_time;
// You can specify the time server pool and the offset (in seconds, can be
// changed later with setTimeOffset() ). Additionaly you can specify the
// update interval (in milliseconds, can be changed using setUpdateInterval() ).
  

void setup(){
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( “.” );
  }

  if(!display.begin(SSD1306_SWITCHCAPVCC))
  {
    Serial.println(F(“SSD1306 allocation failed”));
    for(;;); // Don’t proceed, loop forever
  }
  display.clearDisplay();
  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(WHITE);
  display.setCursor(5, 2);
  display.println(“WELCOME TO”);
  display.println(”  CIRCUIT”);
  display.println(”  DIGEST”);
  display.display();
  delay(3000);
  timeClient.begin();
}

void loop() {
  timeClient.update();
  
  display.clearDisplay();
  
  Serial.println(timeClient.getFormattedTime());
  
  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(BLUE);
  display.setCursor(0, 2);
  int hh = timeClient.getHours();
  int mm = timeClient.getMinutes();
  int ss = timeClient.getSeconds();
  
  if(hh>12)
  {
    hh=hh-12;
    display.print(hh);
    display.print(“:”);
    display.print(mm);
    display.print(“:”);
    display.print(ss);
    display.println(” PM”);
  }
  else
  {
    display.print(hh);
    display.print(“:”);
    display.print(mm);
    display.print(“:”);
    display.print(ss);
    display.println(” AM”);   
  }

  int day = timeClient.getDay();
  display.println(“‘”+arr_days[day]+”‘”);
  
  date_time = timeClient.getFormattedDate();
  int index_date = date_time.indexOf(“T”);
  String date = date_time.substring(0, index_date);
  Serial.println(date);
  display.println(date);
  display.display();      // Show initial text
}

Von Sirko