Raspberry PI NFC Reader Control Code

NFC readers are used for reading data from RFID cards. These cards are radio frequency ID cards which can send data without battery. Electricity is generated in the cards from the electromagnetic field of the NFC reader. The cards can be used for authenticating persons or object. You can control both RC522 and PN532 NFC readers. You can learn more about RFID cards and NFC readers on the internet.

Before running the python codes you need to install the required library's. Please download this setup file for the RC522 card reader and this setup file for the PN532 card reader run the script as superuser (sudo ./setup<module name>.sh).

Required hardware

  • Raspberry PI
  • NFC Reader(s)

Source code to install on controller


#!/usr/bin/env python

import signal
import time
import sys

from pirc522 import RFID

run = True
rdr = RFID()
util = rdr.util()
util.debug = True

def end_read(signal, frame):
    global run
    print("\nCtrl+C captured, ending read.")
    run = False
    rdr.cleanup()
    sys.exit()


signal.signal(signal.SIGINT, end_read)

print("Starting")
while run:
    (error, data) = rdr.request()
    if not error:
        print("\nDetected: " + format(data, "02x"))

    (error, uid) = rdr.anticoll()
    if not error:
        print("Card read UID: " + str(uid[0]) + "," + str(uid[1]) + "," +
        		str(uid[2]) + "," + str(uid[3]))

        print("Setting tag")
        util.set_tag(uid)
        print("\nAuthorizing")
        # util.auth(rdr.auth_a, [0x12, 0x34, 0x56, 0x78, 0x96, 0x92])
        util.auth(rdr.auth_b, [0x74, 0x00, 0x52, 0x35, 0x00, 0xFF])
        print("\nReading")
        util.read_out(4)
        print("\nDeauthorizing")
        util.deauth()

        time.sleep(1)

Source code to install on controller


#!/usr/bin/env python

import time
from subprocess import call

def main():
    try:
        while True:
	    call('nfc-poll')
    except:
	KeyboardInterrupt()

if __name__ == "__main__":
    main()

More information