"""
IR sensor: helps the robot stay on the path (like a black line).
Ultrasonic sensor: detects obstacles in front and stops or turns the robot.
Together: the robot follows the path safely without crashing into anything.
"""
from machine import Pin, time_pulse_us
from time import sleep
# --- Ultrasonic Pins ---
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
# --- IR Sensor Pin ---
ir_sensor = Pin(15, Pin.IN)
SOUND_SPEED = 0.0343 # cm/us
def read_distance():
trigger.low()
sleep(0.002)
trigger.high()
sleep(0.01)
trigger.low()
duration = time_pulse_us(echo, 1, 30000)
distance = (duration * SOUND_SPEED) / 2
return distance
while True:
dist = read_distance()
ir_state = ir_sensor.value()
print("Distance: {:.2f} cm | IR Sensor: {}".format(dist, ir_state))
if dist < 20:
print("⚠️ Obstacle too close!")
if ir_state == 0:
print("⚠️ Line detected!")
sleep(0.5)