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
uidlist passed touid_to_numonly has 7 elements (valid indices 0 to 6). - But your loop runs
range(0,8), which tries to access indices 0 through 7. Wheni=7, you’re trying to getuid[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
相关产品推荐
相关产品推荐

