from machine import Pin, time_pulse_us
import time

# LEDs
led1 = Pin(13, Pin.OUT)
led2 = Pin(14, Pin.OUT)
led3 = Pin(15, Pin.OUT)

# Buzzer
buzzer = Pin(16, Pin.OUT)

# Ultrasonic pins
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

def get_distance():
    # Send trigger pulse
    trig.low()
    time.sleep_us(2)
    trig.high()
    time.sleep_us(10)
    trig.low()

    # Measure echo pulse width
    duration = time_pulse_us(echo, 1, 30000)  # timeout 30ms

    if duration < 0:
        return None  # no reading

    # Convert to distance (cm)
    distance = (duration * 0.0343) / 2
    return distance

while True:
    dist = get_distance()

    if dist is None:
        print("No reading")
        led1.off(); led2.off(); led3.off()
        buzzer.off()
        time.sleep(0.1)
        continue

    print("Distance:", dist, "cm")

    # LED logic
    if dist < 10:
        led1.on(); led2.off(); led3.off()
        buzzer.on()
    elif dist < 20:
        led1.off(); led2.on(); led3.off()
        buzzer.off()
    elif dist < 40:
        led1.off(); led2.off(); led3.on()
        buzzer.off()
    else:
        led1.off(); led2.off(); led3.off()
        buzzer.off()

    time.sleep(0.1)
