from machine import Pin, PWM, time_pulse_us
import time
trig = Pin(5, Pin.OUT)
echo = Pin(17, Pin.IN)
servo = PWM(Pin(18), freq=50)
print("System Active! Click the ultrasonic sensor and move the slider.")
while True:
# Trigger sensor
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
# Calculate distance
duration = time_pulse_us(echo, 1, 30000)
distance = (duration * 0.0343) / 2
# Print reading to terminal to debug
print(f"Current Distance: {distance:.1f} cm")
# Gate Action
if 0 < distance < 50:
print("-> GATE OPENING")
servo.duty(123)
time.sleep(3)
else:
servo.duty(26)
time.sleep(0.4)