RTC Module(DS1302) CN: 두 판 사이의 차이
(새 문서: {{#seo:|title=Arduino维基:Arduino RTC模块(DS1302)指南|title_mode=append|keywords=Arduino, 信息科学, 创客学习, 性能评估, RTC模块(DS1302), Arduino项目, 毕业设计项目, Arduino示例代码|description=介绍如何使用Arduino控制RTC模块(DS1302)(基本信息、电路、示例代码)。可用于信息科学和创客课程。}} 가운데|class=coders100 即使未连接到板子也能记住时间...) |
(차이 없음)
|
2025년 3월 20일 (목) 20:50 기준 최신판

即使未连接到板子也能记住时间的模块。
使用电池(CR2032)。
规格
- 工作电压:3.3V 〜 5V
- 工作电流:2V 基准 300nA
所需硬件
- RTC 模块
- Arduino
连接
| RTC module | Arduino |
| VCC | 5V |
| GND | GND |
| CLK | D5 |
| DAT | D4 |
| RST | D3 |

Library
This document uses the Rtc by Makuna library for Arduino. Arduino Libraries

示例代码
这段代码在编译时保存时间,因此上传到板子时可能会有轻微的差异。 (由于代码在编译后上传到板子,因此在上传过程中会产生误差)

#include <ThreeWire.h>
#include <RtcDS1302.h>
//--------------------Modified Section-------------------------------
#define CLK 5 //Specify CLK pin number
#define DAT 4 //Specify DAT pin number
#define RST 3 //Specify RST pin number
ThreeWire myWire(DAT,CLK,RST);
//--------------------------------------------------------------
RtcDS1302<ThreeWire> Rtc(myWire);
void setup ()
{
Serial.begin(57600);
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) first time you ran and the device wasn't running yet
// 2) the battery on the device is low or even missing
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);
}
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!");
}
delay(10000); // ten seconds
}
#define countof(a) (sizeof(a) / sizeof(a[0]))
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.print(datestring);
}
执行结果
