Skip to content

Instantly share code, notes, and snippets.

@endlessdev
Created May 31, 2017 06:24
Show Gist options
  • Select an option

  • Save endlessdev/c7d310347aab198357992470126de88f to your computer and use it in GitHub Desktop.

Select an option

Save endlessdev/c7d310347aab198357992470126de88f to your computer and use it in GitHub Desktop.

Revisions

  1. endlessdev renamed this gist May 31, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. endlessdev created this gist May 31, 2017.
    85 changes: 85 additions & 0 deletions sketch_study_1_RTC
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <DS1302RTC.h>

    #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!");
    }