#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);
int jam, menit, detik, tanggal, bulan, tahun, hari;
char temp[60];
char nama_hari[7][12] = {"Minggu", "Sen", "Sel", "Rabu", "Kamis", "Jumat", "Sabtu"};
const int btnMode = 4;
const int btnUp = 16;
const int btnSet = 17;
int settingMode = 0;
bool setting = false;
// Variabel sementara saat setting
int set_jam, set_menit, set_tanggal, set_bulan, set_tahun;
void setup() {
pinMode(btnMode, INPUT_PULLUP);
pinMode(btnUp, INPUT_PULLUP);
pinMode(btnSet, INPUT_PULLUP);
lcd.init(); lcd.backlight();
lcd.setCursor(0, 0); lcd.print("JAM DIGITAL");
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
lcd.setCursor(0, 1); lcd.print("RTC Error");
while (1);
} else {
Serial.println("RTC OK");
lcd.setCursor(0, 1); lcd.print("RTC OK");
}
delay(2000);
lcd.clear();
}
void loop() {
static unsigned long lastDebounce = 0;
// Tombol Mode
if (digitalRead(btnMode) == LOW && millis() - lastDebounce > 200) {
if (!setting) {
// Masuk mode pengaturan, salin dari RTC
DateTime now = rtc.now();
set_jam = now.hour();
set_menit = now.minute();
set_tanggal = now.day();
set_bulan = now.month();
set_tahun = now.year();
setting = true;
settingMode = 1;
} else {
// Ganti field yang sedang diatur
settingMode++;
if (settingMode > 5) settingMode = 1;
}
lastDebounce = millis();
}
// Tombol Up
if (setting && digitalRead(btnUp) == LOW && millis() - lastDebounce > 200) {
switch (settingMode) {
case 1: set_jam = (set_jam + 1) % 24; break;
case 2: set_menit = (set_menit + 1) % 60; break;
case 3: set_tanggal = (set_tanggal % 31) + 1; break;
case 4: set_bulan = (set_bulan % 12) + 1; break;
case 5: set_tahun++; break;
}
lastDebounce = millis();
}
// Tombol Set
if (setting && digitalRead(btnSet) == LOW && millis() - lastDebounce > 200) {
rtc.adjust(DateTime(set_tahun, set_bulan, set_tanggal, set_jam, set_menit, 0));
setting = false;
settingMode = 0;
lastDebounce = millis();
}
// Tampilan
if (setting) {
// Tampilkan data sementara
sprintf(temp, "%02d:%02d:%02d SET", set_jam, set_menit, 0);
lcd.setCursor(2, 0); lcd.print(temp);
sprintf(temp, "%02d/%02d/%04d", set_tanggal, set_bulan, set_tahun);
lcd.setCursor(0, 1); lcd.print(temp);
} else {
// Mode normal
DateTime now = rtc.now();
jam = now.hour();
menit = now.minute();
detik = now.second();
tanggal = now.day();
bulan = now.month();
tahun = now.year();
hari = now.dayOfTheWeek();
sprintf(temp, "%02d:%02d:%02d WIB", jam, menit, detik);
lcd.setCursor(2, 0); lcd.print(temp);
sprintf(temp, "%s %02d:%02d:%d", nama_hari[hari], tanggal, bulan, tahun);
lcd.setCursor(0, 1); lcd.print(temp);
}
delay(100);
}