from machine import Pin, I2C, PWM
import time
# Initialize pins
button0 = Pin(2, Pin.IN, Pin.PULL_DOWN)
button1 = Pin(3, Pin.IN, Pin.PULL_DOWN)
button2 = Pin(4, Pin.IN, Pin.PULL_DOWN)
green_led = Pin(15, Pin.OUT)
red_led = Pin(16, Pin.OUT)
buzzer = Pin(4, Pin.OUT)
# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
# Initialize servo
servo = PWM(Pin(12))
servo.freq(50)
# Access control data
ACCESS_CODES = {
0b001: "Student",
0b010: "Lecturer",
0b011: "Technician"
}
def read_buttons():
"""Read the 3-bit binary code from buttons"""
b0 = button0.value()
b1 = button1.value()
b2 = button2.value()
return (b2 << 2) | (b1 << 1) | b0
def unlock_servo():
"""Simulate unlocking by rotating servo to 90 degrees"""
servo.duty_u16(4915) # ~90 degrees
time.sleep(2)
def lock_servo():
"""Simulate locking by rotating servo to 0 degrees"""
servo.duty_u16(1966) # ~0 degrees
time.sleep(0.5)
def access_granted(user_type):
"""Handle granted access sequence"""
print(f"ACCESS GRANTED - {user_type}")
# Visual feedback
green_led.on()
red_led.off()
# LCD display
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("ACCESS GRANTED")
lcd.move_to(0, 1)
lcd.putstr(f"Welcome {user_type}!")
# Sound feedback (2 short beeps)
for _ in range(2):
buzzer.on()
time.sleep(0.1)
buzzer.off()
time.sleep(0.1)
# Unlock servo
unlock_servo()
green_led.off()
lock_servo()
def access_denied():
"""Handle denied access sequence"""
print("ACCESS DENIED")
# Visual feedback
red_led.on()
green_led.off()
# LCD display
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("ACCESS DENIED")
lcd.move_to(0, 1)
lcd.putstr("Invalid Card")
# Sound feedback (continuous beep)
buzzer.on()
time.sleep(1.5)
buzzer.off()
red_led.off()
def main():
"""Main program loop"""
lcd.putstr("Enter Binary")
lcd.move_to(0, 1)
lcd.putstr("Code: ---")
previous_code = -1
while True:
# Read current code
code = read_buttons()
# Only process if code changed
if code != previous_code:
previous_code = code
# Update LCD display
lcd.move_to(6, 1)
lcd.putstr(f"{code:03b}")
# Check access
if code in ACCESS_CODES:
access_granted(ACCESS_CODES[code])
elif code == 0b111:
access_denied()
else:
# Handle other invalid codes
lcd.clear()
lcd.putstr("Invalid Code")
lcd.move_to(0, 1)
lcd.putstr(f"{code:03b} Unknown")
time.sleep(1)
lcd.clear()
lcd.putstr("Enter Binary")
lcd.move_to(0, 1)
lcd.putstr("Code: ---")
time.sleep(0.05)