#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal_I2C.h>
#define backlightButton 2
LiquidCrystal_I2C lcd(0x27, 16, 2);// ref: datasheet
RTC_DS3231 rtc;
String msg; String mode_Msg;
void setup() {
Serial.begin(9600);
Wire.begin(); //to ensure I2C bus is properly initialized before any communication takes place.
lcd.begin(16, 2); //lcd.backlight();
// Initialize RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1); delay(10);
} if (rtc.lostPower()) { Serial.println("RTC lost power, let's set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
/////-----IMPORTANT ----------------------//
// Uncomment the next line on the first run to set the correct time
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
pinMode(backlightButton, INPUT_PULLUP);
}
void loop() {
DateTime now = rtc.now();
int currentHour = now.hour(); int currentMin = now.minute(); int currentSec = now.second();
int currentDay = now.day(); int currentMonth = now.month(); int currentYear = now.year();
int temp = rtc.getTemperature();
int dayOfWeek = now.dayOfTheWeek(); //index to match a representation where Sunday is 1.
//--------Clock function end ----------------------
if(digitalRead(backlightButton)==LOW) { lcd.backlight(); }
if(digitalRead(backlightButton)==HIGH){ lcd.noBacklight();}
lcd.clear(); lcd.setCursor(0, 0);// clear screen & start at upper row
printLcd(0, 0, String(currentHour)); printLcd(2, 0, ":");
printLcd(3, 0, String(currentMin)); printLcd(5, 0, ":");
printLcd(6, 0, String(currentSec));
printLcd(9, 0, String(currentDay) + monthToString(currentMonth) + String(currentYear % 100));
//---- LCD TOP ROW ----ENDS
//----- LCD Bottom row ------start
printLcd(0, 1, dayToString(dayOfWeek));
printLcd(4, 1, msg);
printLcd(9, 1, String(temp - 3)); // to subtrack heat inside the box
printLcd(11, 1, "C");
printLcd(13, 1, mode_Msg);
// ----- LCD Bottom row -----end
delay(1000); //delay for stability-- IMPORTANT
}
void printLcd (int shuru, int sesh, String myWords) { // For LCD Display
lcd.setCursor(shuru, sesh); lcd.print(myWords);
}
String monthToString(int month) {
switch (month) {
case 1: return "Jan"; case 2: return "Feb"; case 3: return "Mar";
case 4: return "Apr"; case 5: return "May"; case 6: return "Jun";
case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep";
case 10: return "Oct"; case 11: return "Nov"; case 12: return "Dec";
default: return "";
}
}
String dayToString(int theDay) {
switch (theDay) {
case 0: return "Sun"; case 1: return "Mon"; case 2: return "Tue";
case 3: return "Wed"; case 4: return "Thu"; case 5: return "Fri";
case 6: return "Sat"; default: return "Invalid day";
}
}//--------