from machine import Pin, I2C, SoftI2C
import time
from hcsr04 import HCSR04
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
button_pressed = 0
last_button_time_stamp = 0
button = Pin(18, Pin.IN, Pin.PULL_DOWN)
US = HCSR04(25, 26)
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #initializing the I2C method for ESP32
#i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000) #initializing the I2C method for ESP8266
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
def int_handler(pin):
global button_pressed
global last_button_time_stamp
cur_button_ts = time.ticks_ms()
button_press_delta = cur_button_ts - last_button_time_stamp
if button_press_delta > 200:
last_button_time_stamp = cur_button_ts
button_pressed = button_pressed + 1
if button_pressed == 5:
button_pressed = 1
def measure_distance():
distance = US.distance_cm()
return distance
def display_distance(distance):
lcd.clear()
lcd.putstr(str(distance))
def main():
button.irq(trigger = Pin.IRQ_FALLING, handler = int_handler)
while True:
if button_pressed > 2:
CM = measure_distance()
display_distance(CM)
time.sleep(1)
if __name__ == "__main__":
main()