Build an RFID door with an attendance log on the Raspberry Pi

Tap a card on the RC522 reader and a servo latch swings open for allowed cards, while unknown cards get a red flash. Every tap is saved in an SQLite database, and a web page shows who came in and...
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi

What you'll need

Build an RFID door with an attendance log on the Raspberry Pi – EEMENTOR STEM™ lesson

Offices, hotels and school gates open with a card instead of a key, and somewhere a computer writes down who came in. In this project you build the same system with a Raspberry Pi. Tap a card on the RC522 RFID reader: if it belongs to someone on your list, a green LED lights up and a servo latch swings open for three seconds. Any other card gets three red flashes. Every tap is saved in an SQLite database, and a web page on your phone shows the attendance log: who came in, when, and how many people have been in today.

You need the skills from lesson 1 of this path: a virtual environment, SQLite and a Flask page running next to your main loop.

What you'll learn

  • How RFID cards work, and why each one has its own ID number
  • How to switch on the Pi's SPI bus and connect an SPI device
  • How to keep a list of allowed cards in a database, and add cards from the command line
  • How to control a servo with gpiozero, and stop it from jittering
  • How to show the newest database rows on a web page that refreshes itself

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS, its USB-C power supply and a Wi-Fi connection
  • RC522 RFID module with the S50 card (ESP32 IoT Starter Kit). Key fobs and other 13.56 MHz MIFARE cards work too.
  • Servo motor (ESP32 IoT Starter Kit)
  • 1 green LED, 1 red LED and two 220 Ω resistors (ESP32 IoT Starter Kit)
  • Breadboard (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires, or female-female and male-male Dupont wires plugged together
  • Optional: a shoebox, and a lolly stick taped to the servo horn as the latch

Look after your Pi: the RC522 runs on 3.3 V. Connect its 3.3V pin to the Pi's 3V3 pin, never to 5V, or the module can be damaged. The servo is the only part that gets 5V. Shut the Pi down and unplug it before you change any wiring.

Wiring

If your RC522 came without pins, solder the straight header first. Push the module's eight pins into the breadboard. The labels are printed next to the pins: SDA, SCK, MOSI, MISO, IRQ, GND, RST, 3.3V. Five of the wires go to the Pi's SPI pins, which sit together in the middle of the header. IRQ stays empty. The servo's three-wire plug goes onto three breadboard holes: brown (or black) is GND, red is 5V, and orange (or yellow) is the signal.

Breadboard wiring diagram on a Raspberry Pi 4: RC522 SDA to pin 24, SCK to pin 23, MOSI to pin 19, MISO to pin 21, RST to pin 22, 3.3V to pin 1, GND to the minus rail; green LED on GPIO 17 and red LED on GPIO 27 through 220 ohm resistors; servo GND to the rail, power to 5V (pin 2), signal to GPIO 18 (pin 12); minus rail to GND (pin 9).
Breadboard view. Check each connection against the wiring table below.
From To
RC522 SDA GPIO 8 / CE0 (pin 24)
RC522 SCK GPIO 11 / SCLK (pin 23)
RC522 MOSI GPIO 10 / MOSI (pin 19)
RC522 MISO GPIO 9 / MISO (pin 21)
RC522 IRQ Not connected
RC522 GND The blue (−) rail
RC522 RST GPIO 25 (pin 22)
RC522 3.3V 3V3 (pin 1)
GPIO 17 (pin 11) 220 Ω resistor → green LED long leg; short leg → the blue (−) rail
GPIO 27 (pin 13) 220 Ω resistor → red LED long leg; short leg → the blue (−) rail
Servo brown (GND) The blue (−) rail
Servo red (power) 5V (pin 2)
Servo orange (signal) GPIO 18 (pin 12)
The blue (−) rail GND (pin 9)

Step 1: Switch on SPI and install the library

SPI is off by default. Open a Terminal and run sudo raspi-config, choose Interface Options → SPI → Yes, then Finish. Alternatively, use Raspberry Pi Configuration → Interfaces on the desktop. Check that it worked: ls /dev/spidev* should list /dev/spidev0.0. Then make a virtual environment and install the mfrc522 library, which also brings the spidev and RPi.GPIO libraries it needs:

python3 -m venv --system-site-packages ~/door-env
source ~/door-env/bin/activate
pip install mfrc522
mkdir ~/rfid-door

Step 2: The program

Save the program as ~/rfid-door/rfid_door.py, for example with nano ~/rfid-door/rfid_door.py.

# RFID door with an attendance log: RC522 + LEDs + servo latch + SQLite + Flask
import os
import sqlite3
import sys
import threading
import time
from datetime import datetime

from flask import Flask
from gpiozero import LED, AngularServo
from mfrc522 import SimpleMFRC522

FOLDER = os.path.expanduser("~/rfid-door")
DB = os.path.join(FOLDER, "door.db")
os.makedirs(FOLDER, exist_ok=True)

green = LED(17)
red = LED(27)
latch = AngularServo(18, min_angle=0, max_angle=180,
                     min_pulse_width=0.0005, max_pulse_width=0.0024)
app = Flask(__name__)
reader = None                      # created in main(), so tests can swap it
OPEN, CLOSED = 90, 0               # latch angles in degrees


def connect():
    con = sqlite3.connect(DB)
    con.execute("CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY, name TEXT)")
    con.execute("CREATE TABLE IF NOT EXISTS log (ts TEXT, card INTEGER, name TEXT, allowed INTEGER)")
    return con


def card_name(card_id):
    with connect() as con:
        row = con.execute("SELECT name FROM cards WHERE id = ?", (card_id,)).fetchone()
    return row[0] if row else None


def add_card(name):
    print(f"Hold the card for {name} on the reader...")
    card_id = reader.read_id()                 # waits for a card
    with connect() as con:
        con.execute("INSERT OR REPLACE INTO cards VALUES (?, ?)", (card_id, name))
    print(f"Card {card_id} now opens the door for {name}")


def move_latch(angle):
    latch.angle = angle
    time.sleep(0.6)                # give the servo time to get there
    latch.detach()                 # stop the pulses: no jitter, no buzzing


def handle(card_id):
    name = card_name(card_id)
    with connect() as con:
        con.execute("INSERT INTO log VALUES (?, ?, ?, ?)",
                    (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), card_id, name, int(bool(name))))
    if name:
        print(f"{datetime.now():%H:%M:%S}  Welcome, {name}!")
        green.on()
        move_latch(OPEN)
        time.sleep(3)              # the door stays open for 3 seconds
        move_latch(CLOSED)
        green.off()
    else:
        print(f"{datetime.now():%H:%M:%S}  Unknown card {card_id}: access denied")
        red.blink(on_time=0.2, off_time=0.2, n=3, background=False)


def door_loop():
    move_latch(CLOSED)
    print("Ready. Tap a card.")
    last_id, last_time = None, 0
    while True:
        card_id = reader.read_id_no_block()
        # ignore the same card while it is still lying on the reader
        if card_id and (card_id != last_id or time.time() - last_time > 5):
            handle(card_id)
            last_id, last_time = card_id, time.time()
        time.sleep(0.2)


@app.route("/")
def attendance():
    with connect() as con:
        rows = con.execute("SELECT ts, name, card, allowed FROM log "
                           "ORDER BY ts DESC LIMIT 50").fetchall()
        today = con.execute("SELECT COUNT(DISTINCT name) FROM log WHERE allowed = 1 "
                            "AND ts >= date('now', 'localtime')").fetchone()[0]
    lines = "".join(
        f"<tr><td>{ts}</td><td>{name or 'Unknown card ' + str(card)}</td>"
        f"<td>{'✅ opened' if ok else '⛔ denied'}</td></tr>" for ts, name, card, ok in rows)
    return ("<!doctype html><meta charset='utf-8'><meta name='viewport' content='width=device-width'>"
            "<meta http-equiv='refresh' content='10'><title>Door log</title>"
            "<style>body{font-family:sans-serif;max-width:700px;margin:auto;padding:16px}"
            "td{padding:6px 12px;border-bottom:1px solid #ddd}</style>"
            f"<h1>Door log</h1><p>People in today: <b>{today}</b></p>"
            f"<table><tr><th>Time</th><th>Who</th><th>Door</th></tr>{lines}</table>")


def main():
    global reader
    reader = SimpleMFRC522()
    if len(sys.argv) == 3 and sys.argv[1] == "add":
        add_card(sys.argv[2])
        return
    threading.Thread(target=lambda: app.run(host="0.0.0.0", port=5000), daemon=True).start()
    try:
        door_loop()
    finally:
        import RPi.GPIO as GPIO    # the RC522 library uses RPi.GPIO
        GPIO.cleanup()


if __name__ == "__main__":
    main()

Step 3: Add your cards, then run the door

With the environment active, register each card. Type the name, then hold the card on the reader until the message appears:

cd ~/rfid-door
python rfid_door.py add "Alex"
python rfid_door.py add "Sam"

Now start the door itself with python rfid_door.py. Open http://<the Pi's address>:5000 on your phone (find the address with hostname -I) to see the log. Press Ctrl+C to stop. To run the door at every boot, make a service file exactly like in lesson 1, step 3, with rfid-door, door-env and rfid_door.py in the paths.

What you should see

When you start the door, the servo moves to the closed position and the Terminal says Ready. Tap a card. Tap a registered card: the Terminal greets the person by name, the green LED lights up, and the latch swings to 90°, waits three seconds and closes again. Tap an unknown card, such as a bank card or a building pass: the Terminal prints Unknown card with its number, and the red LED flashes three times. The web page lists the last 50 taps, newest first, with a ✅ or ⛔ next to each. It refreshes every 10 seconds, so you can leave it open on a tablet next to the door.

What you should see: the Terminal greeting Alex and Sam and denying an unknown card, and the Door log web page listing each tap with its time, name and whether the door opened, plus the number of people in today.
Every tap appears in the Terminal and on the Door log page.

How it works

How it works: the RC522 field powers the card, which answers with its UID; the UID travels to the Pi over the SPI wires SCK, MOSI, MISO and CE0; the Pi looks it up in the cards table, opens the latch or flashes the red LED, and writes a row to the log table.
Card UID → SPI → database → latch and log.

The RC522 makes a 13.56 MHz radio field around its antenna. A card has no battery: its coil picks up energy from the field, wakes up a tiny chip and answers with its UID, a serial number stored in the chip. The library turns the UID into one big number, which is what you see in the log.

The Pi talks to the RC522 over SPI, a fast four-wire bus. SCK is the clock. MOSI carries data from the Pi to the module, and MISO carries data back. The SDA pin (called CE0 on the Pi) tells the module that the Pi is talking to it, so several SPI devices can share the same three data wires. RST lets the library reset the module when it starts.

The database has two tables. cards links each card number to a name, so you can add people without changing the program. log gets one row for every tap: time, card number, name (empty for unknown cards) and whether the door opened. The web page runs two queries: the newest 50 rows, and COUNT(DISTINCT name) for the people who came in today, so Alex tapping five times still counts as one person.

A card lying on the reader would be read again and again, about five times a second. The main loop remembers the last card and its time, and ignores the same card for five seconds. read_id_no_block() returns None straight away when no card is there, so the loop never gets stuck. read_id(), used when adding cards, waits until a card arrives.

A servo turns to an angle set by the width of a pulse sent 50 times a second, from about 0.5 ms for 0° to about 2.4 ms for 180° on small servos like the one in the kit. gpiozero makes those pulses in software, so they wobble a little whenever Linux is busy, and a servo that keeps receiving pulses twitches and hums. move_latch() therefore gives the servo 0.6 seconds to get there and then calls latch.detach(), which stops the pulses. A small servo keeps its position without them.

Try this next

  • Add a buzzer from the kit: a short beep for allowed cards and a long one for unknown cards.
  • Count "in" and "out": the first tap of the day means in, the next one out, and show who is still inside.
  • Add a /cards page that lists the registered cards, so you can see who has access.
  • Next you'll control things on a schedule: a smart relay panel with timers.

Troubleshooting

  • FileNotFoundError: /dev/spidev0.0: SPI is still off. Switch it on in raspi-config and reboot.
  • The door starts but no card is ever read: check the five SPI wires against the table, especially MOSI and MISO, which are easy to swap. Hold the card flat on the reader, within about 3 cm.
  • Every card reads as a different number each time: a loose GND or 3.3V wire. Push the module firmly into the breadboard, or solder its header.
  • The servo twitches or the Pi restarts when it moves: the servo draws bursts of current from the 5V pin. Use the official power supply. If it still happens, power the servo from a separate 5 V supply and connect its GND to the Pi's GND.
  • The latch doesn't reach the right angle: servos differ. Change OPEN and CLOSED, or the two pulse widths, until it stops where you want.
  • RuntimeError about the SoC or GPIO mode: another program is using the pins. Stop it, or reboot, and run only one copy of the door.

Next lesson

Build a smart relay panel with timers on the Raspberry Pi: switch two relays from your phone and let the Pi turn them on and off on a schedule.