import machine
from hcsr04 import HCSR04
import time
from lcd_api.py import LcdApi
from i2c_lcd.py import I2cLcd
# Define GPIO pin numbers for the ultrasonic sensor
trigger_pin = 13 # GPIO15 (D15)
echo_pin = 12 # GPIO13 (D13)
# Define the GPIO pins connected to the buzzer and LED
buzzer_pin = machine.Pin(15, machine.Pin.OUT) # GPIO2 (D2)
led_pin = machine.Pin(2, machine.Pin.OUT) # GPIO4 (D4)
# variables for LCD
I2C_Addr = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_Addr, totalRows. totalColumns, freq=10000)
# Create an HCSR04 object with trigger and echo pins
sensor = HCSR04(trigger_pin, echo_pin)
# Define the distance threshold for activation (in centimeters)
activation_distance = 20 # Adjust this value as needed
while True:
try:
distance = sensor.distance_cm()
print("Distance:", distance, "cm")
if distance <= activation_distance:
print("open")
lcd.putstr("Someone opened the door!")
buzzer_pin.on()
for _ in range(5): # Blink the LED 5 times
led_pin.on()
time.sleep(0.5)
led_pin.off()
time.sleep(0.5)
buzzer_pin.off()
lcd.clear
else:
buzzer_pin.off()
lcd.putstr("Door is closed")
led_pin.off()
print("close")
lcd.clear
except OSError as e:
print("Error reading distance:", e)
time.sleep(0.5) # Adjust the update rate as needed