#include <LiquidCrystal_I2C.h>
#define LED_PIN 32
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

#include "DHTesp.h"
#define DHT_PIN 15
#define PIR_SENSOR 12

DHTesp dhtSensor;

void setup() {
  //config LED_PIN output
  pinMode(LED_PIN, OUTPUT);

  //setup for serial communication
  Serial.begin(9600);
  Serial.print("ESP32 collecting sensors data");

  //setup for dht sensor
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(PIR_SENSOR, INPUT);

  lcd.init(); // initialize the lcd 
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("ESP32 collecting data ...");
  delay(1000);
  
}

void loop() {
  
  // Xoá màn hình LCD
  lcd.clear();
  lcd.setCursor(0,0);   // Đặt con trỏ lại dòng 0, vị trí 0

  // Nhận thông tin từ cảm biến nhiệt đô, độ ẩm
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  double temp = data.temperature;
  double humid = data.humidity;
  String stemp = String(temp) + ((char)0xDF) + "C";
  String shumid = String(humid) + "%";
  // In giá trị nhiệt độ và độ ẩm ra LCD
  lcd.print("Temp: ");   
  lcd.print(stemp);   
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(shumid);
  //delay(1000);
  //  In giá trị nhiệt độ và độ ẩm ra Serial Monitor
  Serial.println("Temp: " + stemp);
  Serial.println("Humidity: " + shumid);
  Serial.println("---");
  delay(1000);

  // Xử lý tín hiệu cảm biến chuyển động
  int pir_value = digitalRead(PIR_SENSOR);
  // Phát hiện chuyển động
  if(pir_value == 1){
    Serial.println("Motion detected");
    digitalWrite(LED_PIN, HIGH);
    Serial.println("LED ON");
    delay(100);

  }
  // Phát hiện chuyển động kết thúc
  else{
    Serial.println("Motion ended");
    digitalWrite(LED_PIN, LOW);
    Serial.println("LED OFF");
    delay(100);

  }

 // digitalWrite(LED_PIN, HIGH);
 // Serial.println("LED ON");
 // delay(500);
 // digitalWrite(LED_PIN, LOW);
 // Serial.println("LED OFF");
 // delay(500);
}