基于 Arduino 与 Python 的可靠 RFID 考勤系统
组件与物料
- Arduino UNO ×1
- RFID-RC522 读写模块(含卡/钥匙扣标签)×1
- 杜邦线若干
软件环境
- Arduino IDE
- XAMPP(Windows)或 LAMP(Linux)集成 Apache + MySQL + phpMyAdmin
- Python 3 +
pyserial+mysqlclient(或PyMySQL)
系统架构
无需以太网扩展板。Arduino 通过 USB/串口将读取到的 UID 发送给 PC(或树莓派),Python 脚本监听串口,解析 UID 后写入 MySQL 数据库(phpMyAdmin 管理),实现考勤记录的实时落库与查询。
接线图(RC522 → Arduino UNO)
| RC522 引脚 | Arduino UNO | Arduino Mega |
|---|---|---|
| RST | D9 | D9 |
| SDA (SS) | D10 | D53 |
| MOSI | D11 | D51 |
| MISO | D12 | D50 |
| SCK | D13 | D52 |
| 3.3V | 3.3V | 3.3V |
| GND | GND | GND |
| IRQ | 悬空 | 悬空 |
注意:RC522 必须供 3.3V,严禁接 5V。
关键库
- Arduino 端:
MFRC522库(库管理器安装) - Python 端:
pyserial(串口通信)、mysqlclient(数据库写入)
工作流程
- Arduino 初始化 RC522,循环轮询标签,读取 4 字节 UID,经串口发送(格式如
UID: 45 8D 08 88)。 - Python 脚本
attendance.py打开串口,持续读取行,正则提取 UID。 - 连接 MySQL,插入/更新
attendance表(字段:uid, name, timestamp, status)。 - phpMyAdmin 可视化查看、导出考勤记录。
代码要点
Arduino 端(片段)
#include
#include
#define RST_PIN 9
#define SS_PIN 10
MFRC522 rfid(SS_PIN, RST_PIN);
void setup() {
Serial.begin(9600);
SPI.begin();
rfid.PCD_Init();
}
void loop() {
if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
Serial.print("UID:");
for (byte i = 0; i < rfid.uid.size; i++) {
Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(rfid.uid.uidByte[i], HEX);
}
Serial.println();
rfid.PICC_HaltA();
}
delay(100);
}
Python 端(片段)
import serial, re, mysql.connector, time
ser = serial.Serial('COM3', 9600, timeout=1) # Linux 下为 /dev/ttyUSB0
db = mysql.connector.connect(host='localhost', user='root', passwd='', database='attendance_db')
cursor = db.cursor()
uid_pattern = re.compile(r'UID:((?:\s[0-9A-F]{2})+)', re.I)
while True:
line = ser.readline().decode().strip()
m = uid_pattern.search(line)
if m:
uid = m.group(1).strip().upper().replace(' ', '')
now = time.strftime('%Y-%m-%d %H:%M:%S')
# 查询用户名,此处简化为直接记录
sql = "INSERT INTO attendance (uid, timestamp) VALUES (%s, %s) ON DUPLICATE KEY UPDATE timestamp=%s"
cursor.execute(sql, (uid, now, now))
db.commit()
print(f"[LOG] {now} - {uid}")
进阶建议
- 将 Arduino 替换为 ESP32/ESP8266,直接 WiFi 入库,免去 PC/树莓派中转。
- 增加蜂鸣器/LED 本地反馈,提升用户体验。
- 数据库设计加入用户表、部门表、异常打卡报警等。
制造工艺
- 集成二维码、RFID与体温验证的门禁控制系统
- 树莓派与 Python 构建远程温度传感器:分步实战指南
- 树莓派与Python构建机器人:完整指南
- Arduino RFID 门锁系统 – RC522 模块实现安全门禁
- 基于 Arduino、1Sheeld 与红外控制的万能安卓遥控器
- Arduino 与智能手机打造智能电压表——简单易做的 DIY 项目
- u-blox LEA-6H GPS 模块:Arduino 与 Python 集成指南
- 使用 Arduino Nano 和 RDA8057M 制作紧凑型 FM 收音机
- 基于 Arduino 与 Google Sheets 的实时 RFID 考勤系统
- 精准降雨预测:基于 Arduino、Python 与 Keras 的端到端气象站系统
- 使用 Arduino 制作便携式 RFID 门锁——分步指南
- Arduino + BitVoicer Server 语音控制二轮机器人:从硬件到语音指令全流程