#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <time.h>
#define OLED_ADDR 0x3C
#define OLED_SDA 21
#define OLED_SCL 22
#define OLED_RST 16
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Define time zone (GMT +5:30)
const long timezoneOffset = 5.5 * 3600; // in seconds
// Create an OLED display instance
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);
void setup() {
Serial.begin(9600);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
// Set the system time from an NTP server
configTime(timezoneOffset, 0, "pool.ntp.org", "time.nist.gov");
// Wait for time to be set
time_t now;
Serial.print("Waiting for time");
while ((now = time(nullptr)) < 24 * 3600) {
delay(500);
Serial.print(".");
}
Serial.println();
// Print the obtained time
Serial.println("Time set!");
// Adjust time zone offset
now += timezoneOffset;
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
setenv("TZ", "GMT+5:30", 1);
tzset();
}
void loop() {
// Get the current time
time_t now = time(nullptr);
struct tm timeinfo;
localtime_r(&now, &timeinfo);
// Clear the display
display.clearDisplay();
// Display time
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 10);
display.print(String(timeinfo.tm_hour) + ":" + String(timeinfo.tm_min) + ":" + String(timeinfo.tm_sec));
// Display date
display.setTextSize(1);
display.setCursor(10, 40);
display.print(String(timeinfo.tm_mday) + "/" + String(timeinfo.tm_mon + 1) + "/" + String(1900 + timeinfo.tm_year));
// Display the content on the OLED
display.display();
delay(1000); // Update every second
}