#include <WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 20, 4);
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
void spinner() {
static int8_t counter = 0;
const char* glyphs = "\xa1\xa5\xdb";
LCD.setCursor(15, 1);
LCD.print(glyphs[counter++]);
if (counter == strlen(glyphs)) {
counter = 0;
}
}
void printLocalTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
LCD.setCursor(0, 1);
LCD.println("Connection Err");
return;
}
time(&now);
// Prepare the time for display
int hour = timeinfo.tm_hour; // Get the hour
int minute = timeinfo.tm_min; // Get the minutes
int second = timeinfo.tm_sec; // Get the seconds
String ampm = "AM"; // Default to AM
// Convert to 12-hour format
if (hour >= 12) {
if (hour > 12) hour -= 12; // Convert 24-hour to 12-hour
ampm = "PM"; // Set to PM
} else if (hour == 0) {
hour = 12; // Midnight case
}
// Display the time
LCD.setCursor(0, 0);
LCD.print(&timeinfo, "%A,");
LCD.setCursor(0, 1);
LCD.print(&timeinfo, "%B %d %Y");
LCD.setCursor(0, 2);
LCD.printf("%02d:%02d:%02d %s", hour, minute, second, ampm.c_str());
LCD.setCursor(0, 3);
LCD.print(now);
}
void setup() {
Serial.begin(115200);
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Connecting to ");
LCD.setCursor(0, 1);
LCD.print("WiFi ");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
spinner();
}
Serial.println("");
Serial.println("WiFi connected");
LCD.clear();
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
}
void loop() {
printLocalTime();
delay(250);
}