NFC Tag Reader with PyNFC

  • Share this:

Code introduction


This function uses the PyNFC library to connect to an NFC reader, waits for an NFC tag to appear, and then reads the data from the tag.


Technology Stack : PyNFC, NFC

Code Type : Function

Code Difficulty : Intermediate


                
                    
import nfc
import time

def read_tag_with_pynfc(tag):
    # This function reads the data from a NFC tag using the PyNFC library
    def connect_to_reader():
        # Connect to a NFC reader
        for reader in nfc.readers():
            if reader.name == 'PN532':
                return reader
        raise IOError("No PN532 reader found")

    reader = connect_to_reader()
    reader.connect()

    # Wait for the tag to be present
    while True:
        tag = reader.poll(1)
        if tag is not None:
            break
        time.sleep(1)

    # Read the tag data
    data = tag.ndef.read()
    reader.close()
    return data                
              
Tags: