Sharifdeen Ashshak
Published

How to get current time using IOT

In this project we will design an Internet Clock using ESP8266 Node-MCU. I will fetch the time and date from the internet using the ESP8266

BeginnerFull instructions provided1,811
How to get current time using IOT

Things used in this project

Story

Read more

Schematics

circuit

Code

code

C/C++
//for more projects visit www.blackkeyhole.com
//modified Ashshak Sharifdeen
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>               
#include <TimeLib.h>                 
#include <LiquidCrystal.h>
 
const int RS = D3, EN = D4, d4 = D5, d5 = D6, d6 = D7, d7 = D8;   
LiquidCrystal lcd(RS, EN, d4, d5, d6, d7); 
 
 
const char *ssid     = "ZTE WIFI";
const char *password = "kl2229834";
 
WiFiUDP ntpUDP;
 
 //srilankan time zone
 //+5 hr 30 Mins = 5x60x60 + 3060 = 19800
NTPClient timeClient(ntpUDP, "asia.pool.ntp.org", 19800, 60000);
 
char Time[ ] = "TIME:00:00:00";
char Date[ ] = "DATE:00/00/2000";
byte last_second, second_, minute_, hour_, day_, month_;
int year_;
 
 
 
void setup() {
 
  Serial.begin(115200);
  lcd.begin(16,2);                 // Initialize I2C LCD module (SDA = GPIO21, SCL = GPIO22)                  
  lcd.setCursor(0, 0);
  lcd.print(Time);
  lcd.setCursor(0, 1);
  lcd.print(Date);
 
  WiFi.begin(ssid, password);
  Serial.print("Connecting.");
 
  while ( WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("connected");
  timeClient.begin();
}
 
 
void loop() {
 
  timeClient.update();
  unsigned long unix_epoch = timeClient.getEpochTime();    // Get Unix epoch time from the NTP server
 
  second_ = second(unix_epoch);
  if (last_second != second_) {
 
 
    minute_ = minute(unix_epoch);
    hour_   = hour(unix_epoch);
    day_    = day(unix_epoch);
    month_  = month(unix_epoch);
    year_   = year(unix_epoch);
 
 
 
    Time[12] = second_ % 10 + 48;
    Time[11] = second_ / 10 + 48;
    Time[9]  = minute_ % 10 + 48;
    Time[8]  = minute_ / 10 + 48;
    Time[6]  = hour_   % 10 + 48;
    Time[5]  = hour_   / 10 + 48;
 
 
 
    Date[5]  = day_   / 10 + 48;
    Date[6]  = day_   % 10 + 48;
    Date[8]  = month_  / 10 + 48;
    Date[9]  = month_  % 10 + 48;
    Date[13] = (year_   / 10) % 10 + 48;
    Date[14] = year_   % 10 % 10 + 48;
 
    Serial.println(Time);
    Serial.println(Date);
 
    lcd.setCursor(0, 0);
    lcd.print(Time);
    lcd.setCursor(0, 1);
    lcd.print(Date);
    last_second = second_;
 
  }
  delay(500);
}

Credits

Sharifdeen Ashshak
34 projects • 44 followers
Ai, IoT, embedded enthusiast

Comments