from machine import I2C, Pin
from time import sleep
import utime
from pico_i2c_lcd import I2cLcd
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
trigger = Pin(3,Pin.OUT)
echo = Pin(2, Pin.IN)
# getting I2C address
I2C_ADDR = i2c.scan()[0]
# creating an LCD object using the I2C address and specifying number of rows and columns in the LCD
# LCD number of rows = 2, number of columns = 16
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
lcd.putstr("Dist.(cm)=")
def ultra ():
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()
timpassed = signalon - signaloff
distance = (timpassed * 0.0343) / 2
print("The distance from object is ",distance,"cm")
return distance
while True:
d = ultra()
d = round(d, 2)
lcd.move_to(10, 0)
lcd.putstr("{:<7}".format(str(d)))
sleep(1)