#define ECHO_PIN 3
#define TRIG_PIN 2
#define pinBuzzer 11
#define lampu 13

#include <Servo.h>

Servo myservo;

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

void setup(){
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(115200);
  pinMode(pinBuzzer, OUTPUT);
  pinMode(lampu, OUTPUT);
  myservo.attach(10);
}

void loop(){
  float orang = readDistanceCM();
  Serial.print("Jarak: ");
  Serial.println(readDistanceCM());

  if(orang <= 50 and orang >= 40){
    myservo.write(90);
    tone(pinBuzzer, 500);
    digitalWrite(lampu, LOW);
    Serial.println("Pintu Terbuka");
    delay(2000);
  }

  else if (orang < 40){
    myservo.write(0);
    noTone(pinBuzzer);
    digitalWrite(lampu, HIGH);
    Serial.println("Orang sudah masuk ruangan");
    delay(1000);
  }

  else {
    myservo.write(0);
    noTone(pinBuzzer);
    digitalWrite(lampu, LOW);
    Serial.println("Orang jauh dari pintu");
    delay(2000);
  }
}