#include #include #include #include #include #define RST 2 // RST or CE #define DAT 3 // DAT or IO #define CLK 4 // CLK LiquidCrystal_I2C lcd(0x3F, 16, 2); DS1302RTC RTC(RST, DAT, CLK); tmElements_t tm; const char days[7][4] = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; void setup() { lcd.init(); // initialize the lcd lcd.backlight(); // turn on backlight Serial.begin(9600); setDateTime(); if (RTC.haltRTC()) { Serial.println("The DS1302 is stopped. Please run the SetTime"); Serial.println("example to initialize the time and begin running."); Serial.println(); } if (!RTC.writeEN()) { Serial.println("The DS1302 is write protected. This normal."); Serial.println(); } } unsigned long prevSec = 0; void loop() { unsigned long nowSec = millis() / 1000; if (prevSec != nowSec) { RTC.read(tm); outputDateTime(); prevSec = nowSec; } } void outputDateTime() { char dateStr[20]; char timeStr[20]; sprintf(dateStr, "%4d-%02d-%02d %s", tmYearToCalendar(tm.Year), tm.Month, tm.Day, days[tm.Wday-2]); sprintf(timeStr, "%s %02d:%02d:%02d", getCurrentAm(tm.Hour), getCurrentHour(tm.Hour), tm.Minute, tm.Second); lcd.setCursor(0, 0); lcd.print(dateStr); lcd.setCursor(1, 1); lcd.print(timeStr); } bool isAm(int hour){ return hour-12 < 0; } int getCurrentHour(int hour){ return isAm(hour) ? hour : hour-12; } char* getCurrentAm(int hour){ return isAm(hour) ? "AM" : "PM"; } void setDateTime() { time_t t; tm.Year = CalendarYrToTm(2017); tm.Month = 5; tm.Day = 31; tm.Hour = 14; tm.Minute = 41; tm.Second = 55; t = makeTime(tm); if (RTC.set(t) == 0) { // Success setTime(t); } else Serial.println("RTC set failed!"); }