You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NTAG213与MFRC522开发遇IndexError:列表越界问题求助

Fixing IndexError in uid_to_num for NTAG213 RFID Reading

Let's break down why you're hitting that IndexError: List Out of Range issue and how to fix it quickly.

The Root Cause

Your code has a clear mismatch between the loop iteration count and the actual length of the NTAG213 UID:

  • NTAG213 uses a 7-byte UID, so the uid list passed to uid_to_num only has 7 elements (valid indices 0 to 6).
  • But your loop runs range(0,8), which tries to access indices 0 through 7. When i=7, you’re trying to get uid[7]—a position that doesn’t exist, hence the error.

The Fix

You have two solid options to resolve this:

Option 1: Dynamic iteration (recommended)

This approach adapts to any RFID tag UID length, not just NTAG213:

def uid_to_num(self, uid):
    n = 0
    # Iterate over every byte in the UID list
    for i in range(len(uid)):
        n = n*256 + uid[i]
    return n

Option 2: Hardcode for NTAG213 specifically

If you only work with NTAG213 tags, you can explicitly set the loop to run 7 times:

def uid_to_num(self, uid):
    n = 0
    # NTAG213 has 7 UID bytes, so iterate from 0 to 6
    for i in range(0, 7):
        n = n*256 + uid[i]
    return n

Quick Debug Check

To confirm the UID length yourself, add a quick print statement at the start of the function:

def uid_to_num(self, uid):
    print(f"Actual UID length: {len(uid)}") # This will show you it's 7, not 8
    n = 0
    for i in range(len(uid)):
        n = n*256 + uid[i]
    return n

内容的提问来源于stack exchange,提问作者Farisa Pratiwi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:03:41