前言
ESP8266基于Arduino IDE的DS1302时钟模块使用,的过程记录。DS1302时钟模块就不详细介绍了,网上还是有很多资料的,这里只说如何快速上手。
下载文件
如果你还没有安装相对应的库文件可以看看下面的步骤。
-
点击工具,在点击管理库。
-
搜索栏中输入DS1302,就能找到我们想要的库
Rtc by Makuna
安装即可。通过库下面的介绍,知道这个库还能用DSxxx系列的其它芯片,不过我们本次以学习DS1302为主。
代码理解
以下是对官方例程的注释翻译,和加上了些自我理解的注释。当然,只要安装了上述库,直接放到xxx.ino
文件编译上传也是可以用的。连线方式数字是GPIO口,当然也写了对应些开发板上的Dx口的连接。
// 连线方式:
// DS1302 CLK/SCLK --> 5 --> D1
// DS1302 DAT/IO --> 4 --> D2
// DS1302 RST/CE --> 2 --> D4
// DS1302 VCC --> 3.3v - 5v
// DS1302 GND --> GND
#include <ThreeWire.h>
#include <RtcDS1302.h>
ThreeWire myWire(4,5,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
void setup ()
{
Serial.begin(115200);
Serial.print("compiled: ");
Serial.print(__DATE__);
Serial.println(__TIME__);
Rtc.Begin();
//程序下载编译时,自动把系统时间定义进结构变量中
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
printDateTime(compiled);
Serial.println();
//设定时间
//Rtc.SetDateTime(compiled);
//判断DS1302是否收到数据
if (!Rtc.IsDateTimeValid())
{
//常见原因:
// 1)第一次运行时,设备还没有运行
// 2)设备电量不足,甚至电量缺失
Serial.println("RTC对DateTime失去了信心!");
//设定时间
Rtc.SetDateTime(compiled);
}
//获取RTC写保护状态
if (Rtc.GetIsWriteProtected())
{
Serial.println("RTC被写入保护,现在允许写入");
Rtc.SetIsWriteProtected(false);
}
//获取RTC是否在运行
if (!Rtc.GetIsRunning())
{
Serial.println("RTC并没有积极运作,现在开始运行");
Rtc.SetIsRunning(true);
}
RtcDateTime now = Rtc.GetDateTime();
if (now < compiled)
{
Serial.println("RTC比编译时更老!(更新DateTime)");
Rtc.SetDateTime(compiled);
}
else if (now > compiled)
{
Serial.println("RTC比编译时更新。(这是意料之中的)");
}
else if (now == compiled)
{
Serial.println("RTC和编译时是一样的!(出乎意料,但一切都很好)");
}
}
void loop ()
{
//获取时间
RtcDateTime now = Rtc.GetDateTime();
printDateTime(now);
Serial.println();
if (!now.IsValid())
{
//常见原因:
// 1)设备电池电量不足,甚至丢失,电源线断开
Serial.println("RTC对DateTime失去了信心!”)");
}
delay(1000); // 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);
}
实际测试
不过在实践中,串口窗口不管是打印官方原注释中的英文,还是打印我翻译过的中文都是处于,乱码状态,不过时间的打印是正常输出的,时钟设置是正常可以使用的。(我用的VScode+Arduino IDE编辑,只用Arduino IDE也是行的)
还有关于时间设定,只要按照RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
的规定的格式来传入指定参数,在通过Rtc.SetDateTime(compiled);
设定就行了。