from machine import Pin, I2C,Timer, SoftI2C
import time
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from oled import OLED
button = Pin(23,Pin.IN,Pin.PULL_UP)
debounce_delay = 50
button_presses = 0
MAX_BUTTON_PRESS = 5
oled_button = Pin(14, Pin.IN, Pin.PULL_UP)
button_presses_oled = 0
max_button_press_oled = 3
# I2C Pin setup for ESP32
i2c = I2C(0,scl=Pin(22), sda=Pin(21), freq=10000)
i2c_1 = SoftI2C(scl=Pin(26), sda=Pin(27), freq=400000)
# Oled setup
oled = OLED.I2C(128, 64, i2c_1)
# LCD setup for ESP32
I2C_ADDR = i2c.scan()[0]
totalRows = 2
totalColumns = 16
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# Ultrasonic Sensor setup
ultra = HCSR04(25,26)
#Button Setup
def handle_button_press_tmr(tmr):
global button_presses
tmr.deinit()
if button.value() == 0:
button_presses = (button_presses + 1)
if button_presses == MAX_BUTTON_PRESS:
button_presses = 1
def handle_button_press_intr(pin):
tmr = Timer(-1)
tmr.init(mode=Timer.ONE_SHOT, period=debounce_delay, callback=handle_button_press_tmr)
def handle_button_press_intr_oled(pin):
tmr = Timer(-1)
tmr.init(mode=Timer.ONE_SHOT, period=debounce_delay, callback=handle_button_press_tmr_oled)
def handle_button_press_tmr_oled(tmr):
global button_presses
tmr.deinit()
if button_oled.value() == 0:
button_presses_oled = (button_presses + 1)
if button_presses_oled == max_button_press_oled:
button_presses_oled = 1
def measure_distance():
# Return the distance in cm
return ultra.distance_cm()
def display_distance(distance):
# Display distance on LCD
lcd.clear()
lcd.putstr("Distance:{_distance:.3f}".format(_distance=distance))
displayed_string = ''
def display_string(to_display):
global displayed_string
if to_display == displayed_string:
return
lcd.clear()
lcd.putstr(to_display)
displayed_string = to_display
def main():
button.irq(handler = handle_button_press_intr,trigger = Pin.IRQ_FALLING | Pin.IRQ_RISING)
button_oled.irq(handler = handle_button_press_intr_oled, trigger = Pin.IRQ_FALLING | Pin.IRQ_RISING)
global button_presses
while True:
# Keep the main functionality running
if button_presses == 0:
display_string('Press Button to Start')
elif button_presses == 1:
display_distance(measure_distance())
elif button_presses == 2:
display_string('DECI Students')
time.sleep(1)
display_string('Embedded Systems')
elif button_presses == 3:
distance = measure_distance()
if distance < 50:
display_string('Too Close')
elif 50 < distance < 100 :
display_string('Keep Distance')
elif distance > 100:
display_string('Safe')
elif button_presses == 4:
display_string(f'LCD Address {I2C_ADDR}')
if button_presses_oled == 1:
frequency = 40000
elif button_presses_oled == 2:
frequency = 4000
elif button_presses_oled == 3:
frequency = 1000
if measure_distance() >= 70:
oled.clear()
oled.text("Safe", 10, 3)
oled.show()
else:
oled.clear()
oled.text("Danger", 10, 3)
oled.show()
time.sleep(1)
if __name__ == "__main__":
main()
Loading
ssd1306
ssd1306