from machine import Pin, I2C
from time import sleep
from hcsr04 import HCSR04
from i2c_lcd import I2cLcd
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)
while True:
try:
distance = sensor.distance_cm()
print("Distance:", distance, "cm")
lcd.clear()
lcd.putstr("Distance: {:.3f}cm\n".format(distance))
lcd.putstr("By Piyawan")
except Exception as e:
print("Error:", e)
lcd.clear()
lcd.putstr("Sensor Error\nBy Piyawan")
sleep(1)