from machine import Pin, PWM
import time
# Initialize Servo on GP15
servo = PWM(Pin(15))
servo.freq(50) # 50Hz PWM frequency
def set_servo_angle(angle):
""" Convert angle (0 to 180) into PWM duty cycle (2000 to 8000) """
duty = int((angle / 180) * 6000 + 2000) # Convert angle to duty cycle
servo.duty_u16(duty) # Set duty cycle
time.sleep(0.5) # Small delay for servo movement
# Define password
PASSWORD = "1234"
entered_password = ""
password = ""
# Define Keypad Rows and Columns
rows = [Pin(i, Pin.OUT) for i in range(1, 5)]
cols = [Pin(i, Pin.IN, Pin.PULL_DOWN) for i in range(5, 9)]
# 4x4 Keypad Layout
key_map = [
["1", "2", "3", "A"],
["4", "5", "6", "B"],
["7", "8", "9", "C"],
["*", "0", "#", "D"]
]
# Servo Functions for Lock and Unlock
def lock_door():
set_servo_angle(0) # Move to locked position
print("Door Locked")
def unlock_door():
set_servo_angle(90) # Move to unlocked position
print("Door Unlocked")
time.sleep(5)
lock_door() # Auto-lock after 5 seconds
# Keypad Scanning Function
def scan_keypad():
for i, row in enumerate(rows):
row.value(1) # Activate one row at a time
for j, col in enumerate(cols):
if col.value() == 1:
time.sleep(0.5) # Check if key is pressed
return key_map[i][j] # Return the pressed key
row.value(0)
return None
# Main Loop
lock_door() # Start with the door locked
while True:
key = scan_keypad()
if key:
password+="*"
print("Key Pressed:", password)
if key.isdigit(): # If key is a number
entered_password += key
elif key == "#": # Confirm password entry
if entered_password == PASSWORD:
print("Correct Password!")
unlock_door()
else:
print("Incorrect Password!")
entered_password = "" # Reset password input
elif key == "*": # Reset entry
entered_password = ""
password = ""