import machine
import utime
# Define GPIO pins for keypad matrix
ROW_PINS = [0, 1, 2, 3] # Example pins, adjust as per your setup
COL_PINS = [4, 5, 6] # Example pins, adjust as per your setup
# Define the keypad matrix layout
KEYPAD_LAYOUT = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['*', '0', '#']
]
# Define the correct passcode
CORRECT_PASSCODE = '4321'
# Define GPIO pin for servo motor
SERVO_PIN = 7 # Example pin, adjust as per your setup
# Define servo motor parameters
SERVO_LOCK_ANGLE = 0 # Example angles for locked and unlocked positions
SERVO_UNLOCK_ANGLE = 90
# Initialize keypad matrix
keypad_rows = [machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) for pin in ROW_PINS]
keypad_cols = [machine.Pin(pin, machine.Pin.OUT) for pin in COL_PINS]
# Initialize servo motor
servo = machine.PWM(machine.Pin(SERVO_PIN))
servo.freq(50) # Set PWM frequency to 50Hz
# Function to read input from keypad
def read_keypad():
key_pressed = None
for i in range(len(COL_PINS)):
for j in range(len(ROW_PINS)):
keypad_cols[i].value(0)
if keypad_rows[j].value() == 0:
key_pressed = KEYPAD_LAYOUT[j][i]
while keypad_rows[j].value() == 0:
pass # Wait for key release
keypad_cols[i].value(1)
return key_pressed
# Function to authenticate passcode
def authenticate_passcode():
entered_passcode = ''
while len(entered_passcode) < len(CORRECT_PASSCODE):
key = read_keypad()
if key:
entered_passcode += key
print("Entered passcode:", entered_passcode)
utime.sleep_ms(200) # Delay to avoid reading multiple times for one key press
if entered_passcode == CORRECT_PASSCODE:
return True
else:
return False
# Function to control servo motor
def control_servo(angle):
duty = (angle / 180) * 1024 + 512 # Convert angle to duty cycle
servo.duty_u16(int(duty))
# Main function
def main():
while True:
print("Enter passcode:")
if authenticate_passcode():
print("Passcode accepted. Unlocking door...")
control_servo(SERVO_UNLOCK_ANGLE)
utime.sleep(5) # Keep door unlocked for 5 seconds
control_servo(SERVO_LOCK_ANGLE)
print("Door locked.")
else:
print("Incorrect passcode. Try again.")
# Run the main function
if __name__ == "__main__":
main()