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

Arduino中RFID522读取卡号显示十进制转十六进制方法问询

Fixing RFID MFRC522 Decimal ID to Hexadecimal Conversion

Hey there! Let's sort out that RFID card ID display problem. The issue with your current code is straightforward: you're directly concatenating the decimal values of each byte in rfid.serNum into a string. For example, if a byte in the serial number is 0x85 (which is 133 in decimal), your code adds "133" to the string instead of the hexadecimal "85". Stacking five of these decimal strings gives you that long, unreadable decimal number instead of the standard hex RFID ID.

Here's the modified code to get hexadecimal output:

if (rfid.isCard()) { 
  if (rfid.readCardSerial()) { 
    String id = "";
    // Iterate over each byte in the card's serial number
    for (int i = 0; i < 5; i++) {
      // Add a leading zero for values less than 0x10 to keep two-digit format
      if (rfid.serNum[i] < 0x10) {
        id += "0";
      }
      // Convert the byte to a hexadecimal string and append it
      id += String(rfid.serNum[i], HEX);
      // Optional: add a space between bytes for better readability
      // id += " ";
    }
    // Convert to uppercase (optional, since HEX returns lowercase by default)
    id.toUpperCase();
    Serial.println(id);
  }
}

How this works:

  • We loop through each of the 5 bytes in rfid.serNum (MFRC522 typically reads 5-byte UIDs for MIFARE cards).
  • The String(value, HEX) function converts the byte's value directly to its hexadecimal string equivalent.
  • We check if the byte is less than 0x10 (16 in decimal) to add a leading zero—this ensures single-digit hex values (like 0x0F) show up as "0F" instead of "F", keeping the ID in the standard two-digit-per-byte format.
  • The optional toUpperCase() call standardizes the output to uppercase hex characters, which is the common format for RFID IDs.

Quick example:

If your card's serial number bytes are 0x85, 0x0F, 0x34, 0xAB, 0x12, your original code would output "133155217118", while the modified code outputs "850F34AB12" (or "85 0F 34 AB 12" if you enable the space).

内容的提问来源于stack exchange,提问作者Salman Mahmood

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:57