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

如何使用RC522模块在NTAG Ultralight标签中读写int值

解决RC522写入NTAG Ultralight存储int类型数值的问题

核心原理

NTAG Ultralight的存储是以**页(4字节/页)**为单位的,而int类型(比如常用的32位int是4字节)本质是一组连续的字节数据。解决问题的关键是把int值转换成符合标签存储顺序(大端/小端)的字节数组,再按页写入标签的用户存储区域。

具体实现步骤

1. 确定int的字节长度与存储顺序

  • 多数平台的int为32位(4字节),若为16位int则是2字节,先明确自身需求。
  • NTAG Ultralight通常默认使用大端字节序(高位字节存在低地址页的低字节位置),也可根据读取需求调整为小端,以下以32位int为例说明。

2. 将int转换为字节数组

以Arduino环境为例(RC522的常用开发环境),编写转换函数:

// 将32位int转换为大端字节数组
void intToBigEndianBytes(int value, byte bytes[4]) {
  bytes[0] = (value >> 24) & 0xFF; // 最高位字节
  bytes[1] = (value >> 16) & 0xFF;
  bytes[2] = (value >> 8) & 0xFF;
  bytes[3] = value & 0xFF;         // 最低位字节
}

// 如果需要小端序,使用此函数
void intToLittleEndianBytes(int value, byte bytes[4]) {
  bytes[0] = value & 0xFF;         // 最低位字节
  bytes[1] = (value >> 8) & 0xFF;
  bytes[2] = (value >> 16) & 0xFF;
  bytes[3] = (value >> 24) & 0xFF; // 最高位字节
}

3. 调用RC522写入接口写入字节数组

假设你已有基于MFRC522库的字符串写入代码,该库的Write函数按页写入4字节数据。注意:NTAG Ultralight前3页是系统页,禁止写入,从第4页开始为用户存储区:

MFRC522 mfrc522(SS_PIN, RST_PIN); // 初始化RC522模块
int myIntValue = 123456; // 待写入的int数值
byte intBytes[4];

intToBigEndianBytes(myIntValue, intBytes); // 转换为字节数组

// 写入第4页(页地址为4)
if (mfrc522.MIFARE_Write(4, intBytes, 4)) {
  Serial.println("Int值写入成功");
} else {
  Serial.println("写入失败");
}

4. 读取验证(可选)

写入后可读取对应页的字节,再转回int值验证:

byte readBytes[4];
if (mfrc522.MIFARE_Read(4, readBytes, &mfrc522.uid)) {
  int readInt = (readBytes[0] << 24) | (readBytes[1] << 16) | (readBytes[2] << 8) | readBytes[3];
  Serial.print("读取到的int值:");
  Serial.println(readInt);
}

注意事项

  • NTAG Ultralight的用户存储区页数有限(比如NTAG213共45页,180字节),需规划好存储位置,避免覆盖系统页。
  • 若写入16位int(2字节),需填充0至剩余2字节,因为页写入必须是4字节整页操作。
  • 写入前需确保RC522已检测并选中标签(通过mfrc522.PICC_IsNewCardPresent()和mfrc522.PICC_ReadCardSerial()实现)。

内容的提问来源于stack exchange,提问作者prabhakar panchal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:30:08