#include <LiquidCrystal.h>
#include "RTClib.h"
LiquidCrystal lcd(12,11,10,9,8,7);
RTC_DS1307 rtc;

int buttonSEC = A0;
int buttonMIN = A1;
int buttonHOUR = A2;
int mSEC = 0;
int mMIN = 0;
int mHOUR = 0;

char ch_imena[4][10] ={
  "",
  "URE",
  "MIN",
  "SEC"
};

int marker = 0;
int alarm = 0;

void setup() {
  lcd.begin(16,2);
  rtc.begin();
  pinMode(buttonSEC, INPUT_PULLUP);
  pinMode(buttonMIN, INPUT_PULLUP);
  pinMode(buttonHOUR, INPUT_PULLUP);
  pinMode(13, OUTPUT);
}

void loop() {
  marker=0;
  if(digitalRead(buttonHOUR) == LOW){
    mHOUR++;
    if(mHOUR >= 24) mHOUR = 0;
    marker = 1;
    delay(50);
  }
  if(digitalRead(buttonMIN) == LOW){
    mMIN++;
    if(mMIN >= 60) mMIN = 0;
    marker = 2;
    delay(50);
  }
  if(digitalRead(buttonSEC) == LOW){
    mSEC++;
    if(mSEC >= 60) mSEC = 0;
    marker = 3;
    delay(50);
  } 

  char * ime = ch_imena[marker];

  textPrint(mSEC, mMIN, mHOUR, ime);
  delay(200);
  
}

void textPrint (int x, int y, int z, char *ime){
  lcd.clear();
  lcd.setCursor(0,1);
  lcd.print(ime);
  if(alarm){
    lcd.setCursor(0,0);
    lcd.print("ALARM");
  }
  char str[8];
  sprintf(str, "%02d:%02d:%02d", z, y, x);
  lcd.setCursor(7,1);
  lcd.print(str);
  ura();
}


void ura(){
  
  DateTime now = rtc.now();
  int ure = now.hour();
  int minute = now.minute();
  int sekunde = now.second();
  char ura[14];
  sprintf (ura, "%02d:%02d:%02d ", ure, minute, sekunde);
  lcd.setCursor(7,0);
  lcd.print(ura);
  if(sekunde == mSEC && minute == mMIN && ure == mHOUR){
    alarm = HIGH;
  }
  else if (alarm && (sekunde > (mSEC +15))) alarm = LOW;
  digitalWrite(13, alarm);

}
GND5VSDASCLSQWRTCDS1307+