import network
import time
from machine import Pin, I2C
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# I2C Pin setup for ESP32
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # Initialize LCD with 2 rows and 16 columns
# Ultrasonic sensor setup
sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
prev_distance = ""
while True:
# Measure distance
distance = sensor1.distance_cm()
# Display distance on LCD
lcd.clear() # Clear the LCD
lcd.putstr("Distance:\n{} cm".format(distance)) # Display distance on the LCD
# Print distance to console
print('Distance:', distance, 'cm')
# Prepare and publish the message
message = ujson.dumps(distance)
if message != prev_distance:
print("Updated!")
print("Reporting to MQTT topic {}:{}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_distance = message
else:
print("No change")
time.sleep(1) # Adjust the sleep time as needed