#include <Servo.h>

Servo myServo;

const int trigPinIn = 2;    // Pin trigger sensor ultrasonik masuk
const int echoPinIn = 3;    // Pin echo sensor ultrasonik masuk
const int trigPinOut = 4;   // Pin trigger sensor ultrasonik keluar
const int echoPinOut = 5;   // Pin echo sensor ultrasonik keluar
const int servoPin = 9;     // Pin servo motor
const int relayPin1 = 8;    // Pin modul relay lampu 1
const int pirPin1 = 7;      // Pin PIR sensor 1
const int lampuPin1 = 6;    // Pin lampu 1
const int relayPin2 = 12;   // Pin modul relay lampu 2
const int pirPin2 = 11;     // Pin PIR sensor 2
const int lampuPin2 = 10;   // Pin lampu 2

void setup() {
  Serial.begin(9600);
  myServo.attach(servoPin);
  pinMode(trigPinIn, OUTPUT);
  pinMode(echoPinIn, INPUT);
  pinMode(trigPinOut, OUTPUT);
  pinMode(echoPinOut, INPUT);
  pinMode(relayPin1, OUTPUT);
  pinMode(pirPin1, INPUT);
  pinMode(lampuPin1, OUTPUT);
  pinMode(relayPin2, OUTPUT);
  pinMode(pirPin2, INPUT);
  pinMode(lampuPin2, OUTPUT);
}

void loop() {
  if (detectPerson(trigPinIn, echoPinIn) || detectPerson(trigPinOut, echoPinOut)) {
    openDoor();
    delay(5000);
    closeDoor();
  }

  if (digitalRead(pirPin1) == HIGH) {
    turnOnLight1();
    delay(2000); // Tahan lampu menyala selama 2 detik (ubah sesuai kebutuhan)
    turnOffLights();
  }

  if (digitalRead(pirPin2) == HIGH) {
    turnOnLight2();
    delay(2000); // Tahan lampu menyala selama 2 detik (ubah sesuai kebutuhan)
    turnOffLights();
  }
}

bool detectPerson(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  int distance = duration * 0.034 / 2;

  return (distance < 100); // Ubah angka sesuai kebutuhan jarak deteksi
}

void openDoor() {
  myServo.write(180);
  digitalWrite(relayPin1, HIGH);
  digitalWrite(relayPin2, HIGH);
}

void closeDoor() {
  myServo.write(0);
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
}

void turnOnLight1() {
  digitalWrite(lampuPin1, HIGH);
  digitalWrite(relayPin1, HIGH);
}

void turnOnLight2() {
  digitalWrite(lampuPin2, HIGH);
  digitalWrite(relayPin2, HIGH);
}

void turnOffLights() {
  digitalWrite(lampuPin1, LOW);
  digitalWrite(lampuPin2, LOW);
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
}
NOCOMNCVCCGNDINLED1PWRRelay Module