Don’t Waste Your Time: Use NTP!

Introduction: Don’t Waste Your Time: Use NTP!

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects.

Make your time count! This is a frequently discussed topic among my subscribers, and for what reason? Due to the simple and indispensable fact that when you make a datalogger, and for everything involving automation, you need the correct time! And there are several ways to measure time: clock with battery, RTC (Real Time Clock), among others. But the one I want to show you today (which informs date, day of the week, and time) is the NTP (Network Time Protocol), which is online. In this video, we’ll retrieve the date and time information online, and show the information on the display.

Step 1: Demonstration

Step 2: Assembly

Step 3: Assembly - Table

Step 4: Adafruit GFX Library

In the Arduino IDE, go to Sketch->Include Library->Manage Libraries ...

Install Adafruit GFX Library

Step 5: Adafruit ST7735 Library

In the Arduino IDE, go to Sketch->Include Library->Manage Libraries ...

Install Adafruit ST7735

Step 6: NTPClient Library

Go to and download the taranais-modified NTPClient library.

Unzip and put the folder in C:\Users\\Documents\Arduino\libraries

Step 7: ESP32_NTP.ino

Includes and define

#include <WiFi.h>
#include <NTPClient.h> //Biblioteca NTPClient modificada #include <WiFiUdp.h> //Socket UDP #include <Adafruit_GFX.h> //Display #include <Adrafuit_ST7735.h> //Display #include <SPI.h> //Pinos do display #define DISPLAY_DC 12 //A0 #define DISPLAY_CS 13 //CS #define DISPLAY_MOSI 14 //SDA #define DISPLAY_CLK 27 //SCK #define DISPLAY_RST 0 //Fuso Horário, no caso horário de verão de Brasília int timeZone = -2; //Struct com os dados do dia e hora struct Date{ int dayOfWeek; int day; int month; int year; int hours; int minutes; int seconds; }; //Socket UDP que a lib utiliza para recuperar dados sobre o horário WiFiUDP udp; //Objeto responsável por recuperar dados sobre horário NTPClient ntpClient( udp, //socket udp "", //URL do servwer NTP timeZone*3600, //Deslocamento do horário em relacão ao GMT 0 60000); //Intervalo entre verificações online //Nomes dos dias da semana char* dayOfWeekNames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; //Objeto responsável pelo display Adafruit_ST7735 display = Adafruit_ST7735(DISPLAY_CS, DISPLAY_DC, DISPLAY_MOSI, DISPLAY_CLK, DISPLAY_RST);


void setup()
{ Serial.begin(115200); setupDisplay(); connectWiFi(); setupNTP(); //Cria uma nova tarefa no core 0 xTaskCreatePinnedToCore( wifiConnectionTask, //Função que será executada "wifiConnectionTask", //Nome da tarefa 10000, //Tamanho da memória disponível (em WORDs) NULL, //Não vamos passar nenhum parametro 2, //prioridade NULL, //Não precisamos de referência para a tarefa 0); //Número do core }


void setupNTP()
{ //Inicializa o client NTP ntpClient.begin(); //Espera pelo primeiro update online Serial.println("Waiting for first update"); while(!ntpClient.update()) { Serial.print("."); ntpClient.forceUpdate(); delay(500); } Serial.println(); Serial.println("First Update Complete"); }


//Tarefa que verifica se a conexão caiu e tenta reconectar
void wifiConnectionTask(void* param) { while(true) { //Se a WiFi não está conectada if(WiFi.status() != WL_CONNECTED) { //Manda conectar connectWiFi(); } //Delay de 100 ticks vTaskDelay(100); } }


void connectWiFi()
{ Serial.println("Connecting"); //Troque pelo nome e senha da sua rede WiFi WiFi.begin("SSID", "12345678"); //Espera enquanto não estiver conectado while(WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected to "); Serial.println(WiFi.SSID()); }


void setupDisplay()
{ display.initR(INITR_BLACKTAB); //Inicializa o display display.setRotation(3); //Rotaciona display.setTextSize(2); //Tamanho do texto display.fillScreen(ST77XX_BLACK); //Preenche com a cor preta display.setCursor(0, 0); //Coloca o cursor no começo display.setTextColor(ST77XX_WHITE, ST77XX_BLACK); //Texto branco com fundo preto display.setTextWrap(false); //Não pula linha automaticamente }


void loop()
{ //Recupera os dados sobre a data e horário Date date = getDate(); //Reseta o cursor display.setCursor(0, 0); //Exibe os dados no display display.printf(" %s \n\n %s \n\n %02d/%02d/%d\n\n %02d:%02d:%02d", WiFi.SSID().c_str(), dayOfWeekNames[date.dayOfWeek],, date.month, date.year, date.hours, date.minutes, date.seconds); delay(100); }


Date getDate()
{ //Recupera os dados de data e horário usando o client NTP char* strDate = (char*)ntpClient.getFormattedDate().c_str(); //Passa os dados da string para a struct Date date; sscanf(strDate, "%d-%d-%dT%d:%d:%dZ", &date.year, &date.month, &, &date.hours, &date.minutes, &date.seconds); //Dia da semana de 0 a 6, sendo 0 o domingo date.dayOfWeek = ntpClient.getDay(); return date; }

Step 8: Files

Download the files



Be the First to Share


    • Clocks Speed Challenge

      Clocks Speed Challenge
    • Toys & Games Contest

      Toys & Games Contest
    • Big vs Small Challenge

      Big vs Small Challenge