#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
// --------------------------------
// --------------------------------
LiquidCrystal_I2C lcd(0x27, 16, 2);
RTC_DS1307 rtc;
int PlusPin = 7;
int MinusPin = 6;
int ChangePin = 5;
DateTime now;
int second;
int minute;
int hour;
int day;
int month;
int year;
int mode = 0;
int adjustingValue = 0;
String types[] = {" ", "hours ", "minutes", "seconds", "days ", "months ", "years "};
// --------------------------------
// --------------------------------
//function that sets correct number format for date -> 23=23 9=09
String formatTime(int num){
return num < 10 ? "0" + String(num) : String(num);
}
// update to current time
void UpdateTime(){
now = rtc.now();
second = now.second();
minute = now.minute();
hour = now.hour();
day = now.day();
month = now.month();
year = now.year();
}
// handle date changing by pressing buttons
int Change(int num, int max, int min = 0){
if (!digitalRead(PlusPin)){
num += 1;
if (num > max) num = min;
}
if (!digitalRead(MinusPin)){
num -= 1;
if (num < min) num = max;
}
return num;
}
// wait after push button press
void DelayAfterButtonPress(int time = 100){
if (!digitalRead(PlusPin) || !digitalRead(MinusPin) || !digitalRead(ChangePin)){
delay(time);
}
}
// handle actions for each mode
void HandleModes(){
if (mode != 0){
lcd.setCursor(0,0);
lcd.print("adjust: ");
if (mode < 7) lcd.print(types[mode]);
lcd.setCursor(0,1);
lcd.print((String(adjustingValue) + " "));
}
if (mode == 0){
UpdateTime();
String line1 = formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second) + " ";
String line2 = formatTime(day) + "." + formatTime(month) + "." + year;
//show on display
lcd.setCursor(0,0);
lcd.print(line1);
lcd.setCursor(0,1);
lcd.print(line2);
}
else if (mode == 1){
hour = Change(hour, 23, 0);
adjustingValue = hour;
}
else if (mode == 2){
minute = Change(minute, 59, 0);
adjustingValue = minute;
}
else if (mode == 3){
second = Change(second, 59, 0);
adjustingValue = second;
}
else if (mode == 4){
day = Change(day, 31, 1);
adjustingValue = day;
}
else if (mode == 5){
month = Change(month, 12, 1);
adjustingValue = month;
}
else if (mode == 6){
year = Change(year, 9999, 0);
adjustingValue = year;
}
else if (mode == 7){
mode = 0;
rtc.adjust(DateTime(year, month, day, hour, minute, second));
}
}
// when change button pressed (yellow button)
void OnChangeButtonPress(){
if (!digitalRead(ChangePin)){
mode += 1;
}
}
// --------------------------------
// --------------------------------
void setup() {
pinMode(PlusPin, INPUT_PULLUP);
pinMode(MinusPin, INPUT_PULLUP);
pinMode(ChangePin, INPUT_PULLUP);
lcd.init();
lcd.backlight();
rtc.begin();
UpdateTime();
}
void loop() {
HandleModes();
OnChangeButtonPress();
DelayAfterButtonPress();
}