PN532: SPI card emulation is not working

I have the elechouse v3 module (or probably a clone, since I don’t know anymore when I purchased it and can’t find out if it is a clone or not).

After setting up everything like in the example for the emulate_tag_ndef.h, I have this loop:

// the loop function runs over and over again until power down or reset
void loop()
{
  Serial.println("Begin emulation.");
  if (!nfc.emulate(10000))timeout 10 seconds
    Serial.println("timed out");
  else
    Serial.println("mobile device found!");

  if (nfc.writeOccured()) {
    Serial.println("\nWrite occured !");
    uint8_t *tag_buf;
    uint16_t length;

    nfc.getContent(&tag_buf, &length);
    NdefMessage msg = NdefMessage(tag_buf, length);
    msg.print();
  }
  delay(1000);
}

It should emulate an NFC tag with the seeeds studio tag. Unfortunately, it doesn’t send the url and gives the wrong data to the phone. image

Enabling the debug on the library, this is what I get once the phone will answer:

Begin emulation. write: 8C 05 04 00 12 34 56 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 read: 8D 08 E0 80 write: 86 read: 87 13 status is not ok tgGetData failed! write: 52 00 read: 53 00 mobile device found!

Shouldn’t it be able to emulate a mifare? I just don’t know if it is something with the library or if it is something with the module.


Edit:

  • 8C is the command for tgInitAsTarget
  • 05 means PICC only (0x04) + Passive only (0x01)
  • 04 00 is SENS_RES (why is it not 08 00 like on the pn532 examples of NXP?)
  • 12 34 56 is the Uid
  • 20 is SEL_RES (Mifare DESFire)
  • The others are NFCId1/2/3t

The answer seems to be ok for this command. But for the 0x86 command (GetData()) I get always the error “The data format does not match to the specification.”. I don’t know what it can be or how to debug it… Seems to be more a phone error…

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (2 by maintainers)

Most upvoted comments

Hi guys @Dermiste @Adrianotiger. I managed to parse horrendous fix together, based on Adrianos explanation (forgive me, I have 10h Arduino experience).

emulatetag.cpp, emulate function (whole function, but only changes in the command array and in the runloop retry stuff)

bool EmulateTag::emulate(const uint16_t tgInitAsTargetTimeout)
{

    //https://github.com/Seeed-Studio/PN532/issues/88
    uint8_t command[] = {
      PN532_COMMAND_TGINITASTARGET,
      0x05,                  // MODE: 0x04 = PICC only, 0x01 = Passive only (0x02 = DEP only)

      // MIFARE PARAMS
      0x04, 0x00,         // SENS_RES (seeeds studio set it to 0x04, nxp to 0x08)
      0x00, 0x00, 0x00,   // NFCID1t	(is set over sketch with setUID())
      0x20,               // SEL_RES    (0x20=Mifare DelFire, 0x60=custom)

      // FELICA PARAMS
      0x01, 0xFE,         // NFCID2t (8 bytes) https://github.com/adafruit/Adafruit-PN532/blob/master/Adafruit_PN532.cpp FeliCa NEEDS TO BEGIN WITH 0x01 0xFE!
      0x05, 0x01, 0x86,
      0x04, 0x02, 0x02,
      0x03, 0x00,         // PAD (8 bytes)
      0x4B, 0x02, 0x4F, 
      0x49, 0x8A, 0x00,   
      0xFF, 0xFF,         // System code (2 bytes)
      
      0x01, 0x01, 0x66,   // NFCID3t (10 bytes)
      0x6D, 0x01, 0x01, 0x10,
      0x02, 0x00, 0x00,

	  0x00, // length of general bytes
      0x00  // length of historical bytes
  };
  if (uidPtr != 0)
  { // if uid is set copy 3 bytes to nfcid1
    memcpy(command + 4, uidPtr, 3);
  }

  if (1 != pn532.tgInitAsTarget(command, sizeof(command), tgInitAsTargetTimeout))
  {
    DMSG("tgInitAsTarget failed or timed out!");
    return false;
  }

  uint8_t compatibility_container[] = {
      0, 0x0F,
      0x20,
      0, 0x54,
      0, 0xFF,
      0x04,                                                        // T
      0x06,                                                        // L
      0xE1, 0x04,                                                  // File identifier
      ((NDEF_MAX_LENGTH & 0xFF00) >> 8), (NDEF_MAX_LENGTH & 0xFF), // maximum NDEF file size
      0x00,                                                        // read access 0x0 = granted
      0x00                                                         // write access 0x0 = granted | 0xFF = deny
  };

  if (tagWriteable == false)
  {
    compatibility_container[14] = 0xFF;
  }

  tagWrittenByInitiator = false;

  uint8_t rwbuf[128];
  uint8_t sendlen;
  int16_t status;
  tag_file currentFile = NONE;
  uint16_t cc_size = sizeof(compatibility_container);
  bool runLoop = true;
  bool firstTry = true;
  uint8_t retries = 0;
  uint8_t maxRetries = 3;
  while (runLoop)
  {
    //retry code begins...
    if(retries < maxRetries) {
      retries++;
      status = pn532.tgGetData(rwbuf, sizeof(rwbuf));

      if(status == -6) {
        DMSG("found 0x29, try init again");
        if (1 != pn532.tgInitAsTarget(command, sizeof(command), tgInitAsTargetTimeout))
        {
            DMSG("reset again failed!");
            pn532.inRelease();
            return true;
        }
        DMSG("inited again succesfully");
        retries = maxRetries; // then continue normally by maxing out retries
        continue; 
      }
      if(status < 0) { // some other kind of fail... still retrying
          DMSG("Some other fail, still retrying...");
          continue;
      }
    } else {
        status = pn532.tgGetData(rwbuf, sizeof(rwbuf));
    }

    if (status < 0)
    {
      DMSG("tgGetData failed!\n");
      pn532.inRelease();
      return true;
    }

    uint8_t p1 = rwbuf[C_APDU_P1];
    uint8_t p2 = rwbuf[C_APDU_P2];
    uint8_t lc = rwbuf[C_APDU_LC];
    uint16_t p1p2_length = ((int16_t)p1 << 8) + p2;

    switch (rwbuf[C_APDU_INS])
    {
    case ISO7816_SELECT_FILE:
      switch (p1)
      {
      case C_APDU_P1_SELECT_BY_ID:
        if (p2 != 0x0c)
        {
          DMSG("C_APDU_P2 != 0x0c\n");
          setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
        }
        else if (lc == 2 && rwbuf[C_APDU_DATA] == 0xE1 && (rwbuf[C_APDU_DATA + 1] == 0x03 || rwbuf[C_APDU_DATA + 1] == 0x04))
        {
          setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
          if (rwbuf[C_APDU_DATA + 1] == 0x03)
          {
            currentFile = CC;
          }
          else if (rwbuf[C_APDU_DATA + 1] == 0x04)
          {
            currentFile = NDEF;
          }
        }
        else
        {
          setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
        }
        break;
      case C_APDU_P1_SELECT_BY_NAME:
        const uint8_t ndef_tag_application_name_v2[] = {0, 0x7, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01};
        if (0 == memcmp(ndef_tag_application_name_v2, rwbuf + C_APDU_P2, sizeof(ndef_tag_application_name_v2)))
        {
          setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
        }
        else
        {
          DMSG("function not supported\n");
          setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
        }
        break;
      }
      break;
    case ISO7816_READ_BINARY:
      switch (currentFile)
      {
      case NONE:
        setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
        break;
      case CC:
        if (p1p2_length > NDEF_MAX_LENGTH)
        {
          setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
        }
        else
        {
          memcpy(rwbuf, compatibility_container + p1p2_length, lc);
          setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
        }
        break;
      case NDEF:
        if (p1p2_length > NDEF_MAX_LENGTH)
        {
          setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
        }
        else
        {
          memcpy(rwbuf, ndef_file + p1p2_length, lc);
          setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
        }
        break;
      }
      break;
    case ISO7816_UPDATE_BINARY:
      if (!tagWriteable)
      {
        setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
      }
      else
      {
        if (p1p2_length > NDEF_MAX_LENGTH)
        {
          setResponse(MEMORY_FAILURE, rwbuf, &sendlen);
        }
        else
        {
          memcpy(ndef_file + p1p2_length, rwbuf + C_APDU_DATA, lc);
          setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
          tagWrittenByInitiator = true;

          uint16_t ndef_length = (ndef_file[0] << 8) + ndef_file[1];
          if ((ndef_length > 0) && (updateNdefCallback != 0))
          {
            updateNdefCallback(ndef_file + 2, ndef_length);
          }
        }
      }
      break;
    default:
      DMSG("Command not supported!");
      DMSG_HEX(rwbuf[C_APDU_INS]);
      DMSG("\n");
      setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
    }
    status = pn532.tgSetData(rwbuf, sendlen);
    if (status < 0)
    {
      DMSG("tgSetData failed\n!");
      pn532.inRelease();
      return true;
    }
  }
  pn532.inRelease();
  return true;
}

PN532.cpp, tgGetData function

int16_t PN532::tgGetData(uint8_t *buf, uint8_t len)
{
    buf[0] = PN532_COMMAND_TGGETDATA;

    if (HAL(writeCommand)(buf, 1)) {
        return -1;
    }

    int16_t status = HAL(readResponse)(buf, len, 3000);
    if (0 >= status) {
        return status;
    }


    uint16_t length = status - 1;

    if(buf[0] == 0x29) {
        DMSG("status 0x29, init again...");
        return -6;
    }
    

    if (buf[0] != 0) {
        DMSG("status is not ok\n");
        return -5;
    }

    for (uint8_t i = 0; i < length; i++) {
        buf[i] = buf[i + 1];
    }

    return length;
}


Some other sidenotes:

It still take a few attempts to get it to recognize the tag. Need to have the phone in the right angle, very close etc… at least for my chip.

I have Arduino MKR 1010 WiFi, and at first I got errors because of _spi->setDataMode so this is my PN532_SPI.cpp begin function (use new beginTransaction method)

void PN532_SPI::begin()
{
    pinMode(_ss, OUTPUT);



    _spi->begin();
    _spi->beginTransaction(SPISettings(SPI_CLOCK_DIV8, LSBFIRST, SPI_MODE0));
    // _spi->setDataMode(SPI_MODE0);  // PN532 only supports mode0
    // _spi->setBitOrder(LSBFIRST);
#ifndef __SAM3X8E__
    // _spi->setClockDivider(SPI_CLOCK_DIV8); // set clock 2MHz(max: 5MHz)
#else
    /** DUE spi library does not support SPI_CLOCK_DIV8 macro */
    // _spi->setClockDivider(42);             // set clock 2MHz(max: 5MHz)
#endif

}

Arduino <-> Chip

RESET <-> RSTO MOSI 8 <-> MOSI SCK 9 <-> SCK MISO 10 <-> MISO SDA 11 <-> SS GND <-> GND 5V <-> VCC

use PIN 11 as the SS pin:

so in the example, swap the argument SS -> PN532_SPI pn532spi(SPI, 11);

#include "emulatetag.h"
#include "NdefMessage.h"

#if 1
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  PN532_SPI pn532spi(SPI, 11);
  EmulateTag nfc(pn532spi);
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>
      
  PN532_HSU pn532hsu(Serial1);
  EmulateTag nfc(pn532hsu);
#endif

After a lot of googling and changes in the library, I found some errors and found some info about it. As said from a lot of users, the NXP documentation isn’t really good and so a lot of info are missing. But the library structure is good and works. Just some info about it:

Starting with this tgInitAsTarget:

  uint8_t command[] = {
      PN532_COMMAND_TGINITASTARGET,
      5, // MODE: PICC only, Passive only

      0x04, 0x00,       // SENS_RES
      0x00, 0x00, 0x00, // NFCID1
      0x20,             // SEL_RES

      0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, // FeliCaParams
      0, 0,

      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NFCID3t

      0, // length of general bytes
      0  // length of historical bytes
  };

On the last commit you changed it and now it is wrong. The PN532 is emulating a FeliCa card and you have to set it up correctly. So, you have to write it in this way:

  uint8_t command[] = {
      PN532_COMMAND_TGINITASTARGET,
      0x05,                  // MODE: 0x04 = PICC only, 0x01 = Passive only (0x02 = DEP only)

      // MIFARE PARAMS
      0x04, 0x00,         // SENS_RES (seeeds studio set it to 0x04, nxp to 0x08)
      0x00, 0x00, 0x00,   // NFCID1t	(is set over sketch with setUID())
      0x20,               // SEL_RES    (0x20=Mifare DelFire, 0x60=custom)

      // FELICA PARAMS
      0x01, 0xFE,         // NFCID2t (8 bytes) https://github.com/adafruit/Adafruit-PN532/blob/master/Adafruit_PN532.cpp FeliCa NEEDS TO BEGIN WITH 0x01 0xFE!
      0x05, 0x01, 0x86,
      0x04, 0x02, 0x02,
      0x03, 0x00,         // PAD (8 bytes)
      0x4B, 0x02, 0x4F, 
      0x49, 0x8A, 0x00,   
      0xFF, 0xFF,         // System code (2 bytes)
      
      0x01, 0x01, 0x66,   // NFCID3t (10 bytes)
      0x6D, 0x01, 0x01, 0x10,
      0x02, 0x00, 0x00,

	  0x00, // length of general bytes
      0x00  // length of historical bytes
  };

Some more info on https://www.nxp.com/docs/en/nxp/application-notes/AN133910.pdf page 51 (how to fill TgInitAsTarget parameters?). I am not sure about it, but after setting it correctly, my phone begun to read the NDEF Tags.

This is not all. An important point is the first tgGetData call. You probably get this one:

write: 86 read: 87 13

if you have a cloned shield or if the NFC-shield is not correctly positioned on your smartphone… Just continue to reading or polling will help you to get a right answer.

Once you get another answer, this one could be:

write: 86 read: 87 29

This is a good answer! The smartphone replied with “target has been released by its initiator”. It means that the message was arrived to destination and the smartphone want to read more (https://stackoverflow.com/questions/24777810/the-pn532-configured-as-target-has-been-released-by-its-initiator). So, if you get this 0x29 answer, just init the PN532 again and the smartphone will read the Tag correctly. You have to modify the pn532.cpp - tgGetData() to parse the 0x29 command and you have to modify the emulatetag.cpp - emulate() to call if (pn532.tgInitAsTarget(command, sizeof(command), 1000) == 1) continue; if the result of the status was 0x29 and it is the first command read inside the loop.

I am still playing with this module, so maybe this is not the best solution. But it works now! If you want I can create a fork and commit my changes… But as said, it is probably not the perfect solution… Just a working solution.

Edit: All messages between phone and PN532 are APDU messages, from the ISO7816. If you want parse the messages, you can begin with this wiki: https://en.wikipedia.org/wiki/Smart_card_application_protocol_data_unit

Hi @Adrianotiger, I guess it’s my turn to step on this issue and try to make things work. It’s been a while but do you possibly have code pieces to share regarding this?

Hi @Adrianotiger, i know has been a long time but i have the same issue: i got the same screenshot with NFC Tools when with the first try of card emulation with PN532. Then i change the settings of “tgInitAsTarget” as you suggested but still i’m not capable of a 100% reading. Do you change anything else? Thanks in advance.

I can’t remember 😛 I think, I begun to make multiple reads. So if I got an incorrect answer, I just made the request again. The module works also better with a high voltage. They write from 2.7 to 5.5V. With 4.5V my module begun to give strange answers… I think you should try a good power supply with 1A and 5V. To have a stable module.