import machine
from machine import Pin, I2C
from time import sleep_us, sleep
from machine import SoftI2C
from i2c_lcd import I2cLcd
echo = Pin(12, Pin.IN)
trig = Pin(13, Pin.OUT)
# Set up the I2C LCD display
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16) # 0x27 is the default I2C address for most 16x2 LCDs
while True:
trig.value(0)
sleep_us(2)
trig.value(1)
sleep_us(10)
trig.value(0)
x = machine.time_pulse_us(echo, 1)
distance = (0.034 * x) / 2 # using 0.034 instead of 0.0343 to get the right value
# Print distance to LCD
lcd.clear()
lcd.putstr("Distance: {:.2f}cm".format(distance))
sleep(1)