Search code examples
c++nfcmifareacr122lib-nfc

libnfc: Write and read back custom data from NTAG


I have been trying for a long while now to write and read data from my NFC cards. The cards are NTAG216. I can use libnfc examples to read manufacturer ID and it works fine. But I need to write to each tag some custom data, e.g. the string "abcdefg" and read it back.

I have read almost everything relevant I could find about libnfc but all of them does not talk about this specific area. I would appreciate any guidance. Code example will be appreciated.

I use an ACRU122 NFC reader/writer with libnfc 1.7.1 from Github.


Solution

  • Once you enumerated and activated the tag, you can use the method nfc_initiator_transceive_bytes() to send raw NTAG commands (such as READ/WRITE) to the tag. Since the command set of NTAG216 is compatible to the MIFARE Ultralight command set (including the COMPATIBILITY WRITE command), you could also use the convenience methods for MIFARE tags defined in utils/mifare.h:

    • nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp)
    • nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)

    See the nfc-mfultralight utility for complete code examples: nfc-mfultralight.c.

    However, you might want to adapt that code to use the more efficient MIFARE Ultralight/NTAG WRITE (0xA2) command instead of the COMPATIBILITY WRITE (which is what MC_WRITE uses).