Skip to content

Instantly share code, notes, and snippets.

@endlessdev
Created May 31, 2017 06:24
Show Gist options
  • Save endlessdev/c7d310347aab198357992470126de88f to your computer and use it in GitHub Desktop.
Save endlessdev/c7d310347aab198357992470126de88f to your computer and use it in GitHub Desktop.
RTC(Real Time Clock) Module - 아두이노, 1602 캐릭터 LCD, RTC Module를 사용하여 ▪ 현재 날짜와 요일 시간을 모두 표시하는 탁상시계를 제작하시오.
#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!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment