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

# I2C configuration
I2C_ADDR = 0x27  # Replace with your I2C LCD address
I2C_SDA_PIN = 0  # GP0
I2C_SCL_PIN = 1  # GP1
I2C_FREQ = 400000

# LCD configuration
LCD_ROWS = 2
LCD_COLS = 16

# Initialize I2C
i2c = I2C(0, scl=Pin(I2C_SCL_PIN), sda=Pin(I2C_SDA_PIN), freq=I2C_FREQ)

# Initialize LCD
try:
    lcd = I2cLcd(i2c, I2C_ADDR, LCD_ROWS, LCD_COLS)
    lcd.clear()
    lcd.putstr("LCD Initialized")
    utime.sleep(2)
    lcd.clear()
except Exception as e:
    print("Error initializing LCD:", e)
    while True:
        pass  # Stop execution if LCD initialization fails

# Ultrasonic sensor pins
trigger = Pin(7, Pin.OUT)
echo = Pin(6, Pin.IN)

distance = 0

def ultrasound():
    global distance
    trigger.low()
    utime.sleep_us(2)  # Ensure a clean low pulse before starting
    trigger.high()
    utime.sleep_us(10)  # Trigger the sensor with a 10us high pulse
    trigger.low()
    
    # Wait for the echo pin to go high (signal sent)
    while echo.value() == 0:
        signaloff = utime.ticks_us()
    
    # Wait for the echo pin to go low (signal received)
    while echo.value() == 1:
        signalon = utime.ticks_us()
    
    # Calculate the time passed
    timepassed = signalon - signaloff
    
    # Calculate the distance in cm (speed of sound is 34300 cm/s)
    distance = (timepassed * 0.0343) / 2

# Main loop to measure and display the distance
while True:
    try:
        ultrasound()
        # Print the distance to the console
        print("The distance from object is", distance, "cm")
        
        # Display the distance on the LCD
        lcd.clear()
        lcd.putstr("Distance: {:.2f} cm".format(distance))
    except Exception as e:
        print("Error in measuring distance:", e)
        lcd.clear()
        lcd.putstr("Error!")
    utime.sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT