from machine import Pin, I2C
import time
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Initialize I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
i2c_addr = i2c.scan()[0]
lcd = I2cLcd(i2c, i2c_addr, 2, 16)
sensor = HCSR04(trigger_pin=25, echo_pin=26)
button_pin = Pin(19, Pin.IN, Pin.PULL_UP)
button_pin2 = Pin(27, Pin.IN, Pin.PULL_UP)
press_count = 1
freq_index = 0
last_press_time = 0
last_press_time2 = 0
frequencies = [400000, 40000, 4000, 1000]
def measure_distance():
"""Measure distance using the HC-SR04 sensor."""
try:
distance = sensor.get_distance_cm()
return distance
except Exception as e:
print("Error measuring distance:", e)
return None
def display_distance(distance):
"""Display the measured distance on the LCD."""
lcd.clear()
if distance is not None:
lcd.putstr("Distance:\n{:.1f} cm".format(distance))
else:
lcd.putstr("Sensor Error")
def button_handler(pin):
"""Handle button press events for Button 1."""
global press_count, last_press_time
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_press_time) > 500:
press_count += 1
if press_count > 5:
press_count = 1
last_press_time = current_time
def button_handler2(pin):
global freq_index, last_press_time2, i2c
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_press_time2) > 500:
freq_index += 1
if freq_index == len(frequencies):
freq_index = 0
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=frequencies[freq_index])
lcd.clear()
lcd.putstr("I2C Freq:\n{} Hz".format(frequencies[freq_index]))
last_press_time2 = current_time
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
button_pin2.irq(trigger=Pin.IRQ_FALLING, handler=button_handler2)
def main():
global press_count
while True:
if press_count == 1:
distance = measure_distance()
display_distance(distance)
time.sleep(1)
elif press_count == 2:
lcd.clear()
lcd.putstr("DECI students")
time.sleep(1)
lcd.clear()
lcd.putstr("Embedded systems")
time.sleep(1)
elif press_count == 3:
distance = measure_distance()
lcd.clear()
if distance is not None:
if distance < 50:
lcd.putstr("Too close")
elif distance < 100:
lcd.putstr("Keep distance")
else:
lcd.putstr("Safe")
else:
lcd.putstr("Sensor Error")
time.sleep(1)
elif press_count == 4:
lcd.clear()
lcd.putstr("I2C Addr:\n{}".format(hex(i2c_addr)))
time.sleep(2)
elif press_count == 5:
press_count = 1
# Add a small delay to avoid busy waiting
time.sleep(0.1)
if __name__ == "__main__":
main()