878  NFC Implementation and Applications

878.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Program NFC Tags: Write URL, text, and custom data to NFC tags
  • Build NFC Applications: Develop Android and Python NFC applications
  • Implement IoT Solutions: Create NFC-enabled smart home and access control systems
  • Apply Best Practices: Follow NFC deployment guidelines for reliable interactions

878.2 Prerequisites

Before diving into this chapter, you should be familiar with:

NFC Deep Dives: - NFC Communication Fundamentals - Operating modes and NDEF - NFC IoT Integration - IoT ecosystems and labs - NFC Security and Comparisons - Security and technology comparisons

Related Technologies: - RFID Hands-on - Related contactless technology - Bluetooth Applications - BLE pairing and beacons

Programming an NFC tag is like writing a note that anyone can read by touching it with their phone. The simplest thing you can put on a tag is a URL - when someone taps the tag, their phone opens that webpage automatically.

What you need: - An NFC tag ($0.20-$2.00 each) - A smartphone with NFC - An NFC writing app (free: NFC Tools, TagWriter)

Simple steps: 1. Open NFC writing app 2. Choose β€œWrite” then β€œURL” 3. Enter your website address 4. Hold tag near phone’s NFC antenna 5. Done! Anyone can now tap to visit your site


878.3 Hands-On: Programming NFC Tags

878.3.1 Example 1: Write URL to NFC Tag (Android)

Java Code:

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;

public void writeUrlToTag(Tag tag, String url) throws Exception {
    // Create NDEF message with URL
    NdefRecord uriRecord = NdefRecord.createUri(url);
    NdefMessage message = new NdefMessage(new NdefRecord[]{uriRecord});

    // Write to tag
    Ndef ndef = Ndef.get(tag);
    ndef.connect();
    ndef.writeNdefMessage(message);
    ndef.close();

    Log.d("NFC", "URL written: " + url);
}

Usage:

// In your Activity
@Override
protected void onNewIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    writeUrlToTag(tag, "https://iotclass.example.com");
}

878.3.2 Example 2: Read NFC Tag (Python with PN532)

Hardware: - Raspberry Pi - PN532 NFC module - NFC tags

Python Code:

import nfc

# Connect to NFC reader
clf = nfc.ContactlessFrontend('tty:USB0:pn532')

def on_tag_discovered(tag):
    """Callback when tag is detected"""
    print(f"Tag detected: {tag}")

    # Read NDEF message
    if tag.ndef:
        for record in tag.ndef.records:
            print(f"Type: {record.type}")
            print(f"Data: {record.text if hasattr(record, 'text') else record.uri}")
    else:
        print("No NDEF data found")

    return True  # Keep tag connected

# Listen for tags
print("Waiting for NFC tag...")
clf.connect(rdwr={'on-connect': on_tag_discovered})

Write to Tag:

import ndef

# Create NDEF message
uri_record = ndef.UriRecord("https://iotclass.example.com")
text_record = ndef.TextRecord("Welcome to IoT Class!")

message = [uri_record, text_record]

# Write to tag
def write_tag(tag):
    if tag.ndef:
        tag.ndef.records = message
        print("Written successfully!")
    return False

clf.connect(rdwr={'on-connect': write_tag})

878.3.3 Example 3: Arduino NFC (PN532)

#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);

void setup() {
    Serial.begin(9600);
    nfc.begin();
    Serial.println("NFC Reader Ready!");
}

void loop() {
    if (nfc.tagPresent()) {
        NfcTag tag = nfc.read();

        Serial.println("Tag detected!");
        Serial.print("UID: ");
        Serial.println(tag.getUidString());

        // Read NDEF message
        if (tag.hasNdefMessage()) {
            NdefMessage message = tag.getNdefMessage();
            int recordCount = message.getRecordCount();

            for (int i = 0; i < recordCount; i++) {
                NdefRecord record = message.getRecord(i);

                // Print record type and payload
                Serial.print("Record ");
                Serial.print(i);
                Serial.print(": ");

                int payloadLength = record.getPayloadLength();
                byte payload[payloadLength];
                record.getPayload(payload);

                // Print as string (if text/URI)
                for (int j = 0; j < payloadLength; j++) {
                    Serial.print((char)payload[j]);
                }
                Serial.println();
            }
        }
    }

    delay(1000);
}

Question: A museum deploys NFC tags at exhibits to provide visitor information. What is the advantage of using dynamic NFC tags (tags pointing to URLs) versus static tags (tags containing all information)?

πŸ’‘ Explanation: Dynamic vs static NFC tags represent fundamentally different approaches to content delivery:

Static NFC Tags (data stored ON tag):

Advantages: - βœ… Works offline (no network required) - βœ… Instant access (no server latency) - βœ… No hosting costs (one-time tag cost) - βœ… Privacy (no tracking possible)

Disadvantages: - ❌ Limited storage (144-888 bytes max) - ❌ Cannot update content (must replace tag) - ❌ No analytics (can’t track who tapped when) - ❌ No multimedia (text only, no images/video)

Dynamic NFC Tags (URL pointing to server):

Advantages: - βœ… Updateable: Change content without touching tags - βœ… Unlimited content: Server can host GB of data - βœ… Rich media: Images, videos, audio, interactive - βœ… Analytics: Track taps, time, demographics - βœ… Personalization: Different content per user

Disadvantages: - ❌ Requires network (no Wi-Fi = no content) - ❌ Server costs (hosting, domain, SSL) - ❌ Latency (1-2 second load time)

Museum example:

Dynamic approach (URL):

Tag content (30 bytes):
https://museum.com/e/mona-lisa

Server response:
- High-res images
- Audio guide (20 languages)
- Video documentary
- Related works
- Visitor reviews

Content updates without touching physical tag!

For museum use case: Dynamic tags are almost always better due to updateability and analytics!

878.4 Real-World NFC Applications

878.4.1 Mobile Payments

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D', 'background': '#ffffff', 'mainBkg': '#2C3E50', 'secondBkg': '#16A085', 'tertiaryBkg': '#E67E22'}}}%%
sequenceDiagram
    participant C as Customer Phone
    participant T as Terminal
    participant B as Bank

    C->>T: Tap (NFC)
    Note over C: Biometric Auth
    T->>C: Request Payment
    C->>T: Token + Cryptogram
    T->>B: Validate
    B->>T: Approved
    T->>C: Success

    Note over C,T: <1 second

Figure 878.1: Mobile payment transaction flow: tap, authenticate, tokenize, and authorize

How It Works:

  1. Customer taps phone to terminal
  2. Phone emulates credit card via NFC
  3. Terminal sends encrypted transaction to bank
  4. Bank authorizes payment
  5. Transaction complete (< 1 second)

Security Features: - Tokenization: Real card number never shared - Biometric auth: Fingerprint/face required - Secure element: Encrypted storage of payment credentials - Device-specific: Token tied to specific phone

Market Leaders: - Apple Pay (iPhone, Apple Watch) - Google Pay (Android) - Samsung Pay (Samsung devices)

878.4.2 Smart Home Automation

NFC Tags for IoT Control:

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D', 'background': '#ffffff', 'mainBkg': '#2C3E50', 'secondBkg': '#16A085', 'tertiaryBkg': '#E67E22'}}}%%
flowchart TD
    Phone[Smartphone] -->|Tap| Tag1[Bedside NFC Tag]
    Phone -->|Tap| Tag2[Car NFC Tag]

    Tag1 -->|Trigger| Scene1[Goodnight Scene]
    Tag2 -->|Trigger| Scene2[Driving Scene]

    Scene1 -->|Turn Off| Lights[All Lights]
    Scene1 -->|Lock| Doors[Smart Locks]
    Scene1 -->|Set| Thermo[Thermostat to 68F]

    Scene2 -->|Open| Garage[Garage Door]
    Scene2 -->|Start| Climate[Climate Control]

    style Phone fill:#2C3E50,stroke:#16A085,color:#fff
    style Tag1 fill:#16A085,stroke:#2C3E50,color:#fff
    style Tag2 fill:#16A085,stroke:#2C3E50,color:#fff
    style Scene1 fill:#E67E22,stroke:#2C3E50,color:#fff
    style Scene2 fill:#E67E22,stroke:#2C3E50,color:#fff

Figure 878.2: NFC tags triggering smart home automation scenes for bedtime and driving

Example Scenarios:

β€œGoodnight” Tag (bedside table): - Tap β†’ Turn off all lights - Set thermostat to 68Β°F - Arm security system - Set phone to Do Not Disturb

β€œWelcome Home” Tag (front door): - Disarm security - Turn on entry lights - Adjust temperature - Start favorite playlist

Implementation with Home Assistant:

# automations.yaml
- id: nfc_bedtime_routine
  alias: "NFC: Bedtime Routine"
  trigger:
    platform: tag
    tag_id: "04:A3:B2:C1:D4:5E:80"  # NFC tag UID
  action:
    - service: light.turn_off
      entity_id: all
    - service: climate.set_temperature
      data:
        temperature: 68
    - service: alarm_control_panel.alarm_arm_night

878.4.3 Product Authentication

Anti-Counterfeiting:

  • Luxury goods: Verify authentic Louis Vuitton, Rolex
  • Pharmaceuticals: Ensure medicine is genuine
  • Electronics: Confirm legitimate Apple, Samsung products
  • Wine/Spirits: Authenticate bottles, track provenance

How It Works: 1. Manufacturer embeds NFC tag with unique encrypted ID 2. Tag registered in blockchain or secure database 3. Customer taps tag with phone 4. App verifies authenticity via cloud lookup 5. Displays product history, warranty info

878.4.4 Smart Posters & Marketing

Interactive Advertising:

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D', 'background': '#ffffff', 'mainBkg': '#2C3E50', 'secondBkg': '#16A085', 'tertiaryBkg': '#E67E22'}}}%%
flowchart LR
    Poster[Smart Poster<br/>with NFC Tag] -->|Tap| Phone[User's Phone]

    Phone -->|Open| Content[Digital Content]

    Content -->|Stream| Video[Movie Trailer]
    Content -->|Purchase| Tickets[Buy Tickets]
    Content -->|Download| Coupon[Discount Coupon]

    style Poster fill:#2C3E50,stroke:#16A085,color:#fff
    style Phone fill:#16A085,stroke:#2C3E50,color:#fff
    style Content fill:#E67E22,stroke:#2C3E50,color:#fff

Figure 878.3: Smart poster NFC tag delivering video trailers, tickets, and coupons

Use Cases: - Movie posters: Tap to watch trailer, buy tickets - Restaurant menus: Nutrition info, allergens, reviews - Museum exhibits: Audio guides, detailed information - Real estate: Virtual tours, floor plans, contact agent - Bus stops: Tap for real-time arrival information

878.4.5 Access Control

Physical Security:

  • Hotel room keys: Smartphone as room key (Hilton, Marriott)
  • Office buildings: NFC badges or phone-based access
  • Parking garages: Tap to enter/exit
  • Gym membership: NFC wristband or phone check-in

Advantages: - No physical key cards to lose - Remote access granting/revocation - Audit trail of entry/exit - Integration with mobile apps

878.5 Security Considerations

WarningNFC Security Risks

While NFC’s short range provides inherent security, risks exist:

  • Eavesdropping: Attackers capture communication (requires proximity)
  • Data corruption: Intentional or accidental tag modification
  • Relay attacks: Extend NFC range using relay devices
  • Cloning: Copy tag data to create duplicate
  • Malicious tags: Tags programmed to exploit vulnerabilities

878.5.1 Security Best Practices

For Payment Systems:

βœ… Tokenization: Never transmit actual card numbers βœ… EMV standards: Follow EMVCo specifications βœ… User authentication: Require biometric or PIN βœ… Transaction limits: Cap contactless payment amounts βœ… Secure element: Use hardware-based key storage

For Access Control:

βœ… Encryption: AES-128 minimum for sensitive data βœ… Mutual authentication: Reader and tag both verify identity βœ… Unique keys: Per-tag encryption keys βœ… Audit logging: Track all access attempts βœ… Expiration: Time-limited access credentials

For Smart Tags:

βœ… Lock tags: Make read-only after deployment βœ… Signature verification: Cryptographically sign critical data βœ… HTTPS only: Use secure URLs in NDEF records βœ… Sanitize input: Validate data read from unknown tags βœ… User confirmation: Require user approval for sensitive actions

Example: Secure NDEF Signature

// Sign NDEF message
NdefRecord signature = NdefRecord.createMime(
    "application/vnd.bluetooth.signature",
    signData(payload, privateKey)
);

NdefMessage secureMessage = new NdefMessage(
    new NdefRecord[] {dataRecord, signature}
);

878.6 Best Practices

βœ… Test Across Devices: iPhones, Android phones behave differently βœ… Optimize Tag Placement: Avoid metal surfaces, test read range βœ… Use NDEF Standard: Ensures compatibility across platforms βœ… Provide Visual Cues: Show users where to tap βœ… Handle Read Failures: Network issues, tag damage, distance βœ… Secure Sensitive Actions: Require user confirmation for payments, access βœ… Monitor Tag Health: Check for corruption, physical damage

878.7 Videos

NoteNFC Introduction
NFC Introduction
From Lesson 4 β€” NFC basics, passive vs active devices, and IoT use cases.

878.8 Summary

This chapter covered NFC implementation and applications:

  • Tag Programming: Write URLs, text, and custom data using Android, Python, and Arduino
  • Mobile Payments: Tokenization and secure element architecture for Apple Pay and Google Pay
  • Smart Home: NFC tags triggering IoT automation scenes
  • Product Authentication: Anti-counterfeiting with encrypted NFC tags
  • Security Best Practices: Encryption, authentication, and input validation

878.9 What’s Next

Continue to NFC IoT Integration to explore NFC gateway patterns, hands-on labs with ESP32 and Raspberry Pi, and advanced IoT integration scenarios.