/*
	DATE : 28/04/2022
	AUTEUR : RACHEL SYSTEME

	該程式允許您透過模組讀取日期和時間
	RTC DS1307 然後將其顯示在序列監視器中。

	注意:程式上傳後,刪除該功能
	“config_RTC()”然後再次上傳程式。

	原始網址:https://github.com/RS-malik-el/RTC_DS1307/blob/main/moniteur_serie_RTC_DS1307.ino
	影片:https://youtu.be/ehHwCxttW6I?si=tMlnMKj6DmivbCod
*/

#include <RTClib.h>

// 建立 RTC_DS1307 對象
RTC_DS1307 rtc;

// 建立日期時間對象
DateTime Now;

String jour[7]{
	"Dimanche",
	"Lundi",
	"Mardi",
	"Mercredi",
	"Jeudi",
	"Vendredi",
	"Samedi"
};

// 函數原型
void config_RTC(int decalage = 10);
void date(void);
void time_f24(void);
void time_f12(void);

void setup(){
	// 初始化串行通訊
	Serial.begin(9600);
	// 初始化與 RTC_DS1307 模組的通信
	rtc.begin();
/*	
	下載程式後,刪除該功能即可
	重新上傳程序。
	注意:如果不刪除,每次啟動程式時,
	日期和時間將設定為上傳日期
	程式.

	在函數參數中插入近似延遲
	例如:config_RTC(20); // 最大值 60
*/
	config_RTC(); 
}

void loop(){
	date();
	time_f24();
	time_f12();
	Serial.println("");
	delay(1000);
}

void config_RTC(int decalage){
	// 如果延遲超過 60 秒
	if (decalage > 60)
		decalage = 60;
/*
	配置 RTC 模組日期和時間
	程式編譯的日期和時間。

	手動設定 2022 年 4 月 27 日 11:00:00
	rtc.調整(日期時間(2022,4,27,11,0,0));
*/
	rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
	
	Now = rtc.now(); // Mise à jour

	int date 	= (int) Now.day();
	int mois 	= (int) Now.month();
	int  annee 	= (int) Now.year();

	int H = (int) Now.hour();
	int M = (int) Now.minute();
	int S = (int) Now.second();

	// 總秒數
	int S_Total = S + decalage;
	// 總分鐘數
	int M_Total =  M + (S_Total / 60);
	// 總小時數
	int H_Total =  H + (M_Total / 60);

	S = S_Total % 60;
	M = M_Total % 60;
	H = H_Total % 24;
/*
	配置 RTC 模組日期和時間
	程式編譯的日期和時間
	加上傳輸到arduino時產生的延遲

*/
	rtc.adjust(DateTime(annee, mois, date, H, M, S));
}

void date(void){
	Now = rtc.now();

	Serial.print(jour[Now.dayOfTheWeek()]);
	Serial.print(" ");
	Serial.print(Now.day());
	Serial.print("/");
	Serial.print(Now.month());
	Serial.print("/");
	Serial.print(Now.year());
	Serial.println("");
}

// 24小時制
void time_f24(){
	Now = rtc.now();

	Serial.print(Now.hour());
	Serial.print(":");
	Serial.print(Now.minute());
	Serial.print(":");
	Serial.print(Now.second());
	Serial.println("");
}

// 12小時制
void time_f12(){
	Now = rtc.now();

	Serial.print(Now.twelveHour());
	Serial.print(":");
	Serial.print(Now.minute());
	Serial.print(":");
	Serial.print(Now.second());

	if (Now.isPM())
		Serial.print(" PM");
	else
		Serial.print(" AM");
	
	Serial.println("");
}
nano:12
nano:11
nano:10
nano:9
nano:8
nano:7
nano:6
nano:5
nano:4
nano:3
nano:2
nano:GND.2
nano:RESET.2
nano:0
nano:1
nano:13
nano:3.3V
nano:AREF
nano:A0
nano:A1
nano:A2
nano:A3
nano:A4
nano:A5
nano:A6
nano:A7
nano:5V
nano:RESET
nano:GND.1
nano:VIN
nano:12.2
nano:5V.2
nano:13.2
nano:11.2
nano:RESET.3
nano:GND.3
GND5VSDASCLSQWRTCDS1307+
rtc1:GND
rtc1:5V
rtc1:SDA
rtc1:SCL
rtc1:SQW