from machine import I2C, Pin, time_pulse_us
from time import sleep
from pico_i2c_lcd import I2cLcd
# LCD por I2C
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# Sensor ultrasónico HC-SR04
trig = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
def get_distance():
"""Devuelve la distancia en cm (o None si no hay lectura)."""
trig.low()
sleep(0.002)
trig.high()
sleep(0.000010) # pulso de 10 µs
trig.low()
duration = time_pulse_us(echo, 1, 30000) # timeout 30 ms
if duration < 0:
return None
return (duration * 0.0343) / 2
while True:
cm = get_distance()
lcd.clear()
if cm is None:
lcd.move_to(0, 0)
lcd.putstr("Sin lectura")
else:
inches = cm / 2.54
feet = inches / 12
lcd.move_to(0, 0)
lcd.putstr("Pulg: {:.2f}in".format(inches))
lcd.move_to(0, 1)
lcd.putstr("Pies: {:.2f}ft".format(feet))
sleep(0.5)Loading
pi-pico-w
pi-pico-w