How to Read Write or Emulate NFC tags with Arduino and PN532

Introduction

Welcome to the world of Near Field Communication (NFC) with Arduino! In this guide, we’ll explore How to Read Write or Emulate NFC tags with Arduino and PN532 NFC RFID module. The PN532 module allows Arduino projects to communicate with NFC tags, enabling functionalities such as reading, writing, and emulating NFC tags. Let’s delve into the details of the PN532 NFC RFID module and learn how to integrate it with Arduino for NFC tag interactions.

Hardware Required

You will require the following Hardware Components for, How to Interfacing PN532 NFC RFID Module with Arduino.

Components#Buy From Amazon
Arduino UNO1Buy Link
PN532 NFC RFID Module1Buy Link
9v DC Adapter (Optional)1Buy Link
Jumper Wires6Buy Link
Breadboard1Buy Link

What is the PN532 NFC RFID Module?

The PN532 NFC RFID module is a versatile communication module manufactured by NXP Semiconductors. It enables Arduino and other microcontroller platforms to interact with NFC tags and devices through NFC technology. The PN532 module supports various NFC modes, including reader/writer mode, peer-to-peer mode, and card emulation mode, allowing Arduino projects to perform a wide range of NFC-related tasks.

Pinout of PN532 Module

I2C Protocol

PN532-NFC-(I2C-Protocol)-Module-Pinout

Pin Configuration

Pin NumberPin NameDescription
1VCCModule power supply – 5V
2GNDGround
3SDAData pin
4SCLClock pin

SPI Protocol:

PN532-NFC-(SPI-Protocol)-Module-Pinout

Pin Configuration

Pin NumberPin NameDescription
1VCCModule power supply – 3-5V
2GNDGround
3SCKClock pin
4MISOOutput data pin
5MOSIInput data pin
6SSSlave select
7IRQInterrupt pin
8RSTOReset pin

HSU Protocol:

PN532-NFC-(HSU-Protocol)-Module-Pinout

Pin Configuration

Pin NumberPin NameDescription
1VCCModule power supply – 5V
2GNDGround
3TXDTransmit data pin
4RXDReceive data pin

Specifications

  1. Operating Frequency:
    • Specifies the frequency range at which the PN532 module operates, typically 13.56 MHz for NFC communication.
  2. Communication Interface:
    • Defines the communication protocol used to interface the PN532 module with Arduino, such as SPI (Serial Peripheral Interface) or I2C (Inter-Integrated Circuit).
  3. Operating Voltage:
    • Specifies the voltage range required for the PN532 module to operate properly with Arduino.
  4. Supported NFC Modes:
    • Indicates the NFC modes supported by the PN532 module, including reader/writer mode, peer-to-peer mode, and card emulation mode.
  5. Antenna Configuration:
    • Describes the antenna configuration and options available for optimizing NFC communication performance.

Features

  1. NFC Tag Reading:
    • Allows Arduino projects to read data from NFC tags, such as text, URLs, or application-specific information.
  2. NFC Tag Writing:
    • Enables Arduino projects to write data to NFC tags, allowing for customization and personalization of NFC tag content.
  3. NFC Peer-to-Peer Communication:
    • Supports peer-to-peer communication between NFC-enabled devices, facilitating data exchange and interaction between Arduino projects and other NFC devices.
  4. Card Emulation:
    • Allows Arduino projects to emulate NFC cards or tags, enabling functionalities such as contactless payment, access control, and authentication.
  5. Advanced Security Features:
    • Incorporates security features such as encryption and authentication to ensure secure NFC communication and data exchange.

Circuit Diagram

The following circuit shows you the connection of the How to Read Write or Emulate NFC tags with Arduino and PN532. Please make the connection carefully

The I2C connection would be the following

How-to-Read-write-or-emulate-NFC-tags-with-Arduino-and-PN532-NFC-RFID-Module-I2C-Connection-Circuit

Circuit Connections

ArduinoPN532
VCCVCC
GNDGND
A4SDA
A5SCL

The SPI connection would be the following

How-to-Read-write-or-emulate-NFC-tags-with-Arduino-and-PN532-NFC-RFID-Module-SPI-Connection-Circuit

Circuit Connections

ArduinoPN532
+5VVCC
GNDGND
D13SCK
D12MISO
D11MOSI
D10SS

The HSU connection would be the following

How-to-Read-write-or-emulate-NFC-tags-with-Arduino-and-PN532-NFC-RFID-Module-HSU-Connection-Circuit

Circuit Connections

ArduinoPN532
VCCVCC
GNDGND
D1TXD
D0RXD

Installing Arduino IDE Software

First, you will require to Download the updated version of Arduino IDE Software and Install it on your PC or laptop. if you Learn How to install the Arduino step-by-step guide then click on how to install Arduino Button given Blow

Installing Libraries

Now when you are Ready to upload the code, to the Arduino Board you will need first to add the Following Libraries in Arduino, If you Learn How to add the library in the Arduino step-by-step guide click on how to install the library Button given Blow

Code

Show data and UID

In this example, we display the data from the PN532 reader along with the data from the tags that are detected.

//For more Projects: www.arduinocircuit.com

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


#define PN532_IRQ (2)

#define PN532_RESET (3) // Not connected by default on the NFC Shield

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);
 
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("PN53x not found");
    while (1); // stop
  }

  // Show sensor data
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
  
  // Configure to read RFID tags
  nfc.setPassiveActivationRetries(0xFF);
  nfc.SAMConfig();
  
  Serial.println("Waiting for ISO14443A card");
}

// Auxiliary function to show the buffer
void printArray(byte *buffer, byte bufferSize) {
   for (byte i = 0; i < bufferSize; i++) {
      Serial.print(buffer[i] < 0x10 ? " 0" : " ");
      Serial.print(buffer[i], HEX);
   }
}
 

void loop(void) {
  booleansuccess;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;

  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
  
  if (success) {
    Serial.println("Card found");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID: "); printArray(uid, uidLength);
    Serial.println("");
  
    delay(1000);
  }
  else
  {
    Serial.println("Card not found");
  }
}

Save data

In this example, we demonstrate how to store data in the memory of a tag.

//For more Projects: www.arduinocircuit.com

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


#define PN532_IRQ (2)

#define PN532_RESET (3)

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void)
{
  Serial.begin(115200);

  // Configure to read RFID tags
  nfc.begin();
  nfc.setPassiveActivationRetries(0xFF);
  nfc.SAMConfig();
  
  Serial.println("Waiting for card");
}

void loop(void)
{
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
    
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success) {
      Serial.println("Trying to authenticate block 4 with key KEYA");
      uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
      if (success)
      {
        Serial.println("Sector 1 (Blocks 4 to 7) authenticated");
        uint8_t data[16];
 
        memcpy(data, (const uint8_t[]){ 'l', 'u', 'i', 's', 'l', 'l', 'a', 'm', 'a', 's' , '.', 'e', ​​'s', 0, 0, 0 }, sizeof data);
        success = nfc.mifareclassic_WriteDataBlock(4, data);
    
        if (success)
        {
          Serial.println("Data written in block 4");
          delay(10000);
        }
        else
        {
          Serial.println("Failed to write card");
          delay(1000);
        }
      }
      else
      {
        Serial.println("Card authentication failed");
        delay(1000);
      }
    }
}

Read data

In this example, we demonstrate how to read data previously recorded in the memory of a tag.

//For more Projects: www.arduinocircuit.com

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


#define PN532_IRQ (2)

#define PN532_RESET (3)

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void)
{
  Serial.begin(115200);

  // Configure to read RFID tags
  nfc.begin();
  nfc.setPassiveActivationRetries(0xFF);
  nfc.SAMConfig();
  
  Serial.println("Waiting for card");
}

void loop(void)
{
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
    
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      Serial.println("Trying to authenticate block 4 with key KEYA");
      uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
      if (success)
      {
        Serial.println("Sector 1 (Blocks 4 to 7) authenticated");
        uint8_t data[16];
          
        success = nfc.mifareclassic_ReadDataBlock(4, data);
        if (success)
        {
      Serial.println("Data read from sector 4:");
          nfc.PrintHexChar(data, 16);
          Serial.println("");
          delay(5000);
        }
        else
        {
          Serial.println("Failed to read card");
        }
      }
      else
      {
        Serial.println("Card authentication failed");
      }
    }
}

Check UID

In this example, we validate whether a card is valid by checking its UID.

//For more Projects: www.arduinocircuit.com

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


#define PN532_IRQ (2)

#define PN532_RESET (3)

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);

  // Configure to read RFID tags
  nfc.begin();
  nfc.setPassiveActivationRetries(0xFF);
  nfc.SAMConfig();

  Serial.println("Waiting for card");
}

const uint8_t validUID[4] = { 0xC8, 0x3E, 0xE7, 0x59 }; // Example of valid UID

//Function to compare two vectors
bool isEqualArray(uint8_t* arrayA, uint8_t* arrayB, uint8_t length)
{
  for (uint8_t index = 0; index < length; index++)
  {
    if (arrayA[index] != arrayB[index]) return false;
  }
  return true;
}

void loop(void)
{
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;

  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
    uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

    if (isEqualArray(uid, validUID, uidLength))
    {
      Serial.println("Valid card");
      delay(5000);
    }
    else
    {
      Serial.println("Invalid card");
      delay(5000);
    }
  }
}

Check data

In this example, we validate whether a card is valid by checking the data that we have previously recorded.

//For more Projects: www.arduinocircuit.com

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


#define PN532_IRQ   (2)

#define PN532_RESET (3)

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);

  // Configurar para leer etiquetas RFID
  nfc.begin();
  nfc.setPassiveActivationRetries(0xFF);
  nfc.SAMConfig();

  Serial.println("Esperando tarjeta");
}

const uint8_t validData[16] = { 'l', 'u', 'i', 's', 'l', 'l', 'a', 'm', 'a', 's', '.', 'e', 's', 0, 0, 0 };  // Ejemplo de clave valida

//Función para comparar dos vectores
bool isEqualArray(uint8_t* arrayA, uint8_t* arrayB, uint8_t length)
{
  for (uint8_t index = 0; index < length; index++)
  {
    if (arrayA[index] != arrayB[index]) return false;
  }
  return true;
}

void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;

  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
    uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

    success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
    if (success)
    {
      uint8_t data[16];

      success = nfc.mifareclassic_ReadDataBlock(4, data);
      if (success)
      {
        if (isEqualArray(data, validData, sizeof validData))
        {
          Serial.println("Tarjeta valida");
          delay(5000);
        }
        else
        {
          Serial.println("Tarjeta invalida");
          delay(5000);
        }
      }
    }
    else
    {
      Serial.println("Fallo autentificar tarjeta");
      delay(5000);
    }
  }
}

Emulate a tag

To emulate a tag (NFC Type 4), you can use the Seed-Studio library available at this link. The library includes an example demonstrating the emulation of a tag. However, please note that the actual functionality may be limited.

Applications

  1. Access Control Systems: Use the PN532 module in access control systems for secure and convenient authentication using NFC-enabled cards or smartphones.
  2. Smart Locks: Integrate the PN532 module into smart lock systems for keyless entry using NFC tags or smartphones.
  3. Mobile Payment Systems: Develop mobile payment systems with Arduino using the PN532 module to enable contactless payments via NFC-enabled cards or smartphones.
  4. Inventory Management: Utilize the PN532 module for inventory management applications, such as tracking and identifying items using NFC tags.
  5. Interactive Displays: Create interactive displays or kiosks with Arduino and the PN532 module, allowing users to interact with NFC-enabled devices to access information or perform actions.

Conclusion

The PN532 NFC RFID module offers endless possibilities for NFC-enabled Arduino projects, empowering developers to create innovative solutions for communication, authentication, and interaction with NFC tags and devices. Whether you’re building access control systems, smart locks, mobile payment solutions, or interactive displays, the PN532 module provides essential NFC capabilities for enhancing functionality and user experience. Let’s harness the power of NFC technology with Arduino and explore new avenues of creativity and innovation!

Leave a Comment


error: