#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <time.h>
// Định nghĩa chiều rộng và chiều cao của màn hình OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Khởi tạo đối tượng màn hình OLED
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Định nghĩa thông tin kết nối WiFi
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Định nghĩa UTC offset cho múi giờ Việt Nam (UTC+7)
const long gmtOffset_sec = 7 * 3600;
const int daylightOffset_sec = 0;
// Hàm lấy tên viết tắt của ngày trong tuần
const char* getDayAbbr(int wday) {
switch (wday) {
case 0: return "Sun";
case 1: return "Mon";
case 2: return "Tue";
case 3: return "Wed";
case 4: return "Thu";
case 5: return "Fri";
case 6: return "Sat";
default: return "";
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Kết nối WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Thiết lập NTP để đồng bộ thời gian
configTime(gmtOffset_sec, daylightOffset_sec, "time.google.com");
// Kiểm tra và khởi động màn hình OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Real Time Clock");
display.display();
delay(2000); // Hiển thị thông điệp chào mừng trong 2 giây
// Đồng bộ thời gian
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
display.setCursor(0, 10);
display.println("Failed to get time");
display.display();
while (1) { delay(1000); }
}
// In thời gian đồng bộ lên Serial Monitor
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}
void loop() {
struct tm timeinfo;
if (getLocalTime(&timeinfo)) {
// Xóa màn hình cũ
display.clearDisplay();
// Hiển thị thời gian (giờ:phút:giây)
display.setTextSize(2);
char timeString[10];
sprintf(timeString, "%02d:%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
Serial.println("Time: " + String(timeString));
int16_t x1, y1;
uint16_t width, height;
display.getTextBounds(timeString, 0, 0, &x1, &y1, &width, &height);
int16_t x = (SCREEN_WIDTH - width) / 2;
display.setCursor(x, 0);
display.print(timeString);
// Hiển thị thứ và ngày (Thứ - ngày-tháng-năm)
display.setTextSize(1);
char dateString[20];
sprintf(dateString, "%s - %02d/%02d/%04d", getDayAbbr(timeinfo.tm_wday), timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year + 1900);
display.getTextBounds(dateString, 0, 0, &x1, &y1, &width, &height);
x = (SCREEN_WIDTH - width) / 2;
display.setCursor(x, 40);
display.print(dateString);
display.display();
}
delay(1000); // Cập nhật mỗi giây
}