from machine import Pin, SoftI2C, SPI, PWM
from mfrc522 import MFRC522
from i2c_lcd import I2cLcd
from time import sleep
green_led = Pin(8, Pin.OUT)
red_led = Pin(7, Pin.OUT)
buzzer = PWM(Pin(6))
green_led.off()
red_led.off()
buzzer.duty_u16(0)
i2c = SoftI2C(sda=Pin(26), scl=Pin(27), freq=100000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# 3. Initialize Hardware SPI0 and MFRC522 RFID Reader
spi = SPI(0, baudrate=1000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(19), miso=Pin(16))
reader = MFRC522(spi=spi, gpioRst=15, gpioCs=17)
# List of authorized card UIDs
AUTHORIZED_UIDS = [
[1, 3, 4, 0],# Blue Card
[170, 204, 0, 0] # Red Card
]
def reset_system():
lcd.clear()
lcd.putstr("Scan your card..")
green_led.off()
red_led.off()
buzzer.duty_u16(0)
# Initialize display state on startup
reset_system()
print("System Ready, Waiting for RFID Tag...")
while True:
(stat, tag_type) = reader.request(reader.REQIDL)
if stat == reader.OK:
(stat, raw_uid) = reader.SelectTagSN()
if stat == reader.OK:
# Format raw UID list into readable Hex string
uid_str = ":".join(["{:02X}".format(x) for x in raw_uid])
print(f"Card Detected! Raw: {raw_uid} | Hex: {uid_str}")
# Check if detected card UID is authorized
if raw_uid in AUTHORIZED_UIDS or uid_str in AUTHORIZED_UIDS:
print(">>> ACCESS GRANTED <<<")
lcd.clear()
lcd.putstr("Access Granted!\nWelcome In..")
green_led.on()
red_led.off()
# Short success beep
buzzer.freq(523)
buzzer.duty_u16(30000)
sleep(0.2)
buzzer.duty_u16(0)
sleep(2.5)
else:
print(">>> ACCESS DENIED! UNKNOWN CARD <<<")
lcd.clear()
lcd.putstr("Access Denied!\nEntry Refused!")
green_led.off()
red_led.on()
# Alarm beep for unauthorized card
buzzer.freq(262)
buzzer.duty_u16(30000)
sleep(0.8)
buzzer.duty_u16(0)
sleep(1.5)
# Reset hardware output back to default state
reset_system()
sleep(0.1)