import machine
from time import sleep
import pico_i2c_lcd as I2C_LCD_driver
import dht
MATRIX = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
['*', 0, '#']] # layout of keys on keypad
ROW = [6, 20, 19, 13] # row pins
COL = [12, 5, 16] # column pins
i2c = machine.I2C(0, sda=machine.Pin(0), scl=machine.Pin(1), freq=400000)
LCD = I2C_LCD_driver.I2cLcd(i2c, 0x27, 2, 16) # instantiate an lcd object, call it LCD
# Initialize LCD
LCD.backlight_on() # turn backlight on
LCD.putstr("Smart Door Lock") # write on line 1
# Set column pins as outputs and write default value of 1 to each
for i in range(3):
col_pin = machine.Pin(COL[i], machine.Pin.OUT)
col_pin.value(1)
# Set row pins as inputs with pull-up
for j in range(4):
row_pin = machine.Pin(ROW[j], machine.Pin.IN, machine.Pin.PULL_UP)
# Servo motor control
servo = machine.Pin(26, machine.Pin.OUT) # set GP26 as output
pwm = machine.PWM(servo) # create PWM object
def keypad_input():
while True:
for i in range(3): # loop through all columns
col_pin = machine.Pin(COL[i], machine.Pin.OUT)
col_pin.value(0) # pull one column pin low
for j in range(4): # check which row pin becomes low
row_pin = machine.Pin(ROW[j], machine.Pin.IN, machine.Pin.PULL_UP)
if not row_pin.value(): # if a key is pressed
while not row_pin.value(): # debounce
sleep(0.1)
return MATRIX[j][i] # return the key pressed
col_pin = machine.Pin(COL[i], machine.Pin.OUT)
col_pin.value(1) # write back default value of 1
def display_message(message):
LCD.clear()
LCD.putstr(message)
def read_temperature_humidity():
# Read temperature and humidity values
dht_pin = machine.Pin(0)
d = dht.DHT22(dht_pin)
d.measure()
temperature = d.temperature()
humidity = d.humidity()
# Check if valid data is received
if isinstance(temperature, float) and isinstance(humidity, float):
return temperature, humidity
else:
return None, None
# Main program loop
while True:
display_message("Enter Passcode:")
passcode = ""
for _ in range(4): # assume a 4-digit passcode
key = str(keypad_input())
passcode += key
sleep(0.2)
LCD.move_to(0, 1)
LCD.putstr(passcode)
if passcode == "0123": # replace with your desired passcode
display_message("Access Granted")
# Control the servo motor to unlock the door
pwm.freq(50)
pwm.duty_u16(6000) # 3% duty cycle
sleep(5) # Keep the door unlocked for 5 seconds
pwm.duty_u16(2000) # 13% duty cycle
sleep(2) # Keep the door locked for 2 seconds
pwm.deinit() # Stop the PWM signal
else:
display_message("Access Denied")
# Read and display temperature and humidity
temperature, humidity = read_temperature_humidity()
if temperature is not None and humidity is not None:
LCD.clear()
LCD.putstr("Temp: {:.1f} C".format(temperature))
LCD.move_to(0, 1)
LCD.putstr("Humidity: {:.1f}%".format(humidity))
sleep(2)