Introduction
先前為了使用開發板用作自動數據紀錄器,練習使用 DS1302 Real Time Clock 模組,紀錄個人使用代碼如下。
安裝
- VCC → 3V or 5V
- GND → GND
- DAT(IO) → D4 (腳位可於代碼中更換)
- CLK(SCLK) → D5 (腳位可於代碼中更換)
- RST(CE) → D2 (腳位可於代碼中更換)
函式庫
安裝函式庫:
代碼
第一次使用(更新時間)
參考代碼:
- 傑森創工(2020), DS1302 時鐘模組快速上手
- SunFounder, Lesson 16: Real Time Clock Module (DS1302), Universal Maker Sensor Kit for Arduino Uno
一般使用
#include <ThreeWire.h>
#include <RtcDS1302.h>
// 定義模組腳位(可自行定義)
ThreeWire myWire(4,5,2); // DAT, CLK, RST
RtcDS1302 <ThreeWire> Rtc(myWire);
void setup ()
{
Serial.begin(9600);
Rtc.Begin();
}
void loop ()
{
Serial.println(getDateTime());
delay(5000); // Loop delay time
}
#define countof(a) (sizeof(a) / sizeof(a[0]))
char* getDateTime()
{
static char dateTimeChar[20];
snprintf_P(dateTimeChar,
countof(dateTimeChar),
PSTR("%04u/%02u/%02u %02u:%02u:%02u"),
Rtc.GetDateTime().Year(),
Rtc.GetDateTime().Month(),
Rtc.GetDateTime().Day(),
Rtc.GetDateTime().Hour(),
Rtc.GetDateTime().Minute(),
Rtc.GetDateTime().Second() );
if (Rtc.GetDateTime().IsValid())
{return dateTimeChar;}
else
{return "Invalid DateTime";}
return dateTimeChar;
}