import math
import time
from machine import Pin, PWM
pwm=PWM(Pin(1))
pwm.freq(50)
trigger_pin = Pin(2, Pin.OUT)
echo_pin = Pin(3, Pin.IN)
def measure_dist():
trigger_pin.low()
time.sleep_us(2)
trigger_pin.high()
time.sleep_us(10)
trigger_pin.low()
while echo_pin.value()==0:
pulse_start = time.ticks_us()
while echo_pin.value()==1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance_cm = (pulse_duration * 0.0340)/2
return round(distance_cm)
while True:
distance = measure_dist()
print("Distance:", distance, "cm")
if(distance<=100):
for position in range(1000, 9000, 50):
pwm.duty_u16(position)
time.sleep(0.01)
print("Gate Opened")
time.sleep(5)
for position in range(9000, 1000, -50):
pwm.duty_u16(position)
time.sleep(0.01)
print("Gate closed")
time.sleep(0.5)