from machine import time_pulse_us , Pin , PWM
import time
#define the trig and Echo PIn
TRIG_PIN = 14
ECHO_PIN = 12
PWM_PIN= 26
trig = Pin(TRIG_PIN,Pin.OUT)
echo = Pin(ECHO_PIN,Pin.IN)
servo = PWM(PWM_PIN,freq = 50)
def get_distance():
trig.value(1)
time.sleep_ms(10)
trig.value(0)
#wait to recieve
duration = time_pulse_us(echo,1,300000)
#calculate distance in cm
distance = (duration * 0.0343) // 2
return distance
def move_servo(distance):
servo.duty(distance)
while True:
obj_distance = round(get_distance())
move_servo(obj_distance)