from machine import Pin, I2C
import utime
from i2c_lcd import I2cLcd

# Constants for the I2C LCD
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16

# Initialize I2C and LCD
i2c = I2C(0, scl=Pin(1), sda=Pin(0))  # Adjust to your Pico's pin configuration
lcd = I2cLcd(i2c, I2C_NUM_ROWS, I2C_NUM_COLS)

# Initialize the ultrasonic sensor
trigger = Pin(7, Pin.OUT)
echo = Pin(6, Pin.IN)

distance = 0

def ultrasound():
    global distance
    trigger.low()
    utime.sleep_us(2)
    trigger.high()
    utime.sleep_us(5)
    trigger.low()
    while echo.value() == 0:
        signaloff = utime.ticks_us()
    while echo.value() == 1:
        signalon = utime.ticks_us()
    timepassed = signalon - signaloff
    distance = (timepassed * 0.0343) / 2

    # Display the distance on the LCD
    lcd.clear()
    lcd.putstr("Dist: {:.2f} cm".format(distance))

while True:
    ultrasound()
    print("The distance from object is ", distance, "cm")
    utime.sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT