#include "DHT.h"
#include "RTClib.h"
#include <LiquidCrystal_I2C.h>

#define thpin 4
#define typedht DHT22

DHT th(thpin, typedht);
RTC_DS1307 rtc;
LiquidCrystal_I2C l(0x27, 20, 4);


char daysOfTheWeek[7][12] = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup() {
  th.begin();
  l.begin(20, 4);
  //l.backlight();
  l.setCursor(0,1);
  l.print("Temperature: ");
  l.setCursor(0,2);
  l.print("Humidity: ");
  l.setCursor(17,0);
  l.print(":");
  if (! rtc.begin()) 
  {
    l.setCursor(0,0);
    l.print("Error Clock");
  }
}

void loop() 
{
  DateTime now = rtc.now();
  int t=th.readTemperature();
  int h=th.readHumidity();
  if(isnan(t)||isnan(h))
  {
    l.setCursor(12,1);
    l.print("Err");
    l.setCursor(9,2);
    l.print("Err");    
  }
  if(t>=0 && t<10){
    l.setCursor(12,1);
    l.print(t);
    l.setCursor(13,1);
    l.print("C  ");
  }
  else if(t>=-9 && t<100){
    l.setCursor(12,1);
    l.print(t);
    l.setCursor(14,1);
    l.print("C ");
  }
  else if(t<=-10){
    l.setCursor(12,1);
    l.print(t);
    l.setCursor(15,1);
    l.print("C");
  }
  else{
    l.setCursor(12,1);
    l.print("Error");
  }
  if(h<10)
  {
    l.setCursor(9,2);
    l.print(h);
    l.setCursor(10,2);
    l.print("%  ");
  }
  else if(h>=10 && h < 100)
  {
    l.setCursor(9,2);
    l.print(h);
    l.setCursor(11,2);
    l.print("% ");
  }
  else if(h==100)
  {
    l.setCursor(9,2);
    l.print(h);
    l.setCursor(12,2);
    l.print("%");
  }
  l.setCursor(0,0);
  l.print(daysOfTheWeek[now.dayOfTheWeek()]);
  l.setCursor(15,0);
  l.print(now.hour(),DEC);
  if(now.minute()<10){
    l.setCursor(17,0);
    l.print("0");
    l.setCursor(18,0);
    l.print(now.minute(),DEC);
  }
  else{
    l.setCursor(18,0);
    l.print(now.minute(),DEC);
  }
}
GND5VSDASCLSQWRTCDS1307+