#include <WiFi.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <SPI.h>
#include "time.h"
#define TFT_CS 5
#define TFT_RST 4
#define TFT_DC 2
#define TFT_SCLK 12
#define TFT_MOSI 11
const char* ssid = "Airtel_arvi_6035";
const char* password = "air26289";
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
// NTP server and offset for IST (UTC+5:30)
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 19800; // 5.5 hours
const int daylightOffset_sec = 0;
unsigned long modeStart;
bool showAnalog = true;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected!");
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
tft.init(240, 280);
tft.setRotation(2);
tft.fillScreen(ST77XX_BLACK);
modeStart = millis();
}
void loop() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return;
}
unsigned long elapsed = millis() - modeStart;
if (elapsed > 60000) { // switch every 60s
showAnalog = !showAnalog;
modeStart = millis();
tft.fillScreen(ST77XX_BLACK);
}
if (showAnalog) {
drawAnalogClock(timeinfo);
} else {
drawDigitalClock(timeinfo);
}
delay(1000);
}
void drawAnalogClock(struct tm t) {
int cx = tft.width()/2;
int cy = tft.height()/2;
int radius = min(cx, cy) - 10;
// clock face
tft.fillScreen(ST77XX_BLACK);
tft.drawCircle(cx, cy, radius, ST77XX_WHITE);
// hour marks
for (int i=0; i<12; i++) {
float angle = i * 30 * PI / 180;
int x1 = cx + cos(angle) * (radius-10);
int y1 = cy + sin(angle) * (radius-10);
int x2 = cx + cos(angle) * radius;
int y2 = cy + sin(angle) * radius;
tft.drawLine(x1, y1, x2, y2, ST77XX_YELLOW);
}
// hands
float secAngle = t.tm_sec * 6 * PI / 180;
float minAngle = t.tm_min * 6 * PI / 180;
float hourAngle = ((t.tm_hour % 12) + t.tm_min/60.0) * 30 * PI / 180;
drawHand(cx, cy, secAngle, radius-15, ST77XX_RED);
drawHand(cx, cy, minAngle, radius-25, ST77XX_GREEN);
drawHand(cx, cy, hourAngle, radius-40, ST77XX_BLUE);
}
void drawHand(int cx, int cy, float angle, int length, uint16_t color) {
int x = cx + cos(angle - PI/2) * length;
int y = cy + sin(angle - PI/2) * length;
tft.drawLine(cx, cy, x, y, color);
}
void drawDigitalClock(struct tm t) {
char buf[20];
sprintf(buf, "%02d:%02d:%02d", t.tm_hour, t.tm_min, t.tm_sec);
tft.fillScreen(ST77XX_BLACK);
tft.setTextColor(ST77XX_CYAN);
tft.setTextSize(4);
tft.setCursor(20, tft.height()/2 - 20);
tft.println(buf);
}
https://wokwi.com/projects/465786985444555777