import time
from machine import Pin, PWM
# --- Keypad class ---
class Keypad:
def __init__(self, row_pins, col_pins, keys):
self.row_pins = [Pin(pin, Pin.OUT) for pin in row_pins]
self.col_pins = [Pin(pin, Pin.IN, Pin.PULL_DOWN) for pin in col_pins]
self.keys = keys
def scan(self):
for row_num, row_pin in enumerate(self.row_pins):
row_pin.high()
for col_num, col_pin in enumerate(self.col_pins):
if col_pin.value():
row_pin.low()
return self.keys[row_num][col_num]
row_pin.low()
return None
# --- Keypad configuration ---
KEYS = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
ROW_PINS = [2, 3, 4, 5]
COL_PINS = [6, 7, 8, 9]
kp = Keypad(ROW_PINS, COL_PINS, KEYS)
# --- Servo and LED setup ---
servo = PWM(Pin(17))
servo.freq(60)
servo1 = PWM(Pin(16))
servo1.freq(60)
ledr = Pin(27, Pin.OUT)
ledg = Pin(22, Pin.OUT)
ledy = Pin(26, Pin.OUT)
buzzer = PWM(Pin(28))
buzzer.freq(600)
vol = 2000
# --- Servo angle function ---
def servo_angle(angle):
duty = int((angle / 180 * 2 + 0.5) / 20 * 65535)
servo.duty_u16(duty)
def servo1_angle(angle):
duty = int((angle / 180 * 2 + 0.5) / 20 * 65535)
servo1.duty_u16(duty)
# --- Start in locked position ---
servo_angle(114)
servo1_angle(114)
# --- Step 1: User enters the passcode to be saved ---
print("Set your 4-digit passcode using the keypad. Press '#' to save it.")
passcode_str = ""
while True:
key = kp.scan()
if key:
time.sleep(0.3) # debounce
if key.isdigit():
if len(passcode_str) < 4:
passcode_str += key
print("Passcode so far:", passcode_str)
else:
print("Max 4 digits allowed.")
elif key == "*":
passcode_str = ""
print("Passcode cleared.")
elif key == "#":
if len(passcode_str) == 4:
saved_code = int(passcode_str)
print("Passcode saved!")
break
else:
print("Passcode must be 4 digits.")
else:
print("Invalid key:", key)
# --- Step 2: Ask user to enter the code to unlock ---
print("Now enter the code to unlock. Press '#' when done.")
entered_str = ""
while True:
key = kp.scan()
if key:
time.sleep(0.3) # debounce
if key.isdigit():
entered_str += key
print("Code so far:", entered_str)
elif key == "*":
entered_str = ""
print("Code entry cleared.")
elif key == "#":
if entered_str != "":
try:
entered_code = int(entered_str)
break
except:
print("Invalid number.")
entered_str = ""
else:
print("No code entered.")
else:
print("Invalid key:", key)
# --- Step 3: Check code ---
if entered_code == saved_code:
print("Correct code! Unlocking...")
ledr.off()
buzzer.duty_u16(0)
servo_angle(220)
servo1_angle(10)
ledg.on()
time.sleep(8)
ledg.off()
else:
print("Wrong code! Triggering alarm...")
for i in range(10):
ledr.on()
buzzer.duty_u16(vol)
servo_angle(115)
servo1_angle(115)
time.sleep(0.5)
ledr.off()
buzzer.duty_u16(0)
time.sleep(0.5)
# --- Reset gate to locked position ---
servo_angle(114)
servo1_angle(114)
print("System reset.")