/* 程式名稱:時鐘模組DS1302 */
#include <ThreeWire.h>
#include <RtcDS1302.h> // 使用函式庫Rtc by Makuna by Michael C. Miller
ThreeWire myWire(6, 7, 5); // 修改時鐘模組腳位(DAT, CLK, RST)
RtcDS1302<ThreeWire> Rtc(myWire);
void setup ()
{
Serial.begin(9600);
Rtc.Begin();
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__); // 變數設為電腦的日期時間
printDateTime(compiled); // 使用自訂函式顯示電腦時間
if (!Rtc.IsDateTimeValid()) //判斷DS1302是否接好
{
Serial.println("RTC lost confidence in the
DateTime!");
Rtc.SetDateTime(compiled);
}
if (Rtc.GetIsWriteProtected())
{
Serial.println("RTC was write protected, enabling
writing now");
Rtc.SetIsWriteProtected(false);
}
if (!Rtc.GetIsRunning())
{
Serial.println("RTC was not actively running,
starting now");
Rtc.SetIsRunning(true);
}
//如果程式編譯當時的時間與DS1302上的時間不同,就更改DS1302的時間
//now為DS1302上紀綠的時間,compiled為編譯時的時間
RtcDateTime now = Rtc.GetDateTime();
if (now != compiled)
{
Serial.println("RTC is older than compile time!
(Updating DateTime)");
Rtc.SetDateTime(compiled);
}
}
void loop ()
{
RtcDateTime now = Rtc.GetDateTime(); // 讀取DS1302時間模組的時間
printDateTime(now); // 使用自訂函式顯示現在時間
if (!now.IsValid()) //判斷DS1302是否正常,不正常可能是線沒接好,或是電池沒電
{
Serial.println("RTC lost confidence in the
DateTime!");
}
delay(1000); // 暫停1000毫秒=1秒
}
#define countof(a) (sizeof(a) / sizeof(a[0]))
void printDateTime(const RtcDateTime& dt) //顯示年月日時間的副程式
{
char datestring[20];
snprintf_P(datestring,
countof(datestring),
PSTR("%04u/%02u/%02u %02u:%02u:%02u"), dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second());
Serial.println(datestring);
}
|