#include <ESP32Servo.h>

const int spin = 16;       // Servo 腳位
const int TRIG_PIN = 26;   // 觸發腳 (Trig)
const int ECHO_PIN = 25;   // 回應腳 (Echo)
Servo sv;

float dis() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH); // 讀取超音波回應時間
  float distance = duration * 0.034 / 2;   // 計算距離 (cm)
  return distance;
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  sv.attach(spin, 500, 2400);        
}

void loop() {
  float distance = dis();   // 呼叫函數取得距離
  Serial.println("距離: " + String(distance) + " CM");

  
  if(distance < 90){
    sv.write(0);
    Serial.println("開門");
  }
  else{
    sv.write(90);
    Serial.println("關門");
  }

  delay(500);
}