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

使用PN532与Arduino设置NTAG215密码后,如何授权写入或修改密码?

解决NTAG215密码保护后的授权与访问问题

NTAG215启用密码保护后,所有涉及受保护区域的读写操作都必须先完成**密码授权(PWD_AUTH)**流程。你当前的代码仅完成了密码写入,缺少授权逻辑,以下是具体解决方法:

关键授权步骤

Adafruit_PN532库提供了ntag2xx_PasswordAuth()方法来完成授权,流程如下:

  • 检测到标签后,调用该方法传入密码和PACK值(你代码中定义的pack[2] = {0xDE, 0xAD})
  • 授权成功后,标签会返回PACK值,库会自动验证匹配性,返回true则授权生效,此时即可执行读写操作

修改后的完整代码

#include <Wire.h>
#include <Adafruit_PN532.h>

#define SDA_PIN 21
#define SCL_PIN 22

Adafruit_PN532 nfc(SDA_PIN, SCL_PIN);

uint8_t password[4] = {0x11, 0x22, 0x33, 0x44};
uint8_t pack[2] = {0xDE, 0xAD};
uint8_t protect_start_page = 4;

void setup() {
    Serial.begin(115200);
    Serial.println("Initializing NFC module...");

    nfc.begin();
    uint32_t versiondata = nfc.getFirmwareVersion();
    if (!versiondata) {
        Serial.println("Didn't find PN53x board");
        while (1);
    }

    Serial.println("Found PN532!");
    nfc.SAMConfig();
}

void loop() {
    Serial.println("Place your NTAG215 tag on the reader...");

    uint8_t success;
    uint8_t uid[7];
    uint8_t uidLength;
    
    success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    if (success) {
        Serial.println("Tag detected!");

        // 执行密码授权
        Serial.println("Authenticating with password...");
        success = nfc.ntag2xx_PasswordAuth(password, pack);
        if (!success) {
            Serial.println("ERROR: Authentication failed!");
            delay(3000);
            return;
        }
        Serial.println("Authentication successful!");

        // 示例1:写入普通数据页(如第4页,假设该页受保护)
        uint8_t test_data[4] = {0x01, 0x02, 0x03, 0x04};
        Serial.println("Writing test data to page 4...");
        if (!nfc.ntag2xx_WritePage(4, test_data)) {
            Serial.println("ERROR: Could not write data!");
        } else {
            Serial.println("Data written successfully.");
        }

        // 示例2:修改密码(写入第130页)
        uint8_t new_password[4] = {0xAA, 0xBB, 0xCC, 0xDD};
        Serial.println("Updating password...");
        if (!nfc.ntag2xx_WritePage(130, new_password)) {
            Serial.println("ERROR: Could not update password!");
        } else {
            Serial.println("Password updated successfully.");
            // 注意:修改密码后,后续授权需要使用新密码
            memcpy(password, new_password, sizeof(password));
        }
    }
    else {
        Serial.println("No tag detected.");
    }
    
    delay(3000);
}

注意事项

  • 授权成功后,标签的授权状态会保持到标签离开读写场或执行REQA命令为止,无需每次操作都重新授权
  • 如果你的PACK值与标签中存储的不匹配,授权会失败,需确保代码中的pack数组与写入标签131页的内容一致
  • 修改密码后,记得更新代码中的password变量,否则下次授权会失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:25:10