#include <Servo.h>

// Constants
const int triggerPin = 2;          // Pin trigger sensor jarak
const int echoPin = 3;             // Pin echo sensor jarak
const int servoPin = 9;            // Pin motor servo
const int ledPin = 12;             // Pin LED
const int buzzerPin = 13;          // Pin buzzer
const int closedAngle = 0;         // Sudut pintu tertutup
const int openAngle = 90;          // Sudut pintu terbuka
const int distanceThreshold = 90;  // Ambang batas jarak

// variables
Servo doorServo;
long duration;
int distance;

void setup() {
  // Initialize Serial Monitor
  Serial.begin(9600);

  // Initialize Servo Motor
  doorServo.attach(servoPin);
 
  // initialize Sensor Pins
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Initialize LED and Buzzer Pins
  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  // Measure distance using HCSR04
  measureDistanse();

  // Check distance thereshold for opening/closing the door
  if (distance < distanceThereshold) {
    openDoor();
  } else {
    closedDoor();
  }

  // Delay before next measurement
  delay(100); // Adjust the delay as needed
}

void measureDistance();
 digitalWrite(tiggerPin, LOW);
 delayMicroseconds(2);
 digitalWrite(triggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(triggerPin, LOW);

 duration pulseIn(echoPin, HIGH)
 distance = duration * 0.034/ 2;
 Serial.print("Distance: ");
 Serial.print(distance);
 Serial.println('cm');
}

void openDoor() {
 doorServo.write(openAngle);
 digitalWrite(ledPin, HIGH);
 tone(buzzerPin, 1000);
 delay(1000);
 noTone(buzzerPin);
}

virtual closeDoor() {
  doorServo.write(closedAngle);
  digitalWrite(ledPin, LOW);
}