ISO/IEC 14443-A MicroPython v1.23 ESP32-S3 Super-Mini & DevKit V1 ST25R3916 I2C 0x50 PN532 (HSU/I2C/SPI) Captive Portal Soft-AP

Bridging Silicon and Air: An Empirical Experiment with RC522, PN532, and ST25R3916 NFC Readers on ESP32 MicroPython

Félix Pupo Pérez Félix Pupo Pérez
October 25, 2026
26 min read
Embedded Systems & Hardware IoT
fpupoperez/esp32_nfc_detector Open Source

Companion open-source repository featuring the non-blocking NFC presence detector in MicroPython. Includes production drivers for RC522 (SPI), PN532 (HSU/I2C/SPI), and ST25R3916 (I2C), on-device diagnostic suites, captive portal provisioning, and authenticated host webhook test tools.

MicroPython ESP32 & ESP32-S3 ISO 14443-A Captive Portal
View on GitHub
Bridging Silicon and Air: ESP32 Multi-Protocol NFC Presence Detector Cover

Interfacing Radio Frequency Identification (RFID) and Near Field Communication (NFC) modules with embedded microcontrollers often looks deceptively simple in tutorial schematics: wire up four SPI pins, copy an Arduino library, wave a card, and watch an LED blink.

However, moving from a toy demo to a robust, headless, multi-protocol NFC presence detector across different physical buses (SPI, I2C, and HSU/UART) and divergent microcontroller layouts (classic ESP32, ESP32-S3 Super-Mini, and Waveshare S3-Zero) reveals a minefield of silicon quirks: 5V level-shifter traps, pin-mapping collisions with internal octal flash, reversed bit orders, and undocumented thermal sensor errata.

In this project, we designed and built a production-grade, non-blocking NFC presence detector in MicroPython. The firmware supports three distinct reader families:

  1. The ubiquitous NXP MFRC522 (over SPI).
  2. The versatile Elechouse PN532 (over HSU/UART, I2C, and SPI).
  3. The industrial M5Stack Unit NFC driven by the ST25R3916 transceiver (over I2C).

Here is the complete engineering breakdown of how the hardware works, the traps encountered along the way, how we unified three wildly divergent silicon architectures under a single non-blocking contract, and what we learned testing them on physical silicon.


01. The Hardware Lineup

To verify true portability, we targeted three distinct ESP32-family development boards alongside three industry-standard 13.56 MHz contactless reader modules.

The Microcontroller Boards

ESP32 DevKit V1
Dual-Core 240 MHz Xtensa LX6

Baseline reference with classic hardware pin multiplexing: GPIO 21/22 for I2C, GPIO 18/23/19/5 for VSPI, and GPIO 2 onboard LED.

ESP32-S3 Super-Mini
Dual-Core Xtensa LX7 + Native USB

Stamp-sized IoT deployment. Pins are scarce and classic pins (21/22/23) are occupied by internal octal SPI flash. Status Neopixel on GPIO 48.

ESP32-S3 Zero
Castellated Waveshare Module

Validates pin portability where the status Neopixel resides on GPIO 21 — precisely the pin classic ESP32s used for I2C SDA!

The Contactless Reader Transceivers

SPI ONLY
NXP MFRC522

Inexpensive, ubiquitous blue board. Operates strictly as an ISO 14443A reader via SPI. Requires register-level management of FIFO buffers, antenna gain, and CRC coprocessors.

HSU / I2C / SPI
Elechouse PN532 V3

Features an onboard 80C51 microcontroller core. Accepts packetized commands (InListPassiveTarget). Bus selection governed via dual DIP switches.

I2C 0x50
ST25R3916 (M5Stack)

Automotive and payment-grade transceiver in a Grove HY2.0-4P casing. High RF output power, automatic antenna tuning, direct command execution engines.

M5Stack Unit NFC module powered by ST25R3916
Figure 1A: The M5Stack Unit NFC (ST25R3916) in its factory HY2.0-4P casing, exposing high-speed I2C communication at address 0x50.
M5Stack Unit NFC interrogating blue 13.56 MHz RFID keyfob
Figure 1B: M5Stack Unit NFC interrogating a passive 13.56 MHz RFID token keyfob directly against its tuned planar antenna.

02. Physical Wiring and Silicon Gotchas

Testing these readers on physical silicon uncovered several practical engineering traps that datasheets and beginner tutorials consistently minimize.

Gotcha 1: The 5V Level-Shifter Trap on the PN532

The Elechouse PN532 breakout board accepts 3.3V to 5V on its VCC pin, and many community guides recommend 5V for improved RF range. However, the board incorporates an onboard N-channel MOSFET level-shifter circuit pulled directly to VCC!

  • The Problem: Feeding 5V into VCC shifts the PN532’s TX and SDA/SCL lines to 5V logic. Connecting this directly to an ESP32 (whose GPIOs are rated for 3.6V maximum) will degrade or permanently destroy the ESP32’s input buffers.
  • The Fix: Always supply the module with 3.3V from the ESP32’s regulated 3V3 rail. At 3.3V, the level shifter operates safely at 3.3V logic levels while still drawing the necessary ~120 mA RF current during active tag polling.
Elechouse PN532 Breakout Board V3
Figure 2A: Elechouse PN532 Breakout Board V3 with onboard antenna and level-shifter MOSFETs.
PN532 DIP Switches for Bus Selection
Figure 2B: Detail of Channel 1 and 2 DIP switches configuring HSU (0,0), I2C (1,0), or SPI (0,1).

Gotcha 2: The ESP32-S3 Internal Octal Flash Pin Collision

On classic ESP32 boards, I2C defaults to SCL=GPIO 22, SDA=GPIO 21. Attempting to instantiate machine.Pin(22) on an ESP32-S3 Super-Mini or Zero immediately raises an unhandled exception:

MicroPython REPL Error
ValueError: invalid pin

On the ESP32-S3 SoC, GPIO 22 through GPIO 25 are physically multiplexed with internal high-speed octal SPI flash/PSRAM. Similarly, classic SPI pins (GPIO 19 and 23) are reserved. For the S3 variants, we migrated all I2C lines to SCL=GPIO 2, SDA=GPIO 1 and SPI to SCK=12, MOSI=11, MISO=13, CS=10, RST=9. Both are general-purpose pins with zero bus conflicts.

3. PN532 DIP Switches and Boot-Time Latching

The PN532 breakout's DIP switches (Channel 1 and Channel 2) configure whether the internal firmware initializes the High-Speed UART (HSU), I2C, or SPI hardware:

Physical Interface DIP Switch 1 DIP Switch 2 Driver Module
HSU (High-Speed UART) 0 (OFF) 0 (OFF) src/pn532/pn532.py
I2C (Address 0x24) 1 (ON) 0 (OFF) src/pn532/pn532_iic.py
SPI (LSB-First) 0 (OFF) 1 (ON) src/pn532/pn532_spi.py

The Trap: The internal 80C51 core inside the PN532 latches the state of its input selection pins only during power-on reset. Toggling switches while the module is powered has zero effect until VCC is physically removed and re-applied!

4. ST25R3916 I2C Register Space Addressing

The ST25R3916’s I2C protocol differs radically from standard byte-addressed EEPROMs or temperature sensors. The chip features two internal register spaces (Space A and Space B) and a direct FIFO buffer:

  • To perform a Register Read in Space A, bit 6 must be asserted: address = 0x40 | (reg & 0x3F).
  • To perform a Register Write in Space A, bit 6 is cleared: address = 0x00 | (reg & 0x3F).
  • Direct Commands: Instructions like Clear FIFO (0xC3) or Transmit WUPA (0xC7) are sent as single-byte control frames with the two most significant bits set to 11b (0xC0 | cmd).
MFRC522 wired to classic ESP32 DevKit V1
Figure 3A: Blue MFRC522 transceiver wired over SPI to the ESP32 DevKit V1 with logic probes verifying clock phase and chip select.
MFRC522 breadboard rig detecting blue RFID keyfob tag
Figure 3B: MFRC522 breadboard setup actively interrogating a blue 13.56 MHz RFID keyfob token across the SPI bus.

03. The Unified Driver Interface & State Machine

Firmware portability usually collapses when high-level business logic (Wi-Fi captive portals, MQTT queues, debounce timers) becomes intertwined with reader-specific register calls.

To solve this, we enforced an architectural contract across all drivers: every driver (mfrc522.py, pn532.py, pn532_iic.py, pn532_spi.py, and st25r3916.py) exposes an identical, non-blocking interface mirroring the classic MFRC522 contract:

Unified Driver Contract Interface
# Driver Contract Constants
OK = 0
NOTAGERR = 1
ERR = 2

# Request modes (ISO14443A Framing)
REQIDL = 0x26  # Request Idle (REQA: probe unhalted cards)
REQALL = 0x52  # Request All  (WUPA: wake all cards including HALT)

class NFCReader:
    def request(self, mode=REQIDL):
        """Non-blocking RF probe: returns (status, back_data_or_atqa)"""
        ...

    def anticoll(self, cascade_level=1):
        """Anticollision resolution: returns (status, uid_bytes)"""
        ...

Why a Non-Blocking State Machine Matters

In MicroPython, blocking calls like time.sleep(0.1) inside a polling loop stall execution entirely. If an HTTP webhook is being dispatched or a captive portal DNS packet arrives while the CPU is busy waiting for an SPI card response, the networking stack drops packets and sockets time out.

In our drivers:

  • reader.request() initiates an RF probe or checks transceiver interrupt flags and immediately yields back to the main loop if no response is detected.
  • reader.anticoll() performs bit-level collision resolution only after request() confirms an ATQA (Answer To Request) is present in the RF field.
  • Debounced Departure: A tag is only deemed "retired" after 3 consecutive missed polls (DEBOUNCE_THRESHOLD = 3), filtering out RF noise or brief physical tag tilts.

The Non-Blocking Visual LED State Machine

Status feedback must never stall the polling loop. We designed a non-blocking state machine driven entirely by time.ticks_ms() that controls either an addressable WS2812 Neopixel or a standard GPIO LED:

Device Operational State Neopixel RGB Pattern Plain LED Pattern Timing Contract
Portal / Wi-Fi Connecting Pulsing Blue 500 ms on / off blink 500 ms toggle cadence
Idle (No tag present) Solid Orange Heartbeat pulse 60 ms pulse every 3,000 ms
Tag Present (Detected) Solid Green Single burst Active while tag remains in RF field
Tag Retired (Departed) Yellow blink 2-second confirmation 500 ms on / off for 2.0 s window

Preemption Contract: If a user removes a tag and instantly taps a new one during the 2-second yellow retire confirmation, the state machine immediately aborts the retire timer and snaps to solid green. Visual feedback reflects reality with zero lag.

Unified Event Schema and Linger Alerts

Regardless of whether transport occurs over MQTT or HTTP webhooks, the device formats an identical JSON envelope:

JSON Event Envelope Schema
{
  "device_id": "esp32-s3-supermini",
  "event": "present",
  "uid": "04 6C 3B 65 D3 2A 81",
  "timestamp": 1718000000.5,
  "message": "Tag present"
}
  • tag/present: Dispatched immediately upon debounced tag insertion.
  • tag/retire: Emitted upon tag removal, including a present_duration_s field recording total dwell time. Webhook dispatch occurs before the 2-second confirmation blink is triggered so network latency never clips visual feedback.
  • tag/alert: Triggered if a card is left resting on the antenna longer than MAX_PRESENT_TIME (default 60 seconds), alerting backend systems to forgotten badges.
  • MQTT LWT (Last Will & Testament): Publishes {"device_id": "...", "status": "offline"} to <base>/reader/status if the socket drops unexpectedly.
White ISO/IEC 14443-A smart card resting on PN532 antenna
Figure 4A: Standard ISO/IEC 14443-A contactless smart card resting on the PN532's integrated PCB antenna coil during dwell timing tests.
13.56 MHz blue RFID keyfob tag positioned on PN532 reader
Figure 4B: Blue 13.56 MHz RFID keyfob tag positioned directly on the PN532 antenna trace for non-blocking anticollision resolution.
Real-time MQTT telemetry stream captured with mosquitto_sub
Figure 5: Live MQTT message stream captured on the host workstation via mosquitto_sub -v -t '#', verifying real-time dispatches of nfc/tag/present, nfc/tag/alert (warning triggered after tag rests on the reader), nfc/tag/retired, and nfc/reader/status (MQTT Last Will & Testament).

04. Deep Dive into the Reader Drivers

1. NXP MFRC522 Driver (mfrc522.py)

The MFRC522 communicates using hardware SPI (Motorola Mode 0: CPOL=0, CPHA=0) with MSB-first transmission. The driver manages the chip's internal FIFO buffer (FIFODataReg) and Command register (CommandReg). Tag discovery uses direct transceive operations:

  • Writes 0x26 (REQA) to the FIFO and sets BitFramingReg to 7 bits (since ISO 14443-A REQA is an incomplete 7-bit transmission).
  • Enables CRC verification via the chip's internal coprocessor for anticollision frames.

2. NXP PN532 Multi-Bus Drivers

Because the PN532 uses higher-level host controller frames, our driver abstracts the command packing into an asynchronous pipeline:

  • HSU (UART): Communicates at 115,200 baud over crossed TX/RX pins. Before sending data, a wake probe preamble (0x55 0x55 0x00 0x00 ...) wakes the PN532 from low-power standby.
  • I2C: The driver talks to 7-bit address 0x24. Crucially, before reading a frame, the driver performs a 1-byte read to check the Ready Bit (LSB == 1). If the chip is still processing, it immediately yields NOTAGERR without blocking.
  • SPI (The LSB-First Inversion): Unlike almost every modern SPI device, the PN532's SPI slave interface shifts data out LSB-first. Because ESP32 hardware SPI peripherals are predominantly configured MSB-first, our pn532_spi.py driver implements a fast 256-entry lookup table to bit-reverse all outgoing command frames and incoming data bytes in real time.

3. STMicroelectronics ST25R3916 Driver (st25r3916.py)

The ST25R3916 driver required solving two unique silicon behaviors:

  • Silicon Errata — Room Temperature Overheat Fix: The ST25R3916 revision 2 silicon contains an errata where internal thermal protection circuitry false-triggers at room temperature upon initial RF field power-up. Following ST's silicon guidelines, the driver sends the diagnostic override sequence 0xFC 0x04 0x10 directly to the chip during initialization.
  • Double-Size (7-byte) UID Cascade Resolution: Unlike simple MIFARE Classic cards with 4-byte UIDs (Cascade Level 1), modern NFC Forum Type 2 tags (such as NTAG213, NTAG215, and NTAG216) use 7-byte UIDs. The driver executes:
    1. Cascade Level 1: Transmits 0x93 0x20 without CRC, receiving CT (Cascade Tag 0x88) plus the first 3 bytes of the UID.
    2. Select CL1: Transmits 0x93 0x70 with CRC enabled to acknowledge the first stage.
    3. Cascade Level 2: Transmits 0x95 0x20 without CRC, receiving the remaining 4 bytes of the UID.
    4. Combines both stages into a clean 7-byte hexadecimal string.
ESP32-S3 Super Mini bench wiring
Figure 6: Stamp-sized ESP32-S3 Super-Mini bench test setup with onboard addressable WS2812 status LED and relocated I2C pins.

05. Code Architecture and Key Blocks

1. The Main Polling and Debounce Loop

Located in src/m5stack/main_esp32_s3_super_mini.py:

Main Non-Blocking Polling Loop
# Non-blocking tag polling loop
(stat, tag_type) = reader.request(reader.REQIDL)

if stat == reader.OK:
    missed_reads = 0
    (stat, uid) = reader.anticoll()
    if stat == reader.OK:
        uid_hex = " ".join("{:02X}".format(b) for b in uid)

        if not tag_present:
            tag_present = True
            current_uid = uid_hex
            tag_inserted_time = time.ticks_ms()
            alert_sent = False
            print("[NFC] TAG INSERTED: " + uid_hex)
            update_status_led("tag_present")
            dispatch_event("tag/present", {"uid": uid_hex, "type": "iso14443a"})
else:
    if tag_present:
        missed_reads += 1
        if missed_reads >= DEBOUNCE_THRESHOLD:
            # 3 consecutive misses confirm tag was physically lifted
            tag_present = False
            duration_s = time.ticks_diff(time.ticks_ms(), tag_inserted_time) // 1000
            print("[NFC] TAG RETIRED: " + current_uid + " after " + str(duration_s) + "s")

            # Webhook dispatch happens BEFORE retire blink so slow HTTP does not delay LED
            dispatch_event("tag/retire", {"uid": current_uid, "present_duration_s": duration_s})
            trigger_retire_blink()
ESP32-S3 MicroPython REPL executing NFC presence detection
Figure 7A: Serial REPL execution on the ESP32-S3 Super-Mini (main_esp32_s3_super_mini.main()), initializing the WS2812 status LED on GPIO 48, establishing Wi-Fi, verifying PN532 firmware revision (32 01 06 07), detecting passive tag 5AA85183, and timing dwell intervals.
Graceful automatic fallback from MQTT to HTTP Webhooks on network drop
Figure 7B: Zero-downtime network fault tolerance: when the MQTT broker drops or becomes unreachable ([Errno 104] ECONNRESET), the firmware automatically falls back to HTTP webhooks without missing tag insertions or crashing the polling loop.
Active white NFC smart card tapped against PN532 reader on ESP32-S3 bench
Figure 8: Live active bench testing with the ESP32-S3 Super-Mini: a white ISO/IEC 14443-A smart card tapped on the PN532 reader confirms instant debounce triggering, solid green WS2812 LED feedback, and non-blocking background telemetry dispatch.

2. Multi-Cascade Anticollision in the ST25R3916 Driver

Located in src/m5stack/st25r3916.py:

ST25R3916 Multi-Cascade Anticollision
def anticoll(self, cascade_level=1):
    # Send ANTICOLLISION command frame without CRC (0xC5 = Transmit without CRC)
    cmd = 0x93 if cascade_level == 1 else 0x95
    resp = self._transceive(bytes([cmd, 0x20]), crc=False)
    if not resp or len(resp) < 5:
        return self.NOTAGERR, None

    # Check XOR checksum of the 4 data bytes against byte 5
    xor_chk = 0
    for b in resp[:4]:
        xor_chk ^= b
    if xor_chk != resp[4]:
        return self.ERR, None

    cl_uid = list(resp[:4])

    # If Cascade Tag (0x88) is present in byte 0, a 7-byte UID is indicated
    if cascade_level == 1 and cl_uid[0] == 0x88:
        # Select Cascade Level 1 with CRC (0xC4 = Transmit with CRC)
        sel_resp = self._transceive(bytes([0x93, 0x70] + cl_uid + [resp[4]]), crc=True)
        if not sel_resp:
            return self.ERR, None

        # Query Cascade Level 2 for the remainder of the UID
        stat_cl2, cl2_uid = self.anticoll(cascade_level=2)
        if stat_cl2 == self.OK:
            # Return complete 7-byte UID (3 bytes from CL1 + 4 bytes from CL2)
            return self.OK, cl_uid[1:4] + cl2_uid

    return self.OK, cl_uid

3. Captive Portal Network Telemetry Dispatch

Located across all variant files:

Telemetry Dispatch with Header Ingestion
def dispatch_event(subtopic, payload):
    """Dispatches event via MQTT if configured, falling back to Webhook HTTP POST."""
    global mqtt_client
    payload["device"] = CONFIG.get("DEVICE_ID")
    payload["timestamp_ms"] = time.ticks_ms()
    data = json.dumps(payload)

    if mqtt_client:
        topic = CONFIG["MQTT_TOPIC"].rstrip("/") + "/" + subtopic
        try:
            mqtt_client.publish(topic, data)
            return True
        except Exception as e:
            print("[MQTT] Publish failed, attempting reconnect:", e)
            mqtt_client = connect_mqtt()

    if CONFIG.get("WEBHOOK_URL"):
        try:
            headers = {"Content-Type": "application/json"}
            # Apply user-defined custom authentication headers (e.g. Bearer tokens)
            for h in CONFIG.get("WEBHOOK_HEADERS", "").split("\n"):
                if ":" in h:
                    k, v = h.split(":", 1)
                    headers[k.strip()] = v.strip()

            urequests.post(CONFIG["WEBHOOK_URL"], data=data, headers=headers)
            return True
        except Exception as ex:
            print("[Webhook] HTTP POST failed:", ex)
    return False

4. First-Time Provisioning: The Captive Portal

Hardcoding Wi-Fi credentials into embedded source code is a notorious security anti-pattern. If no config.json exists on flash storage, or if GPIO 4 is held low to GND during boot, the device launches an open Access Point named ESP32_NFC_SETUP and serves an embedded captive portal on http://192.168.4.1/.

ESP32 NFC Setup Captive Portal Web Interface
Figure 9: Embedded Captive Portal web UI running on the ESP32 Soft-AP (http://192.168.4.1), providing browser-based configuration of Wi-Fi credentials, MQTT brokers, authenticated webhooks, and GPIO pin overrides.

The portal enables browser-based configuration of:

  • Wi-Fi Credentials: SSID and WPA2 passphrase.
  • Device ID: Defaults to esp32- + hardware MAC hex address if left blank.
  • MQTT Settings: Broker IP/host, port, client ID, and topic base (supports {device} macro expansion, e.g., lab/nfc/{device}).
  • Webhook Fallback: Webhook target URL (also supports {device}) and multi-line custom HTTP headers (such as Authorization: Bearer <token>).
  • Hardware Overrides: Dedicated Neopixel GPIO pin assignment and custom network timeouts.

06. Validating Telemetry: Host-Side Webhook Receiver

When testing an embedded device's HTTP webhook pipeline, relying on cloud services (like Webhook.site or AWS API Gateway) introduces latency, internet dependencies, and security concerns when using test credentials. To close the feedback loop cleanly and test entirely offline, the project includes tools/webhook_example.py.

Running the Offline Webhook Receiver
python3 tools/webhook_example.py --token secret123

On boot, the receiver performs a lightweight UDP socket probe (connect(("8.8.8.8", 80))) to interrogate the host OS for its active LAN IP address without transmitting packets, outputting copy-paste-ready values for the setup portal:

Auto-Detected Setup Values
Webhook URL:     http://192.168.1.120:8080/webhook
Webhook headers: Authorization: Bearer secret123

When an event arrives, the server enforces security:

  • Constant-Time Comparison: Compares the incoming header against the expected secret using hmac.compare_digest(), guarding against timing analysis attacks.
  • Helpful Diagnostics: Missing or malformed authentication headers return an immediate HTTP 401 Unauthorized with a diagnostic JSON response and terminal warnings.
  • Live Event Inspection: Validated JSON payloads are decoded and pretty-printed in real time, displaying the detected UID, event classification (tag/present, tag/retire, or tag/alert), and elapsed tag dwell times in seconds.
Zero-dependency host-side webhook server validating incoming telemetry events
Figure 10: Host-side test server (tools/webhook_example.py) receiving incoming HTTP POST payloads from the ESP32 (192.168.0.71), verifying the Authorization: Bearer secret123 security header with constant-time HMAC, and pretty-printing real-time present, alert, and retired telemetry payloads.

07. Testing and Diagnostic Methodology: Isolating Faults in Minutes

Embedded debugging often suffers when entire application monoliths are flashed at once: if an LED doesn't light up, is it bad Wi-Fi, a broken SPI bus, a fried chip, or an invalid pin assignment?

To eliminate guesswork, we developed an on-device diagnostic suite. These scripts run instead of main.py, bypass Wi-Fi and network stacks, and print diagnostic reports to the serial console at 115,200 baud:

Diagnostic Script Target Hardware Purpose & Diagnostic Test
loopback_test.py ESP32 Header Tests microcontroller UART pads using a single jumper wire between TX and RX. Validates hardware pads before connecting any reader.
pn532_test.py PN532 HSU Employs an ADC bias scan to measure floating vs pulled lines. Identifies the PN532 TXD line without knowing pinouts, sends wake probes, and polls tags with 3-second heartbeats.
iic_test.py PN532 I2C Validates line pull-up voltages with ADC, probes address 0x24 in forward and reversed orientations, and prints the exact Python I2C(...) line to use.
test_pins_auto.py PN532 Auto Probes both I2C and UART buses, detects which interface DIP switches have activated, and streams UIDs immediately.
m5stack_nfc_test.py ST25R3916 I2C Sweeps I2C for address 0x50, reads register 0x3F to verify ST25R3916 silicon rev 2 (0x2A), powers the RF field, and streams card reads to console.
main_esp32_s3_super_mini_test.py ESP32-S3 Reader Minimalist reader firmware: executes hardware handshake, reports PASS/FAIL via Neopixel (Green/Red), and pulses blue on tag read.

Operational Gotcha: ampy Heartbeats and Absolute Paths

When running diagnostics via the Adafruit MicroPython Tool (ampy):

  1. Absolute Path Requirement: ampy run resolves file paths directly. Always use absolute paths or shell expansion:
    ampy -p /dev/tty.usbmodem1401 -b 115200 run "$PWD/src/pn532/pn532_test.py"
    Passing relative paths causes Failed to find or read input file.
  2. Preventing Timeouts: If a script stays silent during long polling loops, ampy drops the connection with timeout waiting for first EOF reception. All our diagnostic scripts emit a heartbeat tick every 3 seconds to keep serial streaming alive.
Bench test rig with PN532 and ESP32
Figure 11: Live hardware test bench isolating UART logic levels and validating non-blocking state machine preemption.

08. Step-by-Step Deployment Guide

Deploying the detector to a fresh ESP32 takes less than five minutes:

1. File Selection by Reader Family

Reader & Interface Hardware Driver File Firmware File (Copy as main.py)
RC522 (SPI) src/rc522/mfrc522.py src/rc522/main*.py
PN532 (HSU/UART) src/pn532/pn532.py src/pn532/main*.py
PN532 (I2C) src/pn532/pn532_iic.py src/pn532/main_iic*.py
PN532 (SPI) src/pn532/pn532_spi.py src/pn532/main_spi*.py
M5Stack Unit NFC (I2C) src/m5stack/st25r3916.py src/m5stack/main*.py

2. Copy Files to Device Flash

Using ampy over your serial port:

Uploading Firmware via ampy
# 1. Upload dependencies
ampy -p /dev/tty.usbmodem1401 -b 115200 put urequests.py
ampy -p /dev/tty.usbmodem1401 -b 115200 put umqtt/simple.py

# 2. Upload reader driver (e.g. ST25R3916 for M5Stack Unit NFC)
ampy -p /dev/tty.usbmodem1401 -b 115200 put src/m5stack/st25r3916.py

# 3. Upload target board variant as main.py
ampy -p /dev/tty.usbmodem1401 -b 115200 put src/m5stack/main_esp32_s3_super_mini.py :main.py

3. Provisioning and Verification

  1. Reboot the board. Connect your smartphone or laptop to the open Wi-Fi network ESP32_NFC_SETUP.
  2. Enter your Wi-Fi credentials and point the webhook URL to your host machine running webhook_example.py.
  3. Tap an NFC tag. Watch the LED flash green while the host webhook terminal instantly prints the decoded UID and timestamp!

09. Hardware, Tools, and Library References

Hardware Components

Software Tools & MicroPython Libraries

  • MicroPython: Lean, efficient re-implementation of Python 3 designed to run bare-metal on microcontrollers. Refer to the MicroPython Official Documentation.
  • ampy (Adafruit MicroPython Tool): Host-side CLI utility for manipulating files and executing scripts across a serial REPL. Refer to the adafruit-ampy GitHub Repository.
  • machine Module: Standard MicroPython hardware peripheral interface providing classes for Pin, I2C, SPI, UART, and PWM. Refer to the MicroPython Machine Module Reference.
  • neopixel Module: MicroPython built-in driver for controlling single-wire WS2812 / SK6812 RGB LED strings with precise hardware timing. Refer to the MicroPython NeoPixel Driver Documentation.
  • urequests: Lightweight, memory-efficient subset of Python’s requests library implemented for MicroPython socket connections. Refer to micropython-lib urequests.
  • umqtt.simple: Minimalist MQTT client implementation for MicroPython from the official micropython-lib repository. Refer to micropython-lib umqtt.simple.

Open-Source Code & Firmware Drivers

All MicroPython drivers, board variants (DevKit V1, Super-Mini, S3-Zero), on-device diagnostic tools, and the host webhook test harness are published under the open-source MIT License on GitHub:


Félix Pupo Pérez

Félix Pupo Pérez

Senior Embedded Systems & AI Architect

Over 20 years of experience building bare-metal firmware, industrial IoT telemetries, and distributed systems. Passionate about bridging physical silicon constraints to resilient enterprise cloud architectures.