from machine import Pin, PWM, time_pulse_us
import time
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
servo = PWM(Pin(13), freq=50)
def open_gate():
servo.duty(115) # ~90 degrees (open)
def close_gate():
servo.duty(40) # 0 degrees (closed)
def get_distance_cm():
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
duration = time_pulse_us(ECHO, 1, 30000)
if duration < 0:
return None
distance = (duration * 0.0343) / 2
return distance
close_gate()
while True:
dist = get_distance_cm()
if dist is not None:
print("Distance:", dist, "cm")
if dist < 10:
print("Object detected - opening gate")
open_gate()
time.sleep(3)
close_gate()
time.sleep(0.5)