#include <LiquidCrystal_I2C.h>
#include <DHT22.h>

#define motionOutput 2
#define ledInput 7
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
#define dht22Pin 6
#define triger A2
#define echo A1
#define ldrPin 3

LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
DHT22 dht22(dht22Pin);

void setup() {
  // put your setup code here, to run once:
  pinMode(motionOutput , INPUT);
  pinMode(ledInput , OUTPUT);
  pinMode(echo , INPUT);
  pinMode(triger , OUTPUT);
  pinMode(ldrPin , INPUT);

  lcd.init();
  lcd.backlight();
}

float readDistanceCM() {
  digitalWrite(triger, LOW);
  delayMicroseconds(2);
  digitalWrite(triger, HIGH);
  delayMicroseconds(2);
  digitalWrite(triger, LOW);
  int duration = pulseIn(echo, HIGH);
  return duration * 0.034 / 2;
}


void loop() {
  // put your main code here, to run repeatedly:
  // Start a new measurement:
  digitalWrite(triger, LOW);
  delayMicroseconds(2);
  digitalWrite(triger, HIGH);
  delayMicroseconds(2);
  digitalWrite(triger, LOW);

  // Read the result:

  int duration = pulseIn(echo, HIGH);
  lcd.setCursor(0 , 2);
  lcd.print("Dis CM:");
  lcd.print(duration/58);
  lcd.print(" inches:");
  lcd.print(duration / 148);
  lcd.setCursor(0 , 3);
  // lcd.print("Tnx Nafi vai & Sopon");
  lcd.print("Room: ");
  if (digitalRead(ldrPin) == LOW) {
    lcd.print("Light!");
  } else {
    lcd.print("Dark  ");
  }

  float t = dht22.getTemperature();
  float h = dht22.getHumidity();
  lcd.setCursor(0 , 1);
  lcd.print("T: ");
  lcd.print(t);
  lcd.print(" H: ");
  lcd.print(h);
  int st = 0;
  if(t > 40.0) st = 1;
  if(digitalRead(motionOutput)){
    lcd.setCursor(2 , 0);
    lcd.print("Motion Detected!");
    if(st == 1){
      digitalWrite(ledInput , HIGH);
    }   
  }
  else{
    lcd.setCursor(0 , 0);
    lcd.print("Failed!             ");
    digitalWrite(ledInput , LOW);
  }
}