目录
芯片pinout:
实验器件:
实验连线
解决AVR 架构不支持 printf() 方法
使用GetTimeAndDate.ino设置时间:
使用SetTimeAndDate.ino设置时间:
芯片pinout:
DS1307 是美国 DALLAS 公司推出的 I 总线接口实时时钟芯片,它可独立于 CPU 工作,不受 CPU主品振及其电容的影响,且计时准确,月累积误差一般小于 10秒。芯片还具有主电源掉电情况下的时钟保护电路,DS1307的时钟靠后备电池维持工作,拒绝 CPU 对其读出和写入访问。同时还具有备用电源自动切换控制电路,因而可在主电源掉电和其它些恶劣环境场合中保证系统时钟的定时准确性DS1307 具有产生秒、分、时、曰、月、年等功能,且具有闰年自动调整功能。
-
实验器件:
■ DS1307:1 个
■ 无源晶振:32.768K 1个
■ 多彩面包板实验跳绳:若干
-
实验连线
SCL-A5
SDA-A4
SQW/OUT-悬空
-
解决AVR 架构不支持 printf() 方法
- AVR 架构限制:传统的 Arduino 板(如 Uno、Nano)默认的 Serial 对象(属于 HardwareSerial 类)不支持 printf() 方法。
- ESP32/ESP8266 支持:部分开发板(如 ESP32、ESP8266)的 Serial 类已扩展了 printf(),可直接使用。
增加库:
#include <Bonezegei_Printf.h>
增加代码:
//param Stream
Bonezegei_Printf debug(&Serial);
使用示例:
debug.printf("Time %02d:%02d:%02d ", rtc.getHour(), rtc.getMinute(), rtc.getSeconds());
没有DS1307的库需先安装库文件:Bonezegei_DS1307和Bonezegei_Printf
- 设置时间和读取时间代码
使用GetTimeAndDate.ino设置时间:
/*Get Time And DateAuthor: Bonezegei (Jofel Batutay)Date: Feb 2024*/#include <Bonezegei_DS1307.h>#include <Bonezegei_Printf.h>//param StreamBonezegei_Printf debug(&Serial);Bonezegei_DS1307 rtc(0x68);void setup() {Serial.begin(115200);rtc.begin();}void loop() {if (rtc.getTime()) {debug.printf("Time %02d:%02d:%02d ", rtc.getHour(), rtc.getMinute(), rtc.getSeconds());if (rtc.getFormat() == 12) { // returns 12 or 24 hour formatif (rtc.getAMPM()) { //return 0 = AM 1 =PMSerial.print("AM ");} else {Serial.print("PM ");}}debug.printf("Date %02d-%02d-%d \n", rtc.getMonth(), rtc.getDate(), rtc.getYear());}delay(1000);}
使用SetTimeAndDate.ino设置时间:
/*Set Time And DateAuthor: Bonezegei (Jofel Batutay)Date: Feb 2024*/#include <Bonezegei_DS1307.h>#include <Bonezegei_Printf.h>//param StreamBonezegei_Printf debug(&Serial);Bonezegei_DS1307 rtc(0x68);void setup() {Serial.begin(115200);rtc.begin();rtc.setFormat(24); //Set 12 Hours Formatrtc.setAMPM(1); //Set AM or PM 0 = AM 1 =PMrtc.setTime("21:18:00"); //Set Time Hour:Minute:Secondsrtc.setDate("3/20/25"); //Set Date Month/Date/Year}void loop() {if (rtc.getTime()) {debug.printf("Time %02d:%02d:%02d ", rtc.getHour(), rtc.getMinute(), rtc.getSeconds());if (rtc.getFormat() == 12) { // returns 12 or 24 hour formatif (rtc.getAMPM()) { //return 0 = AM 1 = PMSerial.print("PM ");} else {Serial.print("AM ");}}debug.printf("Date %02d-%02d-%d \n", rtc.getMonth(), rtc.getDate(), rtc.getYear());}delay(1000);}
注意:使用中电源不能断开,否则重新上电后从初始开始显示:
Time 00:00:10 Date 01-01-0,单独芯片不具备时间存储功能。