用python写一个树莓派连接RFID的代码
时间: 2024-05-09 13:21:07 浏览: 18
由于树莓派连接RFID需要使用硬件模块,因此我们需要安装MFRC522模块。
1. 安装MFRC522模块
```python
sudo pip install mfrc522
```
2. 编写代码
```python
import RPi.GPIO as GPIO
import mfrc522
import signal
continue_reading = True
# 停止程序的回调函数
def end_read(signal, frame):
global continue_reading
print("Ctrl+C detected, ending read.")
continue_reading = False
GPIO.cleanup()
# 信号处理
signal.signal(signal.SIGINT, end_read)
# 创建MFRC522实例
MIFAREReader = mfrc522.MFRC522()
# 主循环
while continue_reading:
# 检测是否有卡片出现
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# 如果读到卡片
if status == MIFAREReader.MI_OK:
print("Card detected")
# 获取卡片UID
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# 如果获取UID成功
if status == MIFAREReader.MI_OK:
# 输出UID
print("Card UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]))
```
3. 运行代码
```python
sudo python rfid.py
```
当RFID读到卡片时,程序将输出“Card detected”,并且输出卡片的UID。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)