Skip to content

RFID attendance

Hold a card to an RC522 reader, and the board asks SQL Server whose card it is, logs the scan, and lights a green or red LED. One stored procedure call per scan does the lookup and the logging; there's no web server or PHP script in between. SQL queries give the attendance: who came in today, and when each person arrived and left.

Parts and wiring

  • ESP32 or ESP8266 board
  • RC522 RFID reader (13.56 MHz, MIFARE cards and tags). It runs on 3.3 V; 5 V damages it.
  • Optional: a green and a red LED, each with a resistor (220 Ω to 1 kΩ)
RC522 ESP32 ESP8266
SDA (SS) GPIO5 D8
SCK GPIO18 D5
MOSI GPIO23 D7
MISO GPIO19 D6
RST GPIO22 D3
3.3V 3V3 3V3
GND GND GND
green LED GPIO25 D1
red LED GPIO26 D2

Set up the database

Run setup.sql in your database:

CREATE TABLE dbo.cards (
    uid    VARCHAR(20)  NOT NULL PRIMARY KEY, -- hex, as the reader sends it
    holder NVARCHAR(64) NOT NULL,
    active BIT          NOT NULL DEFAULT 1
);

CREATE TABLE dbo.scans (
    id         INT IDENTITY PRIMARY KEY,
    uid        VARCHAR(20) NOT NULL,
    reader     VARCHAR(32) NOT NULL,
    accepted   BIT         NOT NULL,
    scanned_at DATETIME2   NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE INDEX ix_scans_uid ON dbo.scans (uid, scanned_at);
GO

-- Logs the scan, and returns one row: accepted (1 or 0) and the
-- card holder (NULL for unknown cards). Unknown cards are logged
-- too, so you can see who tried, and add their cards.
CREATE PROCEDURE dbo.scan_card
    @uid    VARCHAR(20),
    @reader VARCHAR(32)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @holder NVARCHAR(64), @active BIT;
    SELECT @holder = holder, @active = active FROM dbo.cards WHERE uid = @uid;
    DECLARE @accepted BIT = CASE WHEN @active = 1 THEN 1 ELSE 0 END;
    INSERT INTO dbo.scans (uid, reader, accepted) VALUES (@uid, @reader, @accepted);
    SELECT @accepted AS accepted, @holder AS holder;
END
GO
-- The reader may only report scans. Run CREATE LOGIN in master.
CREATE LOGIN door_reader WITH PASSWORD = '<a long random password>';
CREATE USER door_reader FOR LOGIN door_reader;
GRANT EXECUTE ON dbo.scan_card TO door_reader;
GO

The reader's login can only call scan_card. It can't list the cards or the scans, and can't add cards.

Configure the sketch

Install the MFRC522 library (by GithubCommunity / miguelbalboa), open rfid_attendance.ino, and fill in the settings at the top. With PlatformIO:

lib_deps =
    mustafakemalgilor/tdslite
    miguelbalboa/MFRC522@^1.4

Add cards

Scan a card: the serial monitor shows its UID, e.g. 04A23B1C: unknown or blocked card. Add it, and block lost cards:

-- Add a card: the UID is printed on the serial monitor when an
-- unknown card is scanned, and logged in dbo.scans
INSERT INTO dbo.cards (uid, holder) VALUES ('04A23B1C', N'Ada Lovelace');

-- Block a lost card; its scans are still logged
UPDATE dbo.cards SET active = 0 WHERE uid = '04A23B1C';

-- Unknown cards scanned in the last week
SELECT uid, COUNT(*) AS scans, MAX(scanned_at) AS last_scan
FROM dbo.scans
WHERE accepted = 0 AND uid NOT IN (SELECT uid FROM dbo.cards)
  AND scanned_at > DATEADD(DAY, -7, SYSUTCDATETIME())
GROUP BY uid;

How it works

The card's UID becomes hex text:

// The card's UID as hex text, e.g. "04A23B1C"
static void uid_to_hex(const MFRC522::Uid & uid, char (&out) [21]) {
    static const char digits [] = "0123456789ABCDEF";
    uint8_t n = 0;
    for (uint8_t i = 0; i < uid.size && i < 10; i++) {
        out [n++] = digits [uid.uidByte [i] >> 4];
        out [n++] = digits [uid.uidByte [i] & 0x0F];
    }
    out [n] = '\0';
}

check_card calls the procedure, and its row callback reads the answer: accepted is a bit, the holder's name an nvarchar (UTF-16), or NULL for an unknown card:

// What SQL Server answered for a card. (Declared before the
// functions: the Arduino IDE puts its prototypes there.)
struct scan_result {
    bool answered = false; // the procedure returned its row
    bool accepted = false;
    char holder [65] = {}; // the card holder's name, ASCII only
};
static void read_result(void * user, const tdsl::tds_colmetadata_token &,
                        const tdsl::tdsl_row & row) {
    scan_result & r = *static_cast<scan_result *>(user);
    r.answered      = true;
    r.accepted      = row [0].as<bool>();
    if (not row [1].is_null()) {
        // nvarchar: UTF-16. Keep the ASCII characters for the serial
        // monitor; a display library could take all of them.
        const auto name = row [1].as<tdsl::u16le_view>();
        size_t n        = 0;
        for (const char16_t c : name) {
            if (n + 1 < sizeof(r.holder)) {
                r.holder [n++] = c < 0x80 ? static_cast<char>(c) : '?';
            }
        }
    }
}

// Logs the scan and returns whether the card is allowed in
static scan_result check_card(const char * uid) {
    tdsl::sql_parameter_varchar card{tdsl::string_view{uid, strlen(uid)}};
    tdsl::sql_parameter_varchar where{reader_name};
    tdsl::sql_parameter_binding params []{card, where};
    for (int attempt = 0; attempt < 2; attempt++) {
        scan_result r;
        const auto result = driver.execute_rpc(
            tdsl::string_view{"EXEC dbo.scan_card @uid = @p0, @reader = @p1"}, params,
            tdsl::rpc_mode::executesql, read_result, &r);
        if (result || not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
            not connect_to_db()) {
            return r;
        }
    }
    return {};
}

If SQL Server doesn't answer, the sketch fails closed: red LED, as for an unknown card.

void loop() {
    if (not reader.PICC_IsNewCardPresent() || not reader.PICC_ReadCardSerial()) {
        delay(50);
        return;
    }
    char uid [21];
    uid_to_hex(reader.uid, uid);
    reader.PICC_HaltA(); // one scan per tap

    const scan_result r = check_card(uid);
    if (not r.answered) {
        // No answer from the database: fail closed
        Serial.printf("%s: no answer from SQL Server\n", uid);
        signal(pin_red);
    } else if (r.accepted) {
        Serial.printf("%s: welcome, %s\n", uid, r.holder);
        signal(pin_green);
    } else {
        Serial.printf("%s: unknown or blocked card\n", uid);
        signal(pin_red);
    }
}

Reports

From queries.sql. The times are in UTC.

First and last scan per person and day:

-- Attendance: first and last scan of each person per day, over the
-- last 30 days
SELECT c.holder,
       CAST(s.scanned_at AS DATE)   AS day,
       MIN(s.scanned_at)            AS first_scan,
       MAX(s.scanned_at)            AS last_scan,
       DATEDIFF(MINUTE, MIN(s.scanned_at), MAX(s.scanned_at)) / 60.0 AS hours
FROM dbo.scans AS s
JOIN dbo.cards AS c ON c.uid = s.uid
WHERE s.accepted = 1 AND s.scanned_at > DATEADD(DAY, -30, SYSUTCDATETIME())
GROUP BY c.holder, CAST(s.scanned_at AS DATE)
ORDER BY day, c.holder;

Who has scanned in today:

-- Who has scanned in today
SELECT DISTINCT c.holder
FROM dbo.scans AS s
JOIN dbo.cards AS c ON c.uid = s.uid
WHERE s.accepted = 1 AND s.scanned_at >= CAST(SYSUTCDATETIME() AS DATE);

The complete sketch

rfid_attendance.ino
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#error "This sketch is for the ESP32 and the ESP8266"
#endif
#include <SPI.h>
#include <MFRC522.h>
#include <tdslite.h>

static const char * wifi_ssid      = "<your Wi-Fi name>";
static const char * wifi_password  = "<your Wi-Fi password>";
static const char db_server []     = "192.168.1.10";
static const char db_name []       = "office";
static const char db_user []       = "door_reader";
static const char db_password []   = "<password>";
static const char reader_name []   = "front-door";

#if defined(ESP32)
static constexpr uint8_t pin_ss = 5, pin_rst = 22, pin_green = 25, pin_red = 26;
#else
static constexpr uint8_t pin_ss = D8, pin_rst = D3, pin_green = D1, pin_red = D2;
#endif

static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
static MFRC522 reader{pin_ss, pin_rst};

// What SQL Server answered for a card. (Declared before the
// functions: the Arduino IDE puts its prototypes there.)
struct scan_result {
    bool answered = false; // the procedure returned its row
    bool accepted = false;
    char holder [65] = {}; // the card holder's name, ASCII only
};

static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
    if (not token.is_error()) {
        return;
    }
    Serial.print("SQL Server error: ");
    for (const char16_t c : token.msgtext) {
        Serial.print(static_cast<char>(c));
    }
    Serial.println();
}

static bool connect_to_db() {
    decltype(driver)::connection_parameters params;
    params.server_name = db_server;
    params.db_name     = db_name;
    params.user_name   = db_user;
    params.password    = db_password;
    params.app_name    = reader_name;
    params.packet_size = 1024;
    return driver.connect(params) == decltype(driver)::e_driver_error_code::success;
}

// The card's UID as hex text, e.g. "04A23B1C"
static void uid_to_hex(const MFRC522::Uid & uid, char (&out) [21]) {
    static const char digits [] = "0123456789ABCDEF";
    uint8_t n = 0;
    for (uint8_t i = 0; i < uid.size && i < 10; i++) {
        out [n++] = digits [uid.uidByte [i] >> 4];
        out [n++] = digits [uid.uidByte [i] & 0x0F];
    }
    out [n] = '\0';
}

static void read_result(void * user, const tdsl::tds_colmetadata_token &,
                        const tdsl::tdsl_row & row) {
    scan_result & r = *static_cast<scan_result *>(user);
    r.answered      = true;
    r.accepted      = row [0].as<bool>();
    if (not row [1].is_null()) {
        // nvarchar: UTF-16. Keep the ASCII characters for the serial
        // monitor; a display library could take all of them.
        const auto name = row [1].as<tdsl::u16le_view>();
        size_t n        = 0;
        for (const char16_t c : name) {
            if (n + 1 < sizeof(r.holder)) {
                r.holder [n++] = c < 0x80 ? static_cast<char>(c) : '?';
            }
        }
    }
}

// Logs the scan and returns whether the card is allowed in
static scan_result check_card(const char * uid) {
    tdsl::sql_parameter_varchar card{tdsl::string_view{uid, strlen(uid)}};
    tdsl::sql_parameter_varchar where{reader_name};
    tdsl::sql_parameter_binding params []{card, where};
    for (int attempt = 0; attempt < 2; attempt++) {
        scan_result r;
        const auto result = driver.execute_rpc(
            tdsl::string_view{"EXEC dbo.scan_card @uid = @p0, @reader = @p1"}, params,
            tdsl::rpc_mode::executesql, read_result, &r);
        if (result || not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
            not connect_to_db()) {
            return r;
        }
    }
    return {};
}

static void signal(uint8_t pin) {
    digitalWrite(pin, HIGH);
    delay(1500);
    digitalWrite(pin, LOW);
}

void setup() {
    Serial.begin(115200);
    pinMode(pin_green, OUTPUT);
    pinMode(pin_red, OUTPUT);

    SPI.begin();
    reader.PCD_Init();

    WiFi.mode(WIFI_STA);
    WiFi.begin(wifi_ssid, wifi_password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }
    driver.set_info_callback(print_message);
    while (not connect_to_db()) {
        Serial.println("SQL Server: connect failed, retrying");
        delay(5000);
    }
    Serial.println("Ready: hold a card to the reader");
}

void loop() {
    if (not reader.PICC_IsNewCardPresent() || not reader.PICC_ReadCardSerial()) {
        delay(50);
        return;
    }
    char uid [21];
    uid_to_hex(reader.uid, uid);
    reader.PICC_HaltA(); // one scan per tap

    const scan_result r = check_card(uid);
    if (not r.answered) {
        // No answer from the database: fail closed
        Serial.printf("%s: no answer from SQL Server\n", uid);
        signal(pin_red);
    } else if (r.accepted) {
        Serial.printf("%s: welcome, %s\n", uid, r.holder);
        signal(pin_green);
    } else {
        Serial.printf("%s: unknown or blocked card\n", uid);
        signal(pin_red);
    }
}

Before you use it for a door

A card's UID is easy to copy: cheap cards and phones can pretend to have any UID. That's fine for attendance, where the worst case is a wrong entry in a report. For a door lock, use cards with cryptographic authentication (e.g. MIFARE DESFire), keep the lock working when the network is down, and follow the fire safety rules for doors.