What You're Building
Most "Arduino RFID door lock" tutorials stop at the same point: a card is scanned, an LED turns green, a relay clicks. That is a good first hour, but it is not a door lock. A real one has to answer questions the demo never asks. Who is allowed in, and how do you change that without re-uploading code? What happens when the power blips? Who opened the door at 2 a.m., and how would you ever know?
This build answers those questions with parts that cost very little. An Arduino Uno reads cards through an RC522 module, shows the result on a 16×2 I2C LCD, and releases a 12 V solenoid lock through a relay. Three things lift it above the usual demo:
- Master-card enrolment. The first card you ever scan becomes the master. Tap it, and for ten seconds every card you present is added to (or removed from) the allowed list. No re-flashing and no UIDs typed into source code.
- A real access log. Every grant, denial, enrolment and removal is written to EEPROM with a timestamp from a DS3231 clock, and you can read it back over Serial. The log is a ring buffer designed so the EEPROM lasts for years.
- Fail-closed behaviour. If the reader or clock is missing at boot, the lock stays locked and the LCD says why. The relay pin is set to its safe level before it becomes an output, so the lock does not twitch at power-up.
The complete sketch is below. It compiles cleanly for the Uno with warnings enabled and uses about 60% of flash and 29% of RAM, so there is plenty of room to extend it. Along the way we cover why each design decision was made, because that is what lets you adapt the project instead of copying it.
How an RFID Door Lock Actually Works
The RC522 is built around NXP's MFRC522 chip. It works at 13.56 MHz and speaks ISO/IEC 14443A, which is the family used by MIFARE Classic cards and keyfobs. Those are the blue fob and white card that ship with nearly every RC522 kit. The reader powers the passive tag through inductive coupling, so the card needs no battery, and the working distance is only a few centimetres.
When a card enters the field, the reader and card run a short anti-collision handshake, and the card reveals its UID, a unique serial number. MIFARE Classic 1K cards have a 4-byte UID. Our sketch compares that number against a list stored in EEPROM and decides what to do.
This matters for your expectations. The door lock authenticates the serial number, not a secret held inside the card. Cards also hold 1 KB of memory protected by keys, but we deliberately ignore it here because it adds complexity without fixing the core weakness (more on that in the security section). A related point catches people out: the cheap 125 kHz "EM4100" cards and the RDM6300 reader are a different, incompatible system. An RC522 will not read them.
The decision flow
The flowchart below shows what happens on every card tap. It is the same logic the code follows, so keep it open while reading the sketch.
Parts List
Everything here is common hobby hardware. The one decision to make early is the lock itself: a 12 V solenoid bolt needs its own supply, which is why the relay sits between it and the Arduino.
Components
14 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Notes on the parts that trip people up
Cards with 4-byte UIDs. The sketch stores 4-byte UIDs, which covers the cards and fobs in an RC522 kit. Newer tags such as NTAG stickers have 7-byte UIDs. The sketch detects these and shows "Unsupported tag" instead of silently misreading them. Supporting longer UIDs is a good extension, and the storage layout makes it a small change.
The buzzer. An Uno pin should supply 20 mA comfortably and 40 mA only as an absolute maximum. Many "5 V active buzzers" draw about 30 mA. If yours does, drive it through a small NPN transistor (a BC547 or 2N2222 with a 1 kΩ base resistor) rather than straight from the pin.
The relay module. Most blue SRD-05VDC boards are active-LOW: the relay switches on when the input pin goes low. The sketch has one constant, RELAY_ACTIVE_LOW, so you can flip the logic if your board is the other way round. Check the contact rating printed on the relay and compare it with your solenoid's current. Many 12 V solenoid locks draw roughly an amp when energised, so confirm the figure on your lock's datasheet.
The RTC. A DS3231 keeps accurate time and survives power loss on its coin cell, which is what makes the log meaningful. If you do not have one, set USE_RTC to 0 and the log records entry numbers instead of dates. One quirk: on some common DS3231 boards the battery holder has a charging circuit meant for rechargeable LIR2032 cells. Using a non-rechargeable CR2032 there is not recommended, so check your board's documentation.
⚠️ Warning
Electric locks and escape routes: a door that traps people inside is a life-safety hazard, and fire codes in most places require free exit on escape routes. Use this project for a workshop cabinet, a lab drawer, a hobby-room door with a mechanical override, or as a learning build. Do not fit it to the only exit of a room or building without a compliant release mechanism.
Wiring
There are three separate circuits here: the SPI reader, the I2C bus (LCD and clock), and the high-current lock circuit. Keep them mentally separate and the build is straightforward.
RC522 to Arduino Uno (SPI)
| RC522 pin | Arduino Uno | Notes |
|---|---|---|
| SDA (SS) | D10 | Chip select. Level-divide (see below) |
| SCK | D13 | Hardware SPI clock. Level-divide |
| MOSI | D11 | Hardware SPI. Level-divide |
| MISO | D12 | Output from the RC522, no divider needed |
| RST | D9 | Level-divide |
| IRQ | not connected | Unused by this sketch |
| GND | GND | |
| 3.3V | 3.3V | Never 5 V |
Why the level dividers
The RC522 is a 3.3 V device. Its supply pin must go to 3.3 V, and its logic inputs are specified for 3.3 V levels. An Uno drives its outputs at 5 V. Plenty of tutorials wire the pins straight across and report that it works, and it often does, but that is running the chip out of specification and you are relying on luck for years of service.
The fix costs pennies. On each of the four Uno-to-RC522 signal lines (SS, SCK, MOSI, RST), put a 1 kΩ resistor in series from the Arduino pin and a 2 kΩ resistor from the RC522 side to ground. That divides 5 V down to roughly 3.3 V. A 4-channel logic-level converter does the same job more neatly. MISO needs nothing, because the RC522 outputs 3.3 V and an Uno reads anything above about 3 V as high.
The Uno's 3.3 V pin is rated for about 50 mA, and the RC522 draws well under that, so powering it from the board is fine.
LCD, RTC and indicators
The LCD backpack and the DS3231 both sit on the I2C bus, so they share two wires. Connect SDA to A4 and SCL to A5, and power both from 5 V and GND. Their I2C addresses do not clash: the LCD is usually 0x27 (sometimes 0x3F) and the DS3231 is 0x68. If the screen stays blank, run a standard I2C scanner sketch to find the real address and change LCD_ADDR. The contrast trimmer on the back of the backpack also needs to be set correctly or the characters will be invisible.
| Part | Arduino Uno |
|---|---|
| Relay IN | D4 |
| Green LED (via 220 Ω) | D6 |
| Red LED (via 220 Ω) | D7 |
| Active buzzer | D8 (or via a transistor) |
| LCD + DS3231 SDA / SCL | A4 / A5 |
The lock circuit
The solenoid never connects to an Arduino pin or to the Arduino's 5 V rail. Power it from its own 12 V supply, switched by the relay's contacts:
| Connection | To |
|---|---|
| 12 V supply (+) | Relay COM |
| Relay NO | Solenoid (+) |
| Solenoid (−) | 12 V supply (−) |
| 1N4007 diode | Across the solenoid, stripe (cathode) on the (+) side |
The relay's switched contacts are electrically isolated from the coil side, so the 12 V loop does not need a shared ground with the Arduino. The relay board gets its 5 V and GND from the Arduino. The diode is not optional. A solenoid is an inductor, and when the relay opens it, the collapsing magnetic field produces a voltage spike that can arc across the relay contacts and generate noise that resets the Arduino. The diode gives that current a harmless path.
Using the NO (normally open) contact means the lock is held by its spring or latch when the relay is off. For most solenoid bolts that is the secure state. If you buy a "fail-safe" lock that unlocks when powered, the logic reverses, so check which type you have.
Libraries
Install these three from Sketch → Include Library → Manage Libraries in the Arduino IDE:
| Library | Author | Used for |
|---|---|---|
| MFRC522 | GithubCommunity | RC522 reader |
| LiquidCrystal I2C | Frank de Brabander | LCD through the backpack |
| RTClib | Adafruit | DS3231 clock (also installs Adafruit BusIO) |
SPI, Wire and EEPROM are built into the Arduino core.
The Complete Sketch
Paste this into a new sketch and upload it with the board set to Arduino Uno. We compile-checked it for the Uno (avr-gcc, Arduino AVR core 1.8.6) with warnings enabled, both with and without the RTC option, and it came to 19,718 bytes of flash (60%) and 603 bytes of RAM (29%) with the clock enabled. Compilation proves the syntax and memory budget, not your wiring, so work through the commissioning steps below with the lock disconnected before you trust it.
/*
Arduino RFID Door Lock with Access Log & LCD Display
SolderHub (solderhub.com)
Board : Arduino Uno (ATmega328P)
Reader : RC522 (SPI, 3.3 V)
Display : 16x2 LCD with I2C backpack (PCF8574)
Clock : DS3231 RTC (I2C) - optional, see USE_RTC
Lock : 5 V relay module + 12 V solenoid lock (separate supply)
Libraries: MFRC522, LiquidCrystal I2C (Frank de Brabander), RTClib (Adafruit)
How it works
- First card ever scanned becomes the MASTER card.
- Tap MASTER -> 10 s program mode. Tap any other card to ADD it (or REMOVE it
if it is already enrolled). Tap MASTER again to leave program mode.
- Enrolled card -> door unlocks for UNLOCK_MS. Unknown card -> denied.
- Every event is written to a 40-entry ring-buffer log in EEPROM.
- Serial Monitor (9600 baud) commands: LOG, LIST, CLEARLOG, RESET
*/
#include <SPI.h>
#include <Wire.h>
#include <EEPROM.h>
#include <MFRC522.h>
#include <LiquidCrystal_I2C.h>
#define USE_RTC 1 // set to 0 if you have no DS3231 (log then shows entry numbers only)
#if USE_RTC
#include <RTClib.h>
RTC_DS3231 rtc;
#endif
// ---------- Pins ----------
const uint8_t PIN_SS = 10; // RC522 SDA/SS
const uint8_t PIN_RST = 9; // RC522 RST
const uint8_t PIN_RELAY = 4;
const uint8_t PIN_LED_GREEN = 6;
const uint8_t PIN_LED_RED = 7;
const uint8_t PIN_BUZZER = 8; // active buzzer
// ---------- Settings ----------
const bool RELAY_ACTIVE_LOW = true; // most 5 V relay modules switch ON with a LOW signal
const uint16_t UNLOCK_MS = 4000; // how long the lock stays released
const uint16_t MESSAGE_MS = 2500; // how long result messages stay on the LCD
const uint16_t PROGRAM_MS = 10000; // program-mode window after tapping the master card
const uint8_t LCD_ADDR = 0x27; // try 0x3F if the LCD stays blank
// ---------- EEPROM layout (1 KB on the Uno) ----------
const uint8_t MAGIC = 0xA5;
const uint8_t MAX_CARDS = 10;
const uint8_t LOG_SIZE = 40;
const int ADDR_MAGIC = 0; // 0xA5 = storage initialised
const int ADDR_HAS_MASTER = 1; // 1 = a master card is enrolled
const int ADDR_MASTER = 2; // 4 bytes
const int ADDR_COUNT = 6; // number of enrolled cards
const int ADDR_CARDS = 8; // MAX_CARDS * 4 bytes
const int ADDR_LOG = 64; // LOG_SIZE * sizeof(LogEntry)
struct LogEntry {
uint32_t seq; // 1, 2, 3 ... ; 0 means "empty slot"
uint32_t time; // Unix time from the RTC (0 if no RTC)
uint8_t uid[4];
uint8_t event;
};
enum Event : uint8_t { EV_GRANTED = 1, EV_DENIED = 2, EV_ADDED = 3, EV_REMOVED = 4 };
static_assert(ADDR_LOG + LOG_SIZE * sizeof(LogEntry) <= 1024, "Log does not fit in EEPROM");
// ---------- Objects and state ----------
MFRC522 rfid(PIN_SS, PIN_RST);
LiquidCrystal_I2C lcd(LCD_ADDR, 16, 2);
bool hasMaster = false;
uint8_t masterUid[4];
uint8_t cardCount = 0;
uint32_t nextSeq = 1;
uint8_t nextSlot = 0;
bool unlocked = false;
unsigned long unlockUntil = 0;
unsigned long messageUntil = 0; // 0 = no message showing
unsigned long programUntil = 0; // 0 = not in program mode
uint8_t lastMinute = 255;
// ---------- Small helpers ----------
unsigned long deadline(uint16_t ms) {
unsigned long t = millis() + ms;
return t ? t : 1; // never return 0 (0 means "inactive")
}
bool expired(unsigned long t) {
return (long)(millis() - t) >= 0;
}
void relay(bool release) {
digitalWrite(PIN_RELAY, (release == RELAY_ACTIVE_LOW) ? LOW : HIGH);
}
void beep(uint16_t ms) {
digitalWrite(PIN_BUZZER, HIGH);
delay(ms);
digitalWrite(PIN_BUZZER, LOW);
}
void beepTimes(uint8_t n, uint16_t ms) {
for (uint8_t i = 0; i < n; i++) {
beep(ms);
if (i < n - 1) delay(ms);
}
}
void uidToText(const uint8_t *uid, char *out) { // out needs 12 bytes
snprintf(out, 12, "%02X:%02X:%02X:%02X", uid[0], uid[1], uid[2], uid[3]);
}
uint32_t unixNow() {
#if USE_RTC
return rtc.now().unixtime();
#else
return 0;
#endif
}
// ---------- LCD ----------
void showMessage(const __FlashStringHelper *line1, const __FlashStringHelper *line2, uint16_t ms) {
lcd.clear();
lcd.setCursor(0, 0); lcd.print(line1);
lcd.setCursor(0, 1); lcd.print(line2);
messageUntil = deadline(ms);
}
void showMessageUid(const __FlashStringHelper *line1, const uint8_t *uid, uint16_t ms) {
char text[12];
uidToText(uid, text);
lcd.clear();
lcd.setCursor(0, 0); lcd.print(line1);
lcd.setCursor(0, 1); lcd.print(text);
messageUntil = deadline(ms);
}
void drawBase() { // the screen shown when nothing else is happening
digitalWrite(PIN_LED_GREEN, unlocked ? HIGH : LOW);
digitalWrite(PIN_LED_RED, programUntil ? HIGH : LOW);
lcd.clear();
lcd.setCursor(0, 0);
if (programUntil) {
lcd.print(F("PROGRAM MODE"));
lcd.setCursor(0, 1);
lcd.print(F("Tap card: +/-"));
} else {
lcd.print(F("RFID Door Lock"));
lcd.setCursor(0, 1);
#if !USE_RTC
lcd.print(F("Scan your card"));
#endif
lastMinute = 255; // force the clock to redraw
}
}
void updateClock() {
#if USE_RTC
static unsigned long nextCheck = 0;
if ((long)(millis() - nextCheck) < 0) return;
nextCheck = millis() + 1000;
DateTime t = rtc.now();
if (t.minute() == lastMinute) return;
lastMinute = t.minute();
lcd.setCursor(0, 1);
lcd.print(F("Scan card "));
if (t.hour() < 10) lcd.print('0');
lcd.print(t.hour());
lcd.print(':');
if (t.minute() < 10) lcd.print('0');
lcd.print(t.minute());
#endif
}
// ---------- Card storage ----------
int8_t findCard(const uint8_t *uid) {
for (uint8_t i = 0; i < cardCount; i++) {
uint8_t stored[4];
for (uint8_t b = 0; b < 4; b++) stored[b] = EEPROM.read(ADDR_CARDS + i * 4 + b);
if (memcmp(stored, uid, 4) == 0) return i;
}
return -1;
}
bool addCard(const uint8_t *uid) {
if (cardCount >= MAX_CARDS) return false;
for (uint8_t b = 0; b < 4; b++) EEPROM.update(ADDR_CARDS + cardCount * 4 + b, uid[b]);
cardCount++;
EEPROM.update(ADDR_COUNT, cardCount);
return true;
}
void removeCard(uint8_t index) {
uint8_t last = cardCount - 1;
if (index != last) { // move the last card into the gap
for (uint8_t b = 0; b < 4; b++)
EEPROM.update(ADDR_CARDS + index * 4 + b, EEPROM.read(ADDR_CARDS + last * 4 + b));
}
cardCount--;
EEPROM.update(ADDR_COUNT, cardCount);
}
bool isMaster(const uint8_t *uid) {
return hasMaster && memcmp(masterUid, uid, 4) == 0;
}
void saveMaster(const uint8_t *uid) {
memcpy(masterUid, uid, 4);
for (uint8_t b = 0; b < 4; b++) EEPROM.update(ADDR_MASTER + b, uid[b]);
EEPROM.update(ADDR_HAS_MASTER, 1);
hasMaster = true;
}
// ---------- Access log (ring buffer with sequence numbers) ----------
// Each entry carries its own sequence number, so no "head pointer" has to be
// rewritten on every event. That spreads EEPROM wear over all 40 slots.
void logEvent(const uint8_t *uid, uint8_t event) {
LogEntry e;
e.seq = nextSeq++;
e.time = unixNow();
memcpy(e.uid, uid, 4);
e.event = event;
EEPROM.put(ADDR_LOG + nextSlot * (int)sizeof(LogEntry), e);
nextSlot = (nextSlot + 1) % LOG_SIZE;
}
bool slotUsed(uint32_t seq) {
return seq != 0 && seq != 0xFFFFFFFFUL;
}
void scanLog() { // find newest entry after a reboot
uint32_t best = 0;
int8_t bestSlot = -1;
for (uint8_t i = 0; i < LOG_SIZE; i++) {
uint32_t seq;
EEPROM.get(ADDR_LOG + i * (int)sizeof(LogEntry), seq); // seq is the first field
if (slotUsed(seq) && seq > best) { best = seq; bestSlot = i; }
}
nextSeq = best + 1;
nextSlot = (bestSlot < 0) ? 0 : (bestSlot + 1) % LOG_SIZE;
}
void clearLog() {
for (uint8_t i = 0; i < LOG_SIZE; i++)
for (uint8_t b = 0; b < 4; b++) EEPROM.update(ADDR_LOG + i * (int)sizeof(LogEntry) + b, 0);
nextSeq = 1;
nextSlot = 0;
}
void factoryReset() {
EEPROM.update(ADDR_MAGIC, MAGIC);
EEPROM.update(ADDR_HAS_MASTER, 0);
for (uint8_t b = 0; b < 4; b++) EEPROM.update(ADDR_MASTER + b, 0);
EEPROM.update(ADDR_COUNT, 0);
clearLog();
hasMaster = false;
cardCount = 0;
}
void loadStorage() {
if (EEPROM.read(ADDR_MAGIC) != MAGIC) factoryReset();
hasMaster = EEPROM.read(ADDR_HAS_MASTER) == 1;
for (uint8_t b = 0; b < 4; b++) masterUid[b] = EEPROM.read(ADDR_MASTER + b);
cardCount = EEPROM.read(ADDR_COUNT);
if (cardCount > MAX_CARDS) cardCount = 0; // corrupted value: fail closed
scanLog();
}
// ---------- Serial tools ----------
const __FlashStringHelper *eventName(uint8_t event) {
switch (event) {
case EV_GRANTED: return F("GRANTED");
case EV_DENIED: return F("DENIED");
case EV_ADDED: return F("ADDED");
case EV_REMOVED: return F("REMOVED");
default: return F("?");
}
}
void printLog() {
uint8_t shown = 0;
Serial.println(F("--- ACCESS LOG (oldest first) ---"));
for (uint8_t k = 0; k < LOG_SIZE; k++) {
uint8_t slot = (nextSlot + k) % LOG_SIZE;
LogEntry e;
EEPROM.get(ADDR_LOG + slot * (int)sizeof(LogEntry), e);
if (!slotUsed(e.seq)) continue;
char uidText[12], stamp[26];
uidToText(e.uid, uidText);
if (e.time) {
#if USE_RTC
DateTime dt(e.time);
snprintf(stamp, sizeof(stamp), "%04u-%02u-%02u %02u:%02u:%02u",
dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute(), dt.second());
#endif
} else {
strcpy(stamp, "no time");
}
Serial.print('#'); Serial.print(e.seq);
Serial.print('\t'); Serial.print(stamp);
Serial.print('\t'); Serial.print(uidText);
Serial.print('\t'); Serial.println(eventName(e.event));
shown++;
}
if (!shown) Serial.println(F("(empty)"));
}
void printCards() {
Serial.println(F("--- ENROLLED CARDS ---"));
char text[12];
if (hasMaster) { uidToText(masterUid, text); Serial.print(F("MASTER ")); Serial.println(text); }
else { Serial.println(F("No master card yet - scan one to create it.")); }
for (uint8_t i = 0; i < cardCount; i++) {
uint8_t uid[4];
for (uint8_t b = 0; b < 4; b++) uid[b] = EEPROM.read(ADDR_CARDS + i * 4 + b);
uidToText(uid, text);
Serial.print(i + 1); Serial.print(F(" ")); Serial.println(text);
}
}
void runCommand(const char *cmd) {
if (strcmp_P(cmd, PSTR("LOG")) == 0) printLog();
else if (strcmp_P(cmd, PSTR("LIST")) == 0) printCards();
else if (strcmp_P(cmd, PSTR("CLEARLOG")) == 0) { clearLog(); Serial.println(F("Log cleared.")); }
else if (strcmp_P(cmd, PSTR("RESET")) == 0) {
factoryReset();
Serial.println(F("Factory reset done. The next card scanned becomes the master."));
programUntil = 0;
drawBase();
} else {
Serial.println(F("Commands: LOG, LIST, CLEARLOG, RESET"));
}
}
void handleSerial() {
static char buf[12];
static uint8_t n = 0;
while (Serial.available()) {
char c = Serial.read();
if (c == '\r' || c == '\n') {
if (n) { buf[n] = 0; runCommand(buf); n = 0; }
} else if (n < sizeof(buf) - 1) {
buf[n++] = toupper(c);
}
}
}
// ---------- Door actions ----------
void lockDoor() {
relay(false);
unlocked = false;
digitalWrite(PIN_LED_GREEN, LOW);
}
void grantAccess(const uint8_t *uid) {
logEvent(uid, EV_GRANTED);
relay(true);
unlocked = true;
unlockUntil = deadline(UNLOCK_MS);
digitalWrite(PIN_LED_GREEN, HIGH);
digitalWrite(PIN_LED_RED, LOW);
showMessage(F("ACCESS GRANTED"), F("Door unlocked"), UNLOCK_MS);
beep(120);
}
void denyAccess(const uint8_t *uid) {
logEvent(uid, EV_DENIED);
digitalWrite(PIN_LED_RED, HIGH);
showMessageUid(F("ACCESS DENIED"), uid, MESSAGE_MS);
beepTimes(3, 80);
}
void handleProgramTap(const uint8_t *uid) {
int8_t index = findCard(uid);
if (index >= 0) {
removeCard(index);
logEvent(uid, EV_REMOVED);
showMessageUid(F("Card REMOVED"), uid, MESSAGE_MS);
beep(400);
} else if (addCard(uid)) {
logEvent(uid, EV_ADDED);
showMessageUid(F("Card ADDED"), uid, MESSAGE_MS);
beepTimes(2, 100);
} else {
showMessage(F("MEMORY FULL"), F("Remove a card"), MESSAGE_MS);
beepTimes(3, 80);
}
programUntil = deadline(PROGRAM_MS); // keep the window open for the next card
}
void handleCard() {
if (rfid.uid.size != 4) { // 7- and 10-byte UIDs (e.g. NTAG) are not supported here
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
showMessage(F("Unsupported tag"), F("Need 4-byte UID"), MESSAGE_MS);
beepTimes(2, 80);
return;
}
uint8_t uid[4];
memcpy(uid, rfid.uid.uidByte, 4);
rfid.PICC_HaltA(); // one tap = one event
rfid.PCD_StopCrypto1();
char text[12];
uidToText(uid, text);
Serial.print(F("Card ")); Serial.println(text);
if (!hasMaster) { // very first card becomes the master
saveMaster(uid);
logEvent(uid, EV_ADDED);
showMessageUid(F("MASTER SAVED"), uid, MESSAGE_MS);
beepTimes(2, 150);
return;
}
if (isMaster(uid)) { // master toggles program mode
if (programUntil) {
programUntil = 0;
digitalWrite(PIN_LED_RED, LOW);
showMessage(F("Program mode"), F("finished"), 1200);
} else {
programUntil = deadline(PROGRAM_MS);
messageUntil = 0;
drawBase();
}
beep(150);
return;
}
if (programUntil) { handleProgramTap(uid); return; }
if (findCard(uid) >= 0) grantAccess(uid);
else denyAccess(uid);
}
[[noreturn]] void fatal(const __FlashStringHelper *msg) {
relay(false); // stay locked
lcd.clear();
lcd.setCursor(0, 0); lcd.print(F("HARDWARE ERROR"));
lcd.setCursor(0, 1); lcd.print(msg);
Serial.print(F("FATAL: ")); Serial.println(msg);
while (true) { delay(1000); }
}
// ---------- Arduino entry points ----------
void setup() {
digitalWrite(PIN_RELAY, RELAY_ACTIVE_LOW ? HIGH : LOW); // set level BEFORE switching to output:
pinMode(PIN_RELAY, OUTPUT); // avoids a brief unlock pulse at power-up
pinMode(PIN_LED_GREEN, OUTPUT);
pinMode(PIN_LED_RED, OUTPUT);
pinMode(PIN_BUZZER, OUTPUT);
Serial.begin(9600);
Wire.begin();
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0); lcd.print(F("Starting..."));
SPI.begin();
rfid.PCD_Init();
uint8_t version = rfid.PCD_ReadRegister(MFRC522::VersionReg);
if (version == 0x00 || version == 0xFF) fatal(F("RC522 not found"));
#if USE_RTC
if (!rtc.begin()) fatal(F("RTC not found"));
if (rtc.lostPower()) rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
#endif
loadStorage();
drawBase();
Serial.println(F("RFID door lock ready. Commands: LOG, LIST, CLEARLOG, RESET"));
if (!hasMaster) Serial.println(F("No master card yet - scan one to create it."));
}
void loop() {
handleSerial();
if (unlocked && expired(unlockUntil)) lockDoor();
if (messageUntil && expired(messageUntil)) { messageUntil = 0; drawBase(); }
if (programUntil && expired(programUntil)) {
programUntil = 0;
if (!messageUntil) drawBase();
}
if (!messageUntil && !programUntil) updateClock();
if (!rfid.PICC_IsNewCardPresent()) return;
if (!rfid.PICC_ReadCardSerial()) return;
handleCard();
}How the Code Works
One tap, one event
The main loop does three jobs on every pass: read Serial commands, check timers, and poll the reader. When a card arrives, handleCard() copies its UID, then immediately calls PICC_HaltA(). That puts the card to sleep so it will not be re-read while it sits on the reader. You must lift the card away and present it again for a second event, which is exactly what you want from a door lock.
Why nothing blocks
A common beginner pattern is delay(3000) to hold the door open. While the Arduino sits in that delay it cannot read Serial, cannot update the screen, and cannot react to anything. Here the unlock, the message timeout and the program-mode window are all deadlines compared against millis(). The helper expired() uses (long)(millis() - t) >= 0, which keeps working correctly when the 32-bit millisecond counter wraps around after about 49 days. The only short delay() calls left are the buzzer beeps, which are a fraction of a second.
The EEPROM map
The Uno's ATmega328P has 1,024 bytes of EEPROM, and the sketch uses about 584 of them. The first bytes hold a magic number, a master flag, the master UID and the card count. The enrolled cards follow, four bytes each, then the log. A magic value of 0xA5 tells the sketch the storage has been initialised, so a brand-new chip (all bytes 0xFF) triggers a clean first-run setup instead of being read as garbage.
A log designed for wear
EEPROM cells are rated for roughly 100,000 write cycles on this chip. The naive way to build a log is to keep a "next slot" pointer in EEPROM and rewrite it after every event. That one byte would take the wear of the entire log and fail first, after 100,000 events.
The sketch avoids this by giving every entry its own sequence number (seq), which counts 1, 2, 3 and so on. Nothing records where the newest entry is. After a reboot, scanLog() reads the first four bytes of each of the 40 slots, finds the highest sequence number, and resumes in the slot after it. Now each slot is rewritten only once every 40 events, so the log can absorb about 4 million events before any cell reaches its rated limit. Writes use EEPROM.update() and EEPROM.put(), which skip bytes that already hold the right value.
The log holds 40 entries, and once full the oldest are overwritten. That is the right trade for a hobby lock. If you need months of history on a busy door, the same entry format can be written to an SD card instead.
Fail-closed by design
Several small choices keep the door safe when things go wrong:
- Boot state. In
setup()the relay pin is given its "locked" level withdigitalWrite()beforepinMode(OUTPUT). On an AVR, writing high to an input pin enables its pull-up, so the pin switches to output already at the right level and the relay never twitches. - Hardware checks. The sketch reads the RC522 version register. A value of
0x00or0xFFmeans no chip is answering on SPI (usually wiring), and the sketch stops with the lock closed. A missing RTC does the same. - Bad data. If the stored card count is nonsense, it is treated as zero cards. An empty list denies everyone rather than admitting anyone.
- Unknown tags. Anything that is not a 4-byte UID is refused with a message instead of being truncated into a possibly matching value.
Enrolment workflow
On a fresh board the first card scanned is saved as the master. After that, tapping the master card turns on the red LED and the LCD reads PROGRAM MODE. For the next ten seconds, each card you present is toggled: new cards are added, enrolled cards are removed. Each action keeps the window open for another ten seconds, so you can enrol a whole batch in one go. Tap the master again to finish. If you ever lose the master card, the RESET Serial command wipes everything so the next card becomes the new master. That requires USB access to the board, which is why the controller should live on the secure side of the door.
Steps
- 1Wire the reader, LCD and RTC first. Leave the relay board and solenoid disconnected for now.
- 2Install the three libraries, select Arduino Uno and the correct port, then upload the sketch.
- 3Open Serial Monitor at 9600 baud. You should see "RFID door lock ready" and the message that no master card exists yet.
- 4Scan your keyfob. The LCD shows MASTER SAVED and you hear two beeps. This is your master card, so label it and keep it safe.
- 5Tap the master again. The red LED lights and the LCD shows PROGRAM MODE.
- 6Tap each card you want to allow, one at a time. The LCD shows Card ADDED with its UID. Tap the master to finish.
- 7Scan an enrolled card: you should see ACCESS GRANTED, the green LED and a click from the relay once it is connected. Scan an unenrolled card: ACCESS DENIED and three beeps.
- 8Type LIST and LOG in Serial Monitor to check the card list and the log of what you just did.
- 9Power-cycle the board and confirm the cards and log survive, and that the relay stays off during boot.
- 10Only now connect the relay output to the solenoid circuit, with the flyback diode fitted, and test again.
Reading the Access Log
Type LOG in the Serial Monitor to print the log oldest-first. Each line has the entry number, the RTC timestamp, the card UID and the event. The example below shows the format; your UIDs and times will differ.
--- ACCESS LOG (oldest first) ---
#1 2026-10-19 09:12:44 A3:B2:C1:D4 ADDED
#2 2026-10-19 09:13:20 5E:11:9C:07 ADDED
#3 2026-10-19 09:15:02 5E:11:9C:07 GRANTED
#4 2026-10-19 11:47:31 77:0A:42:E9 DENIED
#5 2026-10-19 18:03:10 5E:11:9C:07 GRANTEDBecause denied attempts are logged with the UID that was presented, the log also tells you whether someone is repeatedly trying a card that is not enrolled. If the RTC's coin cell has died and the board loses power, the sketch notices (lostPower()) and resets the clock to the compile time. Entries logged before and after that point will then show inconsistent times, so replace the cell if you ever see this.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| LCD says "RC522 not found" | SPI wiring, or divider on the wrong pin | Recheck SS/SCK/MOSI/MISO/RST against the table. Make sure 3.3 V is on the reader. MISO must not go through a divider |
| LCD backlight on, no text | Wrong I2C address or contrast | Run an I2C scanner and set LCD_ADDR. Turn the contrast trimmer on the backpack |
| LCD says "RTC not found" | DS3231 not on A4/A5 or no power | Check SDA/SCL and 5 V. The scanner should show 0x68 |
| Card is never detected | Card too far, wrong card type | Keep it within a few centimetres. 125 kHz cards will not work with an RC522 |
| "Unsupported tag" | Tag has a 7- or 10-byte UID | Use a MIFARE Classic card/fob, or extend the sketch to longer UIDs |
| Relay clicks the wrong way round | Active-HIGH relay module | Set RELAY_ACTIVE_LOW to false |
| Arduino resets when the lock fires | Missing flyback diode, or lock powered from the Arduino | Fit the 1N4007 across the solenoid. Use the separate 12 V supply |
| Lock stays energised after the beep | Relay logic inverted, or relay wired to NC | Check RELAY_ACTIVE_LOW and use the NO contact |
| Log timestamps are wrong | RTC battery flat or first-time set | Replace the cell and re-upload to reset the time |
| Reader works on the bench, flaky in the door | Long SPI wires, metal behind the antenna | Keep the SPI leads as short as practical (tens of centimetres) and keep metal away from the antenna coil |
What This Lock Can and Can't Protect
Being honest about security makes a hobby project better. This design identifies a card by its UID, and a UID is not a secret. A MIFARE Classic UID can be read by any compatible reader, and "magic" cards with a rewritable UID are cheap and easy to buy. So anyone who can briefly read your card can clone it. The crypto on MIFARE Classic itself is also long broken, which is why we ignore the card's memory.
That is acceptable for a workshop cabinet or a project demo. It is not acceptable as the only protection for something valuable. The sensible hardening steps are cheap:
- Mount the Arduino, relay and wiring on the secure side of the door. Only the reader should be exposed outside, because anyone reaching the controller's wires can bypass the whole system.
- Treat the master card as a key. Do not leave it with the door.
- Use a physical key or mechanical override as a backup, which also solves the power-failure case.
- Move to a reader and card system with real mutual authentication if the stakes are high.
Ideas to Take It Further
- Request-to-exit button. A push button on the inside that unlocks the door for a few seconds, logged as its own event.
- Longer UIDs. Store 7-byte UIDs so NTAG stickers and phones' NFC tags work.
- Lockout. After five denied scans in a row, ignore the reader for 30 seconds.
- SD card logging. Write the same
LogEntryrecords to a CSV on an SD module for unlimited history. - Move to an ESP32. Push log events to a phone with Wi-Fi, for example over ESP-NOW or MQTT, and unlock remotely.
Frequently Asked Questions
Can I use an Arduino Nano or Mega instead of the Uno? Yes, but the SPI pins change. On a Nano they match the Uno (D11, D12, D13). On a Mega they are D51 (MOSI), D50 (MISO) and D52 (SCK). Always check the board's pinout rather than copying the Uno wiring.
How many cards can it hold? Ten, plus the master. Change MAX_CARDS to store more, keeping the EEPROM map in mind. The static_assert stops compilation if the log would no longer fit.
Why a master card instead of hard-coded UIDs? Hard-coded UIDs force you to re-upload code every time someone joins or leaves. With a master card, enrolment takes seconds and needs no computer.
Do I need the RTC? No, but without it the log has no dates. Set USE_RTC to 0 and the sketch still works, logging entry numbers only.
Will it still work after a power cut? Yes. Cards and log live in EEPROM, which keeps its contents without power, and the DS3231 keeps time on its coin cell. The relay releases when power is lost, so the lock reverts to its resting state.
Wrap-Up
An RFID reader and a relay will get you a blinking LED in an hour, but the parts that make a lock usable are the ones this build adds: enrolment without re-flashing, a log you can trust, and behaviour that stays safe when wiring or power goes wrong. Build it with the lock disconnected first, check each step in order, and keep its limits in mind. Used within them, it is a solid foundation for shared workshop access, a tool cabinet, or a classroom demonstration of how real access-control systems are structured.



