#include <DHT.h>

#define DHTPIN 33
#define DHTTYPE DHT22
#define ECHO_PIN 2
#define TRIG_PIN 4
#define pir 35
#define ledm 22
#define ledh 21
#define ledb 19
#define ledk 18
#define ledu 15

DHT dht(DHTPIN, DHTTYPE);
long durasi;
int jarak;
float h;
float t;

void setup()
 {
  dht.begin();
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(pir, INPUT);
  pinMode(ledm, OUTPUT);
  pinMode(ledh, OUTPUT);
  pinMode(ledb, OUTPUT);
  pinMode(ledk, OUTPUT);
  pinMode(ledu, OUTPUT);
  Serial.begin(115200);
  awal(); // Matikan semua lampu saat awalnya
  delay(5000);
}

void loop() 
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  durasi = pulseIn(ECHO_PIN, HIGH);
  jarak = durasi * 0.034 / 2;
  
  h = dht.readHumidity();
  t = dht.readTemperature();

  // Deteksi gerakan PIR
  int motionDetected = digitalRead(pir);
  if (motionDetected == HIGH) {
    motionpir();
  }
  if (t > 25) {
    detectsuhu();
  }
  if (h > 20) {
    detectsuhu();
  }
  if (jarak > 120) {
    detectjarak();
  }
  if (t < 25 && h < 20 ) {
    detect2sensor();
  }
  if ( t < 25 && h < 20 && jarak < 120) {
    awal();
  }
  // Tambahkan delay sesuai kebutuhan agar tidak terlalu cepat berulang
  delay(1000); // Delay 1 detik
}

void awal() {
  Serial.print("Suhu: ");
  Serial.println(t);
  Serial.print("Kelembapan: "); 
  Serial.println(h);
  Serial.print("Jarak: ");
  Serial.println(jarak);
  digitalWrite(ledm, LOW);
  digitalWrite(ledh, LOW);
  digitalWrite(ledb, LOW);
  digitalWrite(ledk, LOW);
  digitalWrite(ledu, LOW);
}

void motionpir() {
  digitalWrite(ledm, HIGH);
  delay(500);
  digitalWrite(ledm, LOW);
  delay(500);
}

void detectsuhu() {
  Serial.print("Suhu: ");
  Serial.println(t);
  digitalWrite(ledh, HIGH);
  delay(500);
  digitalWrite(ledh, LOW);
  delay(500);
}

void detectkelembapan() {
  Serial.print("Kelembapan: "); 
  Serial.println(h);
  digitalWrite(ledb, HIGH);
  delay(500);
  digitalWrite(ledb, LOW);
  delay(500);
}

void detectjarak() {
  Serial.print("Jarak: ");
  Serial.println(jarak);
  digitalWrite(ledk, HIGH);
  delay(500);
  digitalWrite(ledk, LOW);
  delay(500);
}

void detect2sensor() {
  Serial.print("Suhu: ");
  Serial.println(t);
  Serial.print("Kelembapan: "); 
  Serial.println(h);
  digitalWrite(ledu, HIGH);
  delay(500);
  digitalWrite(ledu, LOW);
  delay(500);
}