from machine import Pin, PWM, time_pulse_us
from time import sleep, sleep_us
import motion
# Initialize pins inside the module
motion.init()
# === IR Sensor Setup ===
left_ir = Pin(18, Pin.IN)
center_ir = Pin(19, Pin.IN)
right_ir = Pin(20, Pin.IN)
# Ultrasonic sensor pins
TRIG = Pin(15, Pin.OUT) # Trigger pin
ECHO = Pin(14, Pin.IN) # Echo pin
def get_distance():
# Send 10µs pulse to trigger the sensor
TRIG.low()
sleep_us(2) # 2 µs delay before triggering pulse
TRIG.high()
sleep_us(10) # 10 µs pulse duration
TRIG.low()
# Measure the echo pulse duration to calculate distance
duration = time_pulse_us(ECHO, 1)
# Convert the duration to distance in cm
distance_cm = int((duration * 0.0343) / 2)
return distance_cm # Return the measured distance
# === Main Loop ===
while True:
left = left_ir.value()
center = center_ir.value()
right = right_ir.value()
# Get the distance from the ultrasonic sensor
dist = get_distance()
if dist < 10:
motion.stop()
else:
if center == 0:
motion.forward()
elif left == 0:
motion.left()
elif right == 0:
motion.right()
else:
motion.stop()
sleep(0.02) # Short delay to prevent rapid changes