from machine import Pin, I2C
from time import sleep, ticks_ms, ticks_diff
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import oled
# I2C Pin setup for ESP32
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
lcd_addr = i2c.scan()[0] # Automatically find the address
lcd = I2cLcd(i2c, lcd_addr, 2, 16)
oled_2 = oled.I2C(128, 64, i2c)
# Ultrasonic Sensor setup
sensor = HCSR04(trigger_pin=25, echo_pin=26)
def measure_distance():
# Return the distance in cm
distance = reading.get_distance_cm()
return distance
def display_distance(distance):
# Display distance on LCD
lcd.putstr("The distance: " , distance)
# # oled_2.text('Distance: ' , distance, 10, 3)
# if 2 <= distance < 70:
# oled_2.clear()
# oled_2.text("Warning", 10, 3)
# oled_2.show()
# sleep(1)
# else:
# # Safe condition
# oled_2.clear()
# oled_2.text("Safe", 10, 3)
# oled_2.show()
# sleep(1)
button = Pin(23, Pin.IN, Pin.PULL_UP)
press_count = 0
last_press_time = 0
def button_handler(pin):
global press_count, last_press_time
now = ticks_ms()
if ticks_diff(now, last_press_time) > 300:
press_count += 1
if press_count > 5:
press_count = 1
last_press_time = now
button.irq(trigger=Pin.IRQ_RISING, handler=button_handler)
while True:
dist = sensor.distance_cm()
if press_count == 1:
dist = sensor.distance_cm()
lcd.clear()
lcd.putstr("Distance:\n{:.1f} cm".format(dist))
sleep(1)
elif press_count == 2:
lcd.clear()
lcd.putstr("DECI students")
sleep(1)
lcd.clear()
lcd.putstr("Embedded\nsystems")
sleep(1)
elif press_count == 3:
lcd.clear()
if dist < 50:
lcd.putstr("Too close")
elif dist < 100:
lcd.putstr("Keep distance")
else:
lcd.putstr("Safe")
sleep(1)
elif press_count == 4:
addresses = i2c.scan()
for addr in addresses:
lcd.clear()
lcd.putstr("I2C Addr:\n0x{:02X}".format(addr))
sleep(1)
elif press_count == 5:
press_count = 1
lcd.clear()
lcd.putstr("Menu reset")
sleep(1)
# oled_2.text('Distance: ' , distance, 10, 3)
if 2 <= dist < 70:
oled_2.clear()
oled_2.text("Warning", 10, 3)
oled_2.show()
sleep(1)
else:
# Safe condition
oled_2.clear()
oled_2.text("Safe", 10, 3)
oled_2.show()
sleep(1)
# Keep the main functionality running