Implementing NFC P2P Communication on ESP32 Devices

Near Field CommunicationNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. (NFC) is a short-range wireless communication technology that enables devices to exchange data when they are within a few centimeters of each other. NFC is widely used in applications like contactless payments, access control, and device pairing. In this article, we’ll explore how to set up peer-to-peerUsing Wi-Fi Direct on ESP32 for Peer-to-Peer CommunicationUsing Wi-Fi Direct on ESP32 for Peer-to-Peer CommunicationLearn to set up Wi-Fi Direct on ESP32 for secure P2P IoT communication. Our tutorial offers practical guidance, real-world examples, and troubleshooting tips. (P2P) NFC communication between two ESP32 devices. This can be particularly useful for sharing configuration data, firmware updatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesLearn to securely connect ESP32 to AWS IoT Core using X.509 certificates and device shadows, with step-by-step instructions and best practices., or triggering actions between devices without requiring an internet connection.

Table of Contents🔗

1. Introduction to NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. P2P Communication

2. Hardware Requirements

3. Setting Up NFC Modules on ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips.

4. Implementing NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. P2P Communication

5. Practical ApplicationsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications.

6. Security ConsiderationsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting.

7. Troubleshooting Common IssuesZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting.

8. Advanced Techniques and Optimization

Introduction to NFC P2P Communication🔗

NFC P2P communication allows two devices to exchange data directly without the need for an intermediary like a router or access pointCreating a Wi-Fi Configuration Web Panel for ESP32Creating a Wi-Fi Configuration Web Panel for ESP32Discover how to create a secure ESP32 Wi-Fi configuration web panel for dynamic IoT deployments. Enjoy easy network setups and improved device management.. This is done using the NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. Data Exchange Format (NDEF), a standardized format for storing and transferring data like URLs, text, or custom payloads. In the context of ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips., NFC P2P can be used for:

Hardware Requirements🔗

To implement NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. P2P communication, you’ll need:

Setting Up NFC Modules on ESP32🔗

To use NFC with ESP32, you’ll need to connect the NFC module to the ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. via SPI, I2C, or UARTInterfacing ESP32 with Zigbee3.0 Devices (Xiaomi, Philips Hue)Interfacing ESP32 with Zigbee3.0 Devices (Xiaomi, Philips Hue)Unlock seamless smart home integration by following our detailed guide on bridging ESP32 with external Zigbee modules for reliable IoT solutions.. Below is an example of wiringUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityExplore our detailed tutorial on integrating Quectel BC66/BG96 with ESP32 for low-power, reliable NB-IoT connectivity. Learn hardware setup and AT commands. the PN532 module to the ESP32 using SPI:

Wiring Diagram (PN532 with ESP32)

PN532 PinESP32 Pin
VCC3.3V
GNDGND
SCKGPIO 18
MISOGPIO 19
MOSIGPIO 23
SSGPIO 5
IRQGPIO 4

Code: Initializing the PN532 Module

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#define PN532_SCK  18
#define PN532_MISO 19
#define PN532_MOSI 23
#define PN532_SS   5
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
void setup() {
  Serial.begin(115200);
  nfc.begin();
  uint32_t versiondata = nfc.getFirmwareVersion();
  if (!versiondata) {
    Serial.println("Didn't find PN532 module");
    while (1); // Halt
  }
  Serial.println("Found PN532 module");
  nfc.SAMConfig(); // Configure the Secure Access Module
}

Implementing NFC P2P Communication🔗

Once the NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. modules are set up, you can implement P2P communication. The PN532Adding NFC to ESP32: Hardware Options (PN532, RC522) and WiringAdding NFC to ESP32: Hardware Options (PN532, RC522) and WiringDiscover how NFC transforms your ESP32 projects with PN532 or RC522 modules. Follow our guide for secure contactless interactions and proper wiring setups. library provides functions for sending and receiving NDEF messages.

Sending Data (Device A)

void sendData() {
  uint8_t ndefData[] = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in ASCII
  bool success = nfc.inDataExchange(ndefData, sizeof(ndefData), NULL, 0);
  if (success) {
    Serial.println("Data sent successfully!");
  } else {
    Serial.println("Failed to send data.");
  }
}

Receiving Data (Device B)

void receiveData() {
  uint8_t response[32];
  uint8_t responseLength = 32;
  bool success = nfc.inDataExchange(NULL, 0, response, &responseLength);
  if (success) {
    Serial.print("Received data: ");
    for (int i = 0; i < responseLength; i++) {
      Serial.write(response[i]);
    }
    Serial.println();
  } else {
    Serial.println("Failed to receive data.");
  }
}

Example Workflow

1. Device A prepares an NDEF message and calls sendData().

2. Device B listens for incoming data by calling receiveData().

3. When the devices are brought close together, the data is transferred.

Practical Applications🔗

Here are some real-world use casesZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications. for NFC P2P communication between ESP32 devices:

1. Device Pairing: Share configuration data or authentication tokens between IoT devicesConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies..

2. Firmware UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesLearn to securely connect ESP32 to AWS IoT Core using X.509 certificates and device shadows, with step-by-step instructions and best practices.: Transfer small firmware updatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesAWS IoT Core with ESP32: X.509 Certificates and Shadow UpdatesLearn to securely connect ESP32 to AWS IoT Core using X.509 certificates and device shadows, with step-by-step instructions and best practices. or patches offline.

3. Data Sharing: Exchange sensor dataSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. or logs between devices in the field.

4. Trigger Actions: Use NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. to trigger specific actions, such as turning on a light or starting a process.

Security Considerations🔗

While NFC is convenient, it’s important to secure the communication to prevent unauthorized access or data tampering. Here are some best practicesZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications.:

By following these guidelines, you can ensure that your NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. P2P communication is both efficient and secure.

Troubleshooting Common Issues🔗

IssueSolution
Connection TimeoutReduce distance (<5 cm), check wiring
Data CorruptionLower SPI speed to 1 MHz
Inconsistent RolesImplement role-switching logic

Advanced Techniques and Optimization🔗

1. Multiprotocol Coexistence: Use FreeRTOS tasks to handle NFC alongside Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors./BLE.

2. Low-Power Mode: Activate NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. only when triggered by a GPIO interrupt.

3. Fragmented Transfers: Split large payloads into 128-byte chunks.

// Enable deep sleep with NFC wakeup
esp_sleep_enable_ext1_wakeup(GPIO_SEL_5, ESP_EXT1_WAKEUP_ALL_LOW);
esp_deep_sleep_start();

Understanding NFC P2P Mode

NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. P2P follows the ISO/IEC 18092 standard and uses Logical Link Control Protocol (LLCP). Unlike tag emulation, both devices act as initiator and target, negotiating roles dynamically.

FeatureP2P ModeReader/Writer Mode
CommunicationBidirectionalUnidirectional (tag read/write)
Range<10 cm<5 cm
Data Rate106–424 kbps106 kbps
Use CaseDevice pairing, data swapTag authentication

Hardware Setup for ESP32 NFC P2P

The ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. lacks native NFC hardware, so external modules like the PN532Adding NFC to ESP32: Hardware Options (PN532, RC522) and WiringAdding NFC to ESP32: Hardware Options (PN532, RC522) and WiringDiscover how NFC transforms your ESP32 projects with PN532 or RC522 modules. Follow our guide for secure contactless interactions and proper wiring setups. or ST25R3911B are required.

WiringUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityExplore our detailed tutorial on integrating Quectel BC66/BG96 with ESP32 for low-power, reliable NB-IoT connectivity. Learn hardware setup and AT commands. PN532 via SPI:

ESP32 PinPN532 Pin
GPIO 23MOSI
GPIO 19MISO
GPIO 18SCK
GPIO 5SS/CS
3.3VVCC
GNDGND
#include <Adafruit_PN532.h>
Adafruit_PN532 nfc(5); // CS pin GPIO5
void setup() {
  nfc.begin();
  nfc.SAMConfig(); // Configure Secure Access Module
}

Implementing P2P Communication

Step 1: Initializing P2P Mode

bool initP2P() {
  uint8_t buff[] = {0x00}; // LLCP Magic Number
  if (nfc.inListPassiveTarget()) {
    nfc.setPassiveActivationRetries(0x01);
    return nfc.initiatorInit(buff, sizeof(buff));
  }
  return false;
}

Step 2: Sending Data

void sendData(const String &payload) {
  uint8_t ndefBuf[128];
  uint16_t len = nfc.ndefEncode(payload.c_str(), ndefBuf, sizeof(ndefBuf));
  nfc.inDataExchange(ndefBuf, len, nullptr, 0);
}

Step 3: Receiving Data

String receiveData() {
  uint8_t resp[256];
  uint8_t len = sizeof(resp);
  if (nfc.inDataExchange(nullptr, 0, resp, &len)) {
    return nfc.ndefDecode(resp, len);
  }
  return "";
}

Use Cases and Practical Examples

1. Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. Credential Sharing:

// Device A (Sender)
sendData("SSID:MyNetwork,Pass:SecurePass123");
// Device B (Receiver)
String creds = receiveData();
WiFi.begin(creds.substring(6,16), creds.substring(23));

2. Sensor DataSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. Exchange:

Transfer temperature readings between ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips.-based weather stations in offline environments.

Security Considerations

#include <mbedtls/aes.h>
mbedtls_aes_context aes;
uint8_t key[16] = {0x2B, 0x7E, 0x15, ...}; // 128-bit key
mbedtls_aes_setkey_enc(&aes, key, 128);
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext);

Troubleshooting Common Issues

IssueSolution
Connection TimeoutReduce distance (<5 cm), check wiring
Data CorruptionLower SPI speed to 1 MHz
Inconsistent RolesImplement role-switching logic

Advanced Techniques and Optimization

1. Multiprotocol Coexistence: Use FreeRTOS tasks to handle NFC alongside Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors./BLE.

2. Low-Power Mode: Activate NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security. only when triggered by a GPIO interrupt.

3. Fragmented Transfers: Split large payloads into 128-byte chunks.

// Enable deep sleep with NFC wakeup
esp_sleep_enable_ext1_wakeup(GPIO_SEL_5, ESP_EXT1_WAKEUP_ALL_LOW);
esp_deep_sleep_start();

NFC P2P bridges the gap between convenience and security for ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. devices. Whether you’re building a contactless handshake for industrial tools or a privacy-focused data-sharing app, the combination of simplicity and robustness makes NFC P2P a compelling choice.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles