DEV Community

codemee
codemee

Posted on

4 1

在 ESP32 上以 MicroPython 使用 RFID-RC522 模組

使用 ESP8266 撰寫 MicroPython 使用 RFID-RC522 模組時, 通常會載入 mfrc522 程式庫, 不過如果將這個程式庫直接用在 ESP32 上的 MicroPython, 會得到如下的錯誤:

RuntimeError: Unsupported platform
Enter fullscreen mode Exit fullscreen mode

這是因為這個程式庫內會排除他不認得的開發板, 如果要用在 ESP32 上, 就必須修改原始程式庫中 mfrc522.py 的第 32 行, 讓它可以認得 ESP32:

        elif board == 'esp8266' or board == 'esp32':
Enter fullscreen mode Exit fullscreen mode

其餘程式都不需要修改, 將此檔案上傳到 ESP32 後, 就可以撰寫 MicroPython 程式使用 RFID-RC522 模組了, 例如:

from machine import Pin
import mfrc522, time

rfid = mfrc522.MFRC522(
    18, # SCLK
    23, # MOSI
    19, # MISO
    21, # RST
    15  # SDA (CS)
)

led = Pin(2, Pin.OUT)

while True:

    led.value(0)  # 搜尋卡片之前先關閉 LED
    stat, tag_type = rfid.request(rfid.REQIDL)  # 搜尋 RFID 卡片

    if stat == rfid.OK:  # 找到卡片
        stat, raw_uid = rfid.anticoll()  # 讀取 RFID 卡號
        if stat == rfid.OK:
            led.value(1)  # 讀到卡號後點亮 LED

            # 將卡號由 2 進位格式轉換為 16 進位的字串
            id = "%02X%02X%02X%02X" % (raw_uid[0], raw_uid[1],
                                       raw_uid[2], raw_uid[3])
            print("偵測到卡號:", id)

            time.sleep(0.5)  # 暫停一下, 避免 LED 太快熄滅看不到
Enter fullscreen mode Exit fullscreen mode

只要是可用來輸出訊號的腳位都可以當成 SPI 通訊的腳位。

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay