from time import sleep_ms
from machine import I2C, Pin, UART
from i2c_lcd import I2cLcd
from hcsr04 import HCSR04
# Define I2C address of the LCD
lcd_address = 0x27
# Initialize I2C bus
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) # SCL Pin 22, SDA Pin 21
# Initialize LCD
lcd = I2cLcd(i2c, lcd_address, 2, 16) # 2 lines, 16 characters per line
# Initialize HC-SR04 Sensor (Trigger Pin, Echo Pin)
sensor = HCSR04(trigger_pin=14, echo_pin=13) # Example GPIOs, adjust as needed
# Initialize UART for serial display
uart = UART(1, baudrate=9600, tx=Pin(1), rx=Pin(3)) # tx and rx pins can be adjusted based on your ESP32 setup
def read_distance():
try:
distance = sensor.distance_cm()
return distance
except OSError:
return None
def display_data_on_lcd(distance):
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Distance (cm):")
lcd.move_to(0, 1)
if distance is not None:
lcd.putstr("{:.2f}".format(distance))
else:
lcd.putstr("Error")
def send_data_over_uart(distance):
if distance is not None:
uart.write("Distance: {:.2f} cm\r\n".format(distance))
else:
uart.write("Error reading distance\r\n")
def main():
while True:
distance = read_distance()
display_data_on_lcd(distance)
send_data_over_uart(distance)
sleep_ms(500) # Update display every 500 milliseconds
if __name__ == "__main__":
main()