// // Ass 3 Q1 (NTP)
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h> // Include TimeLib library for time manipulation
#include <LiquidCrystal_I2C.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* ntpServerName = "pool.ntp.org";
const long gmtOffset_sec = 3 * 3600; // Egypt
const int daylightOffset_sec = 3600;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntpServerName, gmtOffset_sec, 60000); // Update every 60 seconds
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Connecting to");
lcd.setCursor(0, 1);
lcd.print(ssid);
// Start Wi-Fi connection
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
lcd.setCursor(15, 1); // Move to the end of the line
lcd.print("|"); // Display a simple loading indicator
delay(500);
}
Serial.println();
Serial.print("Connected to WiFi: ");
Serial.println(WiFi.SSID());
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Display connection success on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WiFi Connected");
lcd.setCursor(0, 1);
lcd.print("IP: ");
lcd.print(WiFi.localIP());
// Initialize NTPClient
timeClient.begin();
delay(2000); // Delay to allow IP address to display before continuing
}
void loop() {
timeClient.update();
if (timeClient.getEpochTime() > 0) {
time_t epochTime = timeClient.getEpochTime();
setTime(epochTime); // Set the system time
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Current time: ");
lcd.setCursor(0, 1);
if (hour() < 10) lcd.print("0");
lcd.print(hour());
lcd.print(":");
if (minute() < 10) lcd.print("0");
lcd.print(minute());
lcd.print(":");
if (second() < 10) lcd.print("0");
lcd.print(second());
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Failed to get");
lcd.setCursor(0, 1);
lcd.print("time from NTP");
}
delay(1000);
}