#include <RTClib.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
RTC_DS1307 rtc; // Tạo đối tượng của lớp RTC_DS1307 để tương tác với module RTC.
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
char THU[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
//Tạo 1 mảng 2 chiều có 7 hàng (tương ứng 7 ngày trong tuần) và 12 cột (để chứa tên đầy đủ của từng ngày như "Wednesday") , mỗi cột chứa 1 kí tự
void setup () {
Serial.begin(9600);
while (!Serial); // Đợi serial port kết nối
if (! rtc.begin()) { // Nếu không có tín hiệu của DS1307 thì in ra dòng bên dưới
Serial.println("Couldn't find RTC");
while (1); // Lập lại cho đến khi nhận được tín hiệu của DS1307
}
if(!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) //Nếu khởi tạo thất bại, in thông báo lỗi và dừng chương trình bằng while(1).
{Serial.println("SSD1306 allocation failed");
while(1);
}
oled.clearDisplay(); //Xóa nội dung màn hình OLED.
oled.setTextSize(1.8); //Cài đặt kích thước chữ (mặc định là 1).
oled.setTextColor(WHITE); //Cài đặt màu chữ (WHITE là màu trắng).
oled.setCursor(30,30); //Đặt vị trí con trỏ tại tọa độ (x,y) (pixel).
oled.println("OLED READY!"); //Hiển thị chuỗi ký tự lên màn hình OLED.
oled.display(); //Cập nhật màn hình OLED để hiển thị nội dung vừa vẽ.
delay(1000);
Serial.println("Setting the time...");
//rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// Cài đặt thời gian cho ds1307 (năm,tháng,ngày,giờ,phút,giây)
rtc.adjust(DateTime(2024, 11, 22, 8, 50, 0));
}
void loop () {
DateTime quy = rtc.now();// Tạo đối tượng quy của lớp DateTime và gán, thời gian hiện tại cho nó bằng rtc.now()
oled.clearDisplay(); //Xóa nội dung màn hình OLED.
oled.setTextSize(2); //Cài đặt kích thước chữ (mặc định là 1).
oled.setTextColor(WHITE); //Cài đặt màu chữ (WHITE là màu trắng).
oled.setCursor(0,20); //Đặt vị trí con trỏ tại tọa độ (x,y) (pixel).
Serial.print(quy.year(), DEC); // truy cập năm, ngày, tháng của datetime quy rồi in ra màn hình
Serial.print('/');
oled.print(quy.year(), DEC);
oled.print('/');
Serial.print(quy.month(), DEC);
Serial.print('/');
oled.print(quy.month(), DEC);
oled.print('/');
Serial.print(quy.day(), DEC);
oled.print(quy.day(), DEC);
oled.println();
Serial.print(" (");
Serial.print(THU[quy.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(quy.hour(), DEC);
Serial.print(':');
oled.print(quy.hour(), DEC);
oled.print(':');
Serial.print(quy.minute(), DEC);
Serial.print(':');
oled.print(quy.minute(), DEC);
oled.print(':');
Serial.print(quy.second(), DEC);
oled.print(quy.second(), DEC);
oled.display();
Serial.println();
Serial.println();
delay(1000); //Cứ sau 1s thì cập nhật lại thời gian
}