commit
b3c283172e
7 changed files with 243 additions and 76 deletions
|
@ -13,7 +13,7 @@ Introduction
|
|||
:target: https://travis-ci.org/adafruit/adafruit_CircuitPython_PN532
|
||||
:alt: Build Status
|
||||
|
||||
.. todo:: Describe what the library does.
|
||||
CircuitPython driver for the `PN532 NFC/RFID Breakout <https://www.adafruit.com/product/364>`_ and `PN532 NFC/RFID Shield <https://www.adafruit.com/product/789>`_
|
||||
|
||||
Dependencies
|
||||
=============
|
||||
|
@ -29,7 +29,7 @@ This is easily achieved by downloading
|
|||
Usage Example
|
||||
=============
|
||||
|
||||
.. todo:: Add a quick, simple example. It and other examples should live in the examples folder and be included in docs/examples.rst.
|
||||
Check examples/pn532_simpletest.py for usage example
|
||||
|
||||
Contributing
|
||||
============
|
||||
|
|
|
@ -23,7 +23,7 @@
|
|||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
"""
|
||||
`adafruit_PN532`
|
||||
``adafruit_pn532``
|
||||
====================================================
|
||||
|
||||
This module will let you communicate with a PN532 RFID/NFC shield or breakout
|
||||
|
@ -43,13 +43,12 @@ Implementation Notes
|
|||
|
||||
* Adafruit CircuitPython firmware for the supported boards:
|
||||
https://github.com/adafruit/circuitpython/releases
|
||||
|
||||
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
|
||||
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
|
||||
"""
|
||||
|
||||
|
||||
import time
|
||||
from digitalio import DigitalInOut, Direction
|
||||
from digitalio import Direction
|
||||
import adafruit_bus_device.i2c_device as i2c_device
|
||||
import adafruit_bus_device.spi_device as spi_device
|
||||
|
||||
|
@ -58,7 +57,7 @@ from micropython import const
|
|||
__version__ = "0.0.0-auto.0"
|
||||
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git"
|
||||
|
||||
|
||||
# pylint: disable=bad-whitespace
|
||||
_PREAMBLE = const(0x00)
|
||||
_STARTCODE1 = const(0x00)
|
||||
_STARTCODE2 = const(0xFF)
|
||||
|
@ -174,8 +173,22 @@ _GPIO_P35 = const(5)
|
|||
|
||||
_ACK = b'\x00\x00\xFF\x00\xFF\x00'
|
||||
_FRAME_START = b'\x00\x00\xFF'
|
||||
# pylint: enable=bad-whitespace
|
||||
|
||||
|
||||
def _reset(pin):
|
||||
"""Perform a hardware reset toggle"""
|
||||
pin.direction = Direction.OUTPUT
|
||||
pin.value = True
|
||||
time.sleep(0.1)
|
||||
pin.value = False
|
||||
time.sleep(0.5)
|
||||
pin.value = True
|
||||
time.sleep(0.1)
|
||||
|
||||
def reverse_bit(num):
|
||||
"""Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as
|
||||
it is LSB for the PN532, but 99% of SPI implementations are MSB only!"""
|
||||
result = 0
|
||||
for _ in range(8):
|
||||
result <<= 1
|
||||
|
@ -197,18 +210,15 @@ class PN532:
|
|||
"""
|
||||
self.debug = debug
|
||||
if reset:
|
||||
reset.direction = Direction.OUTPUT
|
||||
reset.value = True
|
||||
time.sleep(0.1)
|
||||
reset.value = False
|
||||
time.sleep(0.1)
|
||||
reset.value = True
|
||||
time.sleep(1)
|
||||
if debug:
|
||||
print("Resetting")
|
||||
_reset(reset)
|
||||
|
||||
try:
|
||||
self._wakeup()
|
||||
self.get_firmware_version() # first time often fails, try 2ce
|
||||
return
|
||||
except:
|
||||
except (BusyError, RuntimeError):
|
||||
pass
|
||||
self.get_firmware_version()
|
||||
|
||||
|
@ -216,7 +226,7 @@ class PN532:
|
|||
# Read raw data from device, not including status bytes:
|
||||
# Subclasses MUST implement this!
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def _write_data(self, framebytes):
|
||||
# Write raw bytestring data to device, not including status bytes:
|
||||
# Subclasses MUST implement this!
|
||||
|
@ -227,10 +237,13 @@ class PN532:
|
|||
# Subclasses MUST implement this!
|
||||
raise NotImplementedError
|
||||
|
||||
def _wakeup(self):
|
||||
# Send special command to wake up
|
||||
raise NotImplementedError
|
||||
|
||||
def _write_frame(self, data):
|
||||
"""Write a frame to the PN532 with the specified data bytearray."""
|
||||
assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
|
||||
assert data is not None and 1 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
|
||||
# Build frame to send as:
|
||||
# - Preamble (0x00)
|
||||
# - Start code (0x00, 0xFF)
|
||||
|
@ -266,6 +279,7 @@ class PN532:
|
|||
response = self._read_data(length+8)
|
||||
if self.debug:
|
||||
print('Read frame:', [hex(i) for i in response])
|
||||
|
||||
# Swallow all the 0x00 values that preceed 0xFF.
|
||||
offset = 0
|
||||
while response[offset] == 0x00:
|
||||
|
@ -276,7 +290,7 @@ class PN532:
|
|||
raise RuntimeError('Response frame preamble does not contain 0x00FF!')
|
||||
offset += 1
|
||||
if offset >= len(response):
|
||||
raise RuntimeError('Response contains no data!')
|
||||
raise RuntimeError('Response contains no data!')
|
||||
# Check length & length checksum match.
|
||||
frame_len = response[offset]
|
||||
if (frame_len + response[offset+1]) & 0xFF != 0:
|
||||
|
@ -288,7 +302,7 @@ class PN532:
|
|||
# Return frame data.
|
||||
return response[offset+2:offset+2+frame_len]
|
||||
|
||||
def call_function(self, command, response_length=0, params=[], timeout=1):
|
||||
def call_function(self, command, response_length=0, params=[], timeout=1): # pylint: disable=dangerous-default-value
|
||||
"""Send specified command to the PN532 and expect up to response_length
|
||||
bytes back in a response. Note that less than the expected bytes might
|
||||
be returned! Params can optionally specify an array of bytes to send as
|
||||
|
@ -298,12 +312,16 @@ class PN532:
|
|||
"""
|
||||
# Build frame data with command and parameters.
|
||||
data = bytearray(2+len(params))
|
||||
data[0] = _HOSTTOPN532
|
||||
data[1] = command & 0xFF
|
||||
for i in range(len(params)):
|
||||
data[2+i] = params[i]
|
||||
data[0] = _HOSTTOPN532
|
||||
data[1] = command & 0xFF
|
||||
for i, val in enumerate(params):
|
||||
data[2+i] = val
|
||||
# Send frame and wait for response.
|
||||
self._write_frame(data)
|
||||
try:
|
||||
self._write_frame(data)
|
||||
except OSError:
|
||||
self._wakeup()
|
||||
return None
|
||||
if not self._wait_ready(timeout):
|
||||
return None
|
||||
# Verify ACK response and wait to be ready for function response.
|
||||
|
@ -328,7 +346,7 @@ class PN532:
|
|||
raise RuntimeError('Failed to detect the PN532')
|
||||
return tuple(response)
|
||||
|
||||
def SAM_configuration(self):
|
||||
def SAM_configuration(self): # pylint: disable=invalid-name
|
||||
"""Configure the PN532 to read MiFare cards."""
|
||||
# Send SAM configuration command with configuration for:
|
||||
# - 0x01, normal mode
|
||||
|
@ -347,7 +365,7 @@ class PN532:
|
|||
try:
|
||||
response = self.call_function(_COMMAND_INLISTPASSIVETARGET,
|
||||
params=[0x01, card_baud],
|
||||
response_length=17,
|
||||
response_length=19,
|
||||
timeout=timeout)
|
||||
except BusyError:
|
||||
return None # no card found!
|
||||
|
@ -362,7 +380,7 @@ class PN532:
|
|||
# Return UID of card.
|
||||
return response[6:6+response[5]]
|
||||
|
||||
def mifare_classic_authenticate_block(self, uid, block_number, key_number, key):
|
||||
def mifare_classic_authenticate_block(self, uid, block_number, key_number, key): # pylint: disable=invalid-name
|
||||
"""Authenticate specified block number for a MiFare classic card. Uid
|
||||
should be a byte array with the UID of the card, block number should be
|
||||
the block to authenticate, key number should be the key type (like
|
||||
|
@ -378,7 +396,7 @@ class PN532:
|
|||
params[1] = key_number & 0xFF
|
||||
params[2] = block_number & 0xFF
|
||||
params[3:3+keylen] = key
|
||||
params[3+keylen:] = uid
|
||||
params[3+keylen:] = uid
|
||||
# Send InDataExchange request and verify response is 0x00.
|
||||
response = self.call_function(_COMMAND_INDATAEXCHANGE,
|
||||
params=params,
|
||||
|
@ -420,11 +438,38 @@ class PN532:
|
|||
response_length=1)
|
||||
return response[0] == 0x0
|
||||
|
||||
def ntag2xx_write_block(self, block_number, data):
|
||||
"""Write a block of data to the card. Block number should be the block
|
||||
to write and data should be a byte array of length 4 with the data to
|
||||
write. If the data is successfully written then True is returned,
|
||||
otherwise False is returned.
|
||||
"""
|
||||
assert data is not None and len(data) == 4, 'Data must be an array of 4 bytes!'
|
||||
# Build parameters for InDataExchange command to do NTAG203 classic write.
|
||||
params = bytearray(3+len(data))
|
||||
params[0] = 0x01 # Max card numbers
|
||||
params[1] = MIFARE_ULTRALIGHT_CMD_WRITE
|
||||
params[2] = block_number & 0xFF
|
||||
params[3:] = data
|
||||
# Send InDataExchange request.
|
||||
response = self.call_function(_COMMAND_INDATAEXCHANGE,
|
||||
params=params,
|
||||
response_length=1)
|
||||
return response[0] == 0x00
|
||||
|
||||
def ntag2xx_read_block(self, block_number):
|
||||
"""Read a block of data from the card. Block number should be the block
|
||||
to read. If the block is successfully read a bytearray of length 16 with
|
||||
data starting at the specified block will be returned. If the block is
|
||||
not read then None will be returned.
|
||||
"""
|
||||
return self.mifare_classic_read_block(block_number)[0:4] # only 4 bytes per page
|
||||
|
||||
class PN532_UART(PN532):
|
||||
"""Driver for the PN532 connected over Serial UART"""
|
||||
def __init__(self, uart, *, irq=None, reset=None, debug=False):
|
||||
"""Create an instance of the PN532 class using Serial connection
|
||||
"""Create an instance of the PN532 class using Serial connection.
|
||||
Optional IRQ pin (not used), reset pin and debugging output.
|
||||
"""
|
||||
self.debug = debug
|
||||
self._irq = irq
|
||||
|
@ -432,10 +477,12 @@ class PN532_UART(PN532):
|
|||
super().__init__(debug=debug, reset=reset)
|
||||
|
||||
def _wakeup(self):
|
||||
"""Send any special commands/data to wake up PN532"""
|
||||
#self._write_frame([_HOSTTOPN532, _COMMAND_SAMCONFIGURATION, 0x01])
|
||||
self.SAM_configuration()
|
||||
|
||||
def _wait_ready(self, timeout=1):
|
||||
"""Wait `timeout` seconds"""
|
||||
time.sleep(timeout)
|
||||
return True
|
||||
|
||||
|
@ -446,9 +493,12 @@ class PN532_UART(PN532):
|
|||
raise BusyError("No data read from PN532")
|
||||
if self.debug:
|
||||
print("Reading: ", [hex(i) for i in frame])
|
||||
else:
|
||||
time.sleep(0.1)
|
||||
return frame
|
||||
|
||||
def _write_data(self, framebytes):
|
||||
"""Write a specified count of bytes to the PN532"""
|
||||
while self._uart.read(1): # this would be a lot nicer if we could query the # of bytes
|
||||
pass
|
||||
self._uart.write('\x55\x55\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') # wake up!
|
||||
|
@ -456,31 +506,45 @@ class PN532_UART(PN532):
|
|||
|
||||
class PN532_I2C(PN532):
|
||||
"""Driver for the PN532 connected over I2C."""
|
||||
def __init__(self, i2c, *, irq=None, reset=None, debug=False):
|
||||
"""Create an instance of the PN532 class using either software SPI (if
|
||||
the sclk, mosi, and miso pins are specified) or hardware SPI if a
|
||||
spi parameter is passed. The cs pin must be a digital GPIO pin.
|
||||
Optionally specify a GPIO controller to override the default that uses
|
||||
the board's GPIO pins.
|
||||
def __init__(self, i2c, *, irq=None, reset=None, req=None, debug=False):
|
||||
"""Create an instance of the PN532 class using I2C. Note that PN532
|
||||
uses clock stretching. Optional IRQ pin (not used),
|
||||
reset pin and debugging output.
|
||||
"""
|
||||
self.debug = debug
|
||||
self._irq = irq
|
||||
self._req = req
|
||||
if reset:
|
||||
_reset(reset)
|
||||
self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS)
|
||||
super().__init__(debug=debug, reset=reset)
|
||||
|
||||
def _wakeup(self):
|
||||
def _wakeup(self): # pylint: disable=no-self-use
|
||||
"""Send any special commands/data to wake up PN532"""
|
||||
if self._req:
|
||||
self._req.direction = Direction.OUTPUT
|
||||
self._req.value = True
|
||||
time.sleep(0.1)
|
||||
self._req.value = False
|
||||
time.sleep(0.1)
|
||||
self._req.value = True
|
||||
time.sleep(0.5)
|
||||
|
||||
def _wait_ready(self, timeout=1):
|
||||
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
|
||||
status = bytearray(1)
|
||||
t = time.monotonic()
|
||||
while (time.monotonic() - t) < timeout:
|
||||
with self._i2c:
|
||||
self._i2c.readinto(status)
|
||||
timestamp = time.monotonic()
|
||||
while (time.monotonic() - timestamp) < timeout:
|
||||
try:
|
||||
with self._i2c:
|
||||
self._i2c.readinto(status)
|
||||
except OSError:
|
||||
self._wakeup()
|
||||
continue
|
||||
if status == b'\x01':
|
||||
return True # No longer busy
|
||||
else:
|
||||
time.sleep(0.1) # lets ask again soon!
|
||||
time.sleep(0.05) # lets ask again soon!
|
||||
# Timed out!
|
||||
return False
|
||||
|
||||
|
@ -495,15 +559,19 @@ class PN532_I2C(PN532):
|
|||
i2c.readinto(frame) # ok get the data, plus statusbyte
|
||||
if self.debug:
|
||||
print("Reading: ", [hex(i) for i in frame[1:]])
|
||||
else:
|
||||
time.sleep(0.1)
|
||||
return frame[1:] # don't return the status byte
|
||||
|
||||
def _write_data(self, framebytes):
|
||||
"""Write a specified count of bytes to the PN532"""
|
||||
with self._i2c as i2c:
|
||||
i2c.write(framebytes)
|
||||
|
||||
class PN532_SPI(PN532):
|
||||
"""Driver for the PN532 connected over SPI. Pass in a hardware or bitbang SPI device & chip select
|
||||
digitalInOut pin. Optional IRQ pin (not used), reset pin and debugging output."""
|
||||
"""Driver for the PN532 connected over SPI. Pass in a hardware or bitbang
|
||||
SPI device & chip select digitalInOut pin. Optional IRQ pin (not used),
|
||||
reset pin and debugging output."""
|
||||
def __init__(self, spi, cs_pin, *, irq=None, reset=None, debug=False):
|
||||
"""Create an instance of the PN532 class using SPI"""
|
||||
self.debug = debug
|
||||
|
@ -512,20 +580,25 @@ class PN532_SPI(PN532):
|
|||
super().__init__(debug=debug, reset=reset)
|
||||
|
||||
def _wakeup(self):
|
||||
"""Send any special commands/data to wake up PN532"""
|
||||
with self._spi as spi:
|
||||
time.sleep(1)
|
||||
spi.write(bytearray([0x00]))
|
||||
time.sleep(1)
|
||||
|
||||
def _wait_ready(self, timeout=1):
|
||||
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
|
||||
status = bytearray([reverse_bit(_SPI_STATREAD), 0])
|
||||
|
||||
t = time.monotonic()
|
||||
while (time.monotonic() - t) < timeout:
|
||||
|
||||
timestamp = time.monotonic()
|
||||
while (time.monotonic() - timestamp) < timeout:
|
||||
with self._spi as spi:
|
||||
time.sleep(0.02) # required
|
||||
spi.write_readinto(status, status)
|
||||
if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB
|
||||
return True # Not busy anymore!
|
||||
else:
|
||||
time.sleep(0.1) # pause a bit till we ask again
|
||||
time.sleep(0.01) # pause a bit till we ask again
|
||||
# We timed out!
|
||||
return False
|
||||
|
||||
|
@ -535,21 +608,23 @@ class PN532_SPI(PN532):
|
|||
frame = bytearray(count+1)
|
||||
# Add the SPI data read signal byte, but LSB'ify it
|
||||
frame[0] = reverse_bit(_SPI_DATAREAD)
|
||||
|
||||
|
||||
with self._spi as spi:
|
||||
time.sleep(0.01) # required
|
||||
time.sleep(0.02) # required
|
||||
spi.write_readinto(frame, frame)
|
||||
for i in range(len(frame)):
|
||||
frame[i] = reverse_bit(frame[i]) # turn LSB data to MSB
|
||||
for i, val in enumerate(frame):
|
||||
frame[i] = reverse_bit(val) # turn LSB data to MSB
|
||||
if self.debug:
|
||||
print("Reading: ", [hex(i) for i in frame[1:]])
|
||||
return frame[1:]
|
||||
|
||||
def _write_data(self, framebytes):
|
||||
# start by making a frame with data write in front, then rest of bytes, and LSBify it
|
||||
reversed = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes]
|
||||
"""Write a specified count of bytes to the PN532"""
|
||||
# start by making a frame with data write in front,
|
||||
# then rest of bytes, and LSBify it
|
||||
rev_frame = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes]
|
||||
if self.debug:
|
||||
print("Writing: ", [hex(i) for i in reversed])
|
||||
print("Writing: ", [hex(i) for i in rev_frame])
|
||||
with self._spi as spi:
|
||||
time.sleep(0.01) # required
|
||||
spi.write(bytes(reversed))
|
||||
time.sleep(0.02) # required
|
||||
spi.write(bytes(rev_frame))
|
||||
|
|
|
@ -20,7 +20,7 @@ extensions = [
|
|||
# Uncomment the below if you use native CircuitPython modules such as
|
||||
# digitalio, micropython and busio. List the modules you use. Without it, the
|
||||
# autodoc module docs will fail to generate with a warning.
|
||||
# autodoc_mock_imports = ["digitalio", "busio"]
|
||||
autodoc_mock_imports = ["digitalio", "busio", "adafruit_bus_device", "micropython"]
|
||||
|
||||
|
||||
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
|
||||
|
|
|
@ -23,14 +23,11 @@ Table of Contents
|
|||
.. toctree::
|
||||
:caption: Tutorials
|
||||
|
||||
.. todo:: Add any Learn guide links here. If there are none, then simply delete this todo and leave
|
||||
the toctree above for use later.
|
||||
|
||||
.. toctree::
|
||||
:caption: Related Products
|
||||
|
||||
.. todo:: Add any product links here. If there are none, then simply delete this todo and leave
|
||||
the toctree above for use later.
|
||||
`PN532 NFC/RFID Breakout <https://www.adafruit.com/product/364>` and `PN532 NFC/RFID Shield <https://www.adafruit.com/product/789>`_
|
||||
|
||||
|
||||
.. toctree::
|
||||
:caption: Other Links
|
||||
|
|
|
@ -1,35 +1,48 @@
|
|||
from Adafruit_Circuitpython_PN532 import adafruit_pn532
|
||||
from digitalio import DigitalInOut, Direction, Pull
|
||||
"""
|
||||
This example shows connecting to the PN532 with I2C (requires clock
|
||||
stretching support), SPI, or UART. SPI is best, it uses the most pins but
|
||||
is the most reliable and universally supported.
|
||||
After initialization, try waving various 13.56MHz RFID cards over it!
|
||||
"""
|
||||
|
||||
import board
|
||||
import time
|
||||
import busio
|
||||
|
||||
reset_pin = DigitalInOut(board.D3)
|
||||
|
||||
from digitalio import DigitalInOut
|
||||
from Adafruit_Circuitpython_PN532 import adafruit_pn532
|
||||
|
||||
# I2C connection:
|
||||
#i2c = busio.I2C(board.SCL, board.SDA)
|
||||
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin)
|
||||
i2c = busio.I2C(board.SCL, board.SDA)
|
||||
|
||||
# Non-hardware
|
||||
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False)
|
||||
|
||||
# With I2C, we recommend connecting RSTPD_N (reset) to a digital pin for manual
|
||||
# harware reset
|
||||
reset_pin = DigitalInOut(board.D6)
|
||||
# On Raspberry Pi, you must also connect a pin to P32 "H_Request" for hardware
|
||||
# wakeup! this means we don't need to do the I2C clock-stretch thing
|
||||
req_pin = DigitalInOut(board.D12)
|
||||
pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin, req=req_pin)
|
||||
|
||||
# SPI connection:
|
||||
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
#cs_pin = DigitalInOut(board.D2)
|
||||
#pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False, reset=reset_pin)
|
||||
#cs_pin = DigitalInOut(board.D5)
|
||||
#pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False)
|
||||
|
||||
# UART connection
|
||||
#uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=100)
|
||||
#pn532 = adafruit_pn532.PN532_UART(uart, debug=False, reset=reset_pin)
|
||||
#pn532 = adafruit_pn532.PN532_UART(uart, debug=False)
|
||||
|
||||
ic, ver, rev, support = pn532.get_firmware_version()
|
||||
print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev))
|
||||
|
||||
# Configure PN532 to communicate with MiFare cards
|
||||
# Configure PN532 to communicate with MiFare cards
|
||||
pn532.SAM_configuration()
|
||||
|
||||
print('Waiting for MiFare card...')
|
||||
print('Waiting for RFID/NFC card...')
|
||||
while True:
|
||||
# Check if a card is available to read
|
||||
uid = pn532.read_passive_target(timeout=0.25)
|
||||
uid = pn532.read_passive_target(timeout=0.5)
|
||||
print('.', end="", flush=True)
|
||||
# Try again if no card is available.
|
||||
if uid is None:
|
||||
|
|
81
examples/readwrite_ntag2xx.py
Normal file
81
examples/readwrite_ntag2xx.py
Normal file
|
@ -0,0 +1,81 @@
|
|||
# Example of detecting and reading a block from a MiFare NFC card.
|
||||
# Author: Tony DiCola & Roberto Laricchia
|
||||
# Copyright (c) 2015 Adafruit Industries
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in all
|
||||
# copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
"""
|
||||
This example shows connecting to the PN532 and writing & reading an ntag2xx
|
||||
type RFID tag
|
||||
"""
|
||||
|
||||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
from Adafruit_Circuitpython_PN532 import adafruit_pn532
|
||||
|
||||
# I2C connection:
|
||||
#i2c = busio.I2C(board.SCL, board.SDA)
|
||||
|
||||
# Non-hardware reset/request with I2C
|
||||
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False)
|
||||
|
||||
# With I2C, we recommend connecting RSTPD_N (reset) to a digital pin for manual
|
||||
# harware reset
|
||||
#reset_pin = DigitalInOut(board.D6)
|
||||
# On Raspberry Pi, you must also connect a pin to P32 "H_Request" for hardware
|
||||
# wakeup! this means we don't need to do the I2C clock-stretch thing
|
||||
#req_pin = DigitalInOut(board.D12)
|
||||
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin, req=req_pin)
|
||||
|
||||
# SPI connection:
|
||||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
cs_pin = DigitalInOut(board.D5)
|
||||
pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False)
|
||||
|
||||
# UART connection
|
||||
#uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=100)
|
||||
#pn532 = adafruit_pn532.PN532_UART(uart, debug=False)
|
||||
|
||||
ic, ver, rev, support = pn532.get_firmware_version()
|
||||
print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev))
|
||||
|
||||
# Configure PN532 to communicate with MiFare cards
|
||||
pn532.SAM_configuration()
|
||||
|
||||
print('Waiting for RFID/NFC card to write to!')
|
||||
while True:
|
||||
# Check if a card is available to read
|
||||
uid = pn532.read_passive_target(timeout=0.5)
|
||||
print('.', end="", flush=True)
|
||||
# Try again if no card is available.
|
||||
if uid is not None:
|
||||
break
|
||||
|
||||
print("")
|
||||
print('Found card with UID:', [hex(i) for i in uid])
|
||||
|
||||
# Set 4 bytes of block to 0xFEEDBEEF
|
||||
data = bytearray(4)
|
||||
data[0:4] = [0xFE, 0xED, 0xBE, 0xEF]
|
||||
# Write 4 byte block.
|
||||
pn532.ntag2xx_write_block(6, data)
|
||||
# Read block #6
|
||||
print('Wrote to block 6, now trying to read that data:',
|
||||
[hex(x) for x in pn532.ntag2xx_read_block(6)])
|
|
@ -1,2 +1,3 @@
|
|||
Adafruit-Blinka
|
||||
adafruit-circuitpython-busdevice
|
||||
pyserial
|
||||
|
|
Loading…
Reference in a new issue