Arduino-時鐘
11/18
11/18
Arduino本身不具備時間記錄功能,需使用其他模組。DS1302模組是常用於時間記錄的選擇,搭配程式庫使用即可輕鬆實現,並可透過一個簡易的顯示螢幕來完成時鐘功能。
程式碼:
#include <ThreeWire.h>
#include <RtcDS1302.h>
#include <TM1637Display.h>
#define countof(a) (sizeof(a) / sizeof(a[0]))
#define CLK 11
#define DIO 12
TM1637Display display(CLK, DIO);
ThreeWire myWire(4, 5, 6); //接腳: DAT/IO, SCLK/CLK, RST/CE
RtcDS1302<ThreeWire> Rtc(myWire);
void setup()
{
Serial.begin(9600);//鮑率57600
display.setBrightness(7);
Serial.print("compiled: ");
Serial.print(__DATE__);
Serial.println(__TIME__);
Rtc.Begin();
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
printDateTime(compiled);
Serial.println();
if (!Rtc.IsDateTimeValid())
{
// Common Causes:
// 1) 第一次使用但設備還沒跑好
// 2) 電池電量低
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);
}
else if (now > compiled)
{
Serial.println("RTC is newer than compile time. (this is expected)");
}
else if (now == compiled)
{
Serial.println("RTC is the same as compile time! (not expected but all is fine)");
}
}
void loop()
{
RtcDateTime now = Rtc.GetDateTime();
printDateTime(now);//呼叫副函數
Serial.println();
if (!now.IsValid())
{
// Common Causes:
// 1) the battery on the device is low or even missing and the power line was disconnected
Serial.println("RTC lost confidence in the DateTime!");
}
}
void printDateTime(const RtcDateTime &dt)
{
char datestring[20];
snprintf_P(datestring,
countof(datestring),
PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
dt.Month(),//月
dt.Day(),//日
dt.Year(),//年
dt.Hour(),//小時
dt.Minute(),//分鐘
dt.Second());//秒
Serial.println(dt.Minute());
display.showNumberDecEx(dt.Hour(), 0b11100000, 2, 2); //前兩位數設定為小時
display.showNumberDecEx(dt.Minute(), 0b11100000, true, 2, 2); //後兩位數設定為分鐘
delay(1000);
}