# HC-SR04 distance on XIAO RP2040, ~15 readings/s. TRIG -> D0 (GPIO26), ECHO -> divider -> D2 (GPIO28).
# On-board RGB LED: < 10 cm red, 10-20 cm blue, > 20 cm green, off when no echo.
import machine, time

trig = machine.Pin(26, machine.Pin.OUT, value=0)   # D0
echo = machine.Pin(28, machine.Pin.IN)             # D2

# On-board RGB LED, active-low (0 = on)
red = machine.Pin(17, machine.Pin.OUT, value=1)
green = machine.Pin(16, machine.Pin.OUT, value=1)
blue = machine.Pin(25, machine.Pin.OUT, value=1)


def show(led):
    for p in (red, green, blue):
        p.value(0 if p is led else 1)


while True:
    trig.value(1)
    time.sleep_us(10)                               # 10 us trigger pulse
    trig.value(0)
    t = machine.time_pulse_us(echo, 1, 30000)       # echo high time; 30 ms timeout (~5 m)
    if t < 0:
        show(None)
        print("out of range / no echo")
    else:
        cm = t * 0.0343 / 2                         # speed of sound 343 m/s, there and back
        show(red if cm < 10 else blue if cm <= 20 else green)
        print("%.1f cm" % cm)
    time.sleep_ms(66)                               # ~15 Hz
