from machine import Pin, PWM, time_pulse_us
from time import sleep_ms, sleep_us
rf_A = Pin(18, Pin.IN, Pin.PULL_DOWN)
rf_B = Pin(19, Pin.IN, Pin.PULL_DOWN)
rf_C = Pin(20, Pin.IN, Pin.PULL_DOWN)
rf_D = Pin(13, Pin.IN, Pin.PULL_DOWN)
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
servo = PWM(Pin(11))
servo.freq(50)
angle = 90
def set_angle(a):
global angle
angle = max(0, min(180, a))
servo.duty_u16(int((0.4 + angle / 180 * 2.1) / 20 * 65535))
def read_distance_cm():
trig.value(1)
sleep_us(10)
trig.value(0)
t = time_pulse_us(echo, 1, 30000)
return t * 0.0343 / 2 if t > 0 else None
set_angle(90)
print("Ready.")
last_C = 0
last_D = 0
last_motion = 0
while True:
A, B, C, D = rf_A.value(), rf_B.value(), rf_C.value(), rf_D.value()
if D and not last_D:
set_angle(90)
print("Back to normal position")
if C and not last_C:
d = read_distance_cm()
print("Object detected in front:", round(d, 1), "cm") if d and d <= 30 else print("No object in front")
motion = 1 if A and not B and not D else 2 if B and not A and not D else 0
if motion and motion != last_motion:
print("Moving Left.." if motion == 1 else "Moving Right..")
if motion:
set_angle(angle - 1 if motion == 1 else angle + 1)
last_motion, last_C, last_D = motion, C, D
sleep_ms(40)