Search code examples
arduinonfcndefarduino-c++nfc-p2p

Extract payload from NDEF message


I am using Arduino UNO and a PN532 NFC module to receive P2P NDEF messages from an Android phone.

I am sending a plaintext string "Hello". When the transfer is successful, I get this on my Arduino: image

How can I extract the string "Hello" (I think the pairs of numbers before it is the "Hello" in hexadecimal, same for the "text/plain" type indication, type length and payload length) from the NDEF message payload into a regular variable?

Here is my Arduino code:

// Receive a NDEF message from a Peer
// Requires SPI. Tested with Seeed Studio NFC Shield v2

#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"

PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];

void setup() {
  Serial.begin(9600);
  Serial.println("NFC Peer to Peer Example - Receive Message");
}

void loop() {
  Serial.println("Waiting for message from Peer");
  //string payload = nfc.read();
  int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf));
      NdefMessage msg  = NdefMessage(ndefBuf, msgSize);
      msg.print();
}

Solution

  • A NdefMessage is made up of multiple NdefRecord items and you msg has 1 record

    so this should do it (not tested)

    // Get the first record
    NdefRecord record = msg.getRecord(0);
    // Get the payload size
    byte length = record.getPayloadLength();
    // Create byte array big enough for payload
    byte payload[length];
    // Get payload to byte array
    record.getPayload(payload);
    // Convert byte Array to string
    String string = String((char *)payload);