库文件:https://github.com/msparks/arduino-ds1302
基本使用:
设置时间:
#include <stdio.h>
#include <DS1302.h>
namespace {
const int kCePin = 5; // 复位引脚
const int kIoPin = 6; // 数据引脚
const int kSclkPin = 7; // 时钟引脚
DS1302 rtc(kCePin, kIoPin, kSclkPin);
String dayAsString(const Time::Day day) {
switch (day) {
case Time::kSunday: return "Sunday";
case Time::kMonday: return "Monday";
case Time::kTuesday: return "Tuesday";
case Time::kWednesday: return "Wednesday";
case Time::kThursday: return "Thursday";
case Time::kFriday: return "Friday";
case Time::kSaturday: return "Saturday";
}
return "(unknown day)";
}
void printTime() {
// 从模块获得当前时间
Time t = rtc.time();
// 星期几?
const String day = dayAsString(t.day);
// 格式化时间数据
char buf[50];
snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
day.c_str(),
t.yr, t.mon, t.date,
t.hr, t.min, t.sec);
Serial.println(buf);
}
} // namespace
void setup() {
Serial.begin(9600);
rtc.writeProtect(false);
rtc.halt(false);
// 设置初始时间为 2018-1-18,17:28:00 星期四
Time t(2018, 1, 18, 17, 28, 0, Time::kThursday);
rtc.time(t);
}
void loop() {
printTime();
delay(1000);
}
增加一个OLED显示
#include <stdio.h>
#include <DS1302.h>
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);
char buf[50];
char oled_buf[50]; // 用于在OLED上显示
namespace {
const int kCePin = 5; // 复位引脚
const int kIoPin = 6; // 数据引脚
const int kSclkPin = 7; // 时钟引脚
DS1302 rtc(kCePin, kIoPin, kSclkPin);
String dayAsString(const Time::Day day) {
switch (day) {
case Time::kSunday: return "Sunday";
case Time::kMonday: return "Monday";
case Time::kTuesday: return "Tuesday";
case Time::kWednesday: return "Wednesday";
case Time::kThursday: return "Thursday";
case Time::kFriday: return "Friday";
case Time::kSaturday: return "Saturday";
}
return "(unknown day)";
}
void printTime() {
// 从模块获得当前时间
Time t = rtc.time();
// 星期几?
const String day = dayAsString(t.day);
// 格式化时间数据
//char buf[50];
snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
day.c_str(),
t.yr, t.mon, t.date,
t.hr, t.min, t.sec);
snprintf(oled_buf, sizeof(oled_buf), "%04d-%02d-%02d %02d:%02d:%02d",
t.yr, t.mon, t.date,
t.hr, t.min, t.sec);
Serial.println(buf);
}
} // namespace
void init_oled(){
if ( u8g.getMode() == U8G_MODE_R3G3B2 )
u8g.setColorIndex(255); // white
else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
u8g.setColorIndex(3); // max intensity
else if ( u8g.getMode() == U8G_MODE_BW )
u8g.setColorIndex(1); // pixel on
u8g.setFont(u8g_font_6x10);
u8g.setFontRefHeightExtendedText();
u8g.setDefaultForegroundColor();
u8g.setFontPosTop();
}
void setup() {
Serial.begin(9600);
init_oled();
rtc.writeProtect(false);
rtc.halt(false);
// 设置初始时间为 2018-1-18,17:52:00 星期四
// Time t(2018, 1, 18, 17, 52, 0, Time::kThursday);
// rtc.time(t);
}
void loop() {
u8g.firstPage();
do {
u8g.drawStr(10,0,oled_buf);
} while( u8g.nextPage() );
delay(500);
printTime();
delay(500);
}