UnboundLocalError in Obstacle Detection with Ultrasonic Sensor Using MicroPython

Am working on a smart car automation system using MicroPython, the system include various functionalities such as obstacle detection, line following, speed control, and environmental monitoring. am trying to detect obstacles in front of the car using an ultrasonic sensor HC-SR04 and control the motor accordingly. my aim is to measure the distance to obstacles and stop the car if an obstacle is too close.
But I keep getting the error
UnboundLocalError: local variable 'start' referenced before assignment

here's my code 👇
from machine import Pin
import time

# Ultrasonic sensor setup
trigger = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)

def measure_distance():
    trigger.off()
    time.sleep_us(2)
    trigger.on()
    time.sleep_us(10)
    trigger.off()

    while echo.value() == 0:
        start = time.ticks_us()
    while echo.value() == 1:
        end = time.ticks_us()

    duration = time.ticks_diff(end, start)
    distance = (duration * 0.0343) / 2
    return distance

while True:
    distance = measure_distance()
    print('Distance:', distance, 'cm')
    if distance < 10:
        print("Obstacle detected! Stopping car.")
        stop()  # Add stop function from Stage 1
    time.sleep(1)
Was this page helpful?