from machine import Pin, I2C
import time
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import machine
import utime
button = Pin(2, Pin.IN, Pin.PULL_DOWN)
count = 0
last_press_time = 0
press_window = 1000
def button_handler(pin):
global count, last_press_time
utime.sleep_ms(100)
if pin.value():
current_time = utime.ticks_ms()
if utime.ticks_diff(current_time, last_press_time) < press_window:
count += 1
else:
count = 1
last_press_time = current_time
print("Button pressed. Count:", count)
button.irq(trigger=Pin.IRQ_RISING, handler=button_handler)
# I2C Pin setup for ESP32
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# Ultrasonic Sensor setup
ultrasonic = HCSR04(trigger_pin = 25, echo_pin = 26)
def measure_distance():
try:
distance = ultrasonic.distance_cm()
return distance
except:
return -1
def mode_display_distance():
while True:
distance = measure_distance()
lcd.clear()
if distance == -1:
lcd.putstr("Sensor Error")
else:
lcd.putstr("Distance:\n{} cm".format(distance))
time.sleep(1)
if check_mode_change():
break
def mode_display_messages():
while True:
lcd.clear()
lcd.putstr("DECI students")
time.sleep(1)
if check_mode_change():
break
lcd.clear()
lcd.putstr("Embedded systems")
time.sleep(1)
if check_mode_change():
break
def mode_object_status():
while True:
distance = measure_distance()
lcd.clear()
if distance == -1:
lcd.putstr("Sensor Error")
elif distance < 50:
lcd.putstr("Too close")
elif 50 <= distance < 100:
lcd.putstr("Keep distance")
else:
lcd.putstr("Safe")
time.sleep(1)
if check_mode_change():
break
def mode_i2c_scan():
lcd.clear()
lcd.putstr("Scanning I2C...")
time.sleep(1)
devices = i2c.scan()
lcd.clear()
if devices:
for addr in devices:
lcd.clear()
lcd.putstr("I2C Device:\n0x{:02X}".format(addr))
time.sleep(2)
if check_mode_change():
return
else:
lcd.putstr("No devices")
time.sleep(2)
def mode_reset_menu():
global count
lcd.clear()
lcd.putstr("Resetting Menu...")
time.sleep(2)
count = 0
lcd.clear()
lcd.putstr("Waiting for\ninput...")
time.sleep(2)
def check_mode_change():
global count, last_press_time
start_count = count
time.sleep(0.1)
return start_count != count
def main():
global count
lcd.clear()
lcd.putstr("Waiting for\ninput...")
while True:
if count == 1:
mode_display_distance()
elif count == 2:
mode_display_messages()
elif count == 3:
mode_object_status()
elif count == 4:
mode_i2c_scan()
elif count == 5:
mode_reset_menu()
else:
time.sleep(0.1)
if __name__ == "__main__":
main()