#+TITLE: NFC MODULE V3 Raspberry pi 
#+DATE: 2018-01-07 12:00:00 UTC
#+DESCRIPTION: How to wire and install software to drive a PN532 
#+FILETAGS: tech:pi:nfc
#+CATEGORY: hardware
#+SLUG: nfc-module-v3-raspberry-pi
#+THUMBNAIL: ../../images/hardware/PN532-PI.png
#+BEGIN_COMMENT
.. title: NFC MODULE V3 Raspberry pi 
.. slug: nfc-module-v3-raspberry-pi 
.. date: 2018-01-07 12:00:00 UTC
.. tags: pi, nfc
.. category: tech, pi, nfc
.. description: How to wire and install software to drive a PN532 
.. type: text
#+END_COMMENT

The below guide is to setup a pn532 nfc reader on a raspberry pi.

First up make surer the PN532 is setup in UART mode, and connect to the pi in the same manor as the diagram below.

#+CAPTION: PN532 Rfid read connected to a Raspberry PI 
[[../../images/hardware/PN532-PI.png]]


Before getting started setup your pi with the latest debian image and complete your standard setup.
Once the pi is setup run the commands below installing the necessary libraries.

Run the below commands to install the tools and libraries we will need for the rest of the setup.
#+BEGIN_SRC sh
  sudo apt-get install git build-essential autoconf libtool libpcsclite-dev
  sudo apt-get install libusb-dev libcurl4-openssl-dev libjson-c-dev python-pip
#+END_SRC

Download the nfc library from github.
#+BEGIN_SRC sh
git clone https://github.com/nfc-tools/libnfc.git
cd libnfc
sudo mkdir -p /etc/nfc/devices.d/
#+END_SRC


Copy the relevant config to the correct place on the pi.
#+BEGIN_SRC sh
sudo cp contrib/libnfc/pn532_uart_on_rpi_3.conf.sample /etc/nfc/devices.d/pn532_uart_on_rpi_3.conf
#+END_SRC

Compile the libnfc library.
#+BEGIN_SRC sh
autoreconf -vis
./configure --with-drivers=pn532_uart --sysconfdir=/etc --prefix=/usr
sudo make clean && sudo make install all
#+END_SRC


Install the python library
#+BEGIN_SRC sh
pip install -U nfcpy
#+END_SRC


To check everything is working try running the command below to make sure your reader is detected and listed.
#+BEGIN_SRC sh
nfc-scan-device
#+END_SRC

Now create your first python program to make sure everything is working.
#+BEGIN_SRC python
import nfc
import ndef
from nfc.tag import tt1
from nfc.tag import tt2
from nfc.tag import tt3
from nfc.tag import tt4


tagtypes = (
    ('uid', nfc.tag.tt1.Type1Tag),
    ('uid', nfc.tag.tt2.Type2Tag),
    ('idm', nfc.tag.tt3.Type3Tag),
    ('uid', nfc.tag.tt4.Type4Tag)
)

def connected(tag):
    print tag.type
    for uid, type in tgtypes:
        if isinstance(tag, type):
            print str(attr(tag, uid)).encode("hex")
            return
    print "error: unknown tag type"

with nfc.ContactlessFrontend('tty:S0:pn532') as clf:
    print('waiting for connection')
    print(clf)
    tag = clf.connect(rdwr={'on-connect': lambda tag: False})
    print(str(tag.identifier).encode('hex'))
    print(tag.type)
    if not tag.ndef:
        print('no ndef data') 
    else:
        for record in tag.ndef.records:
            print(record)
#+END_SRC



