Merge pull request #2 from ladyada/master

pylint party
This commit is contained in:
Limor "Ladyada" Fried 2018-08-26 12:11:15 -07:00 committed by GitHub
commit b3c283172e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 243 additions and 76 deletions

View file

@ -13,7 +13,7 @@ Introduction
:target: https://travis-ci.org/adafruit/adafruit_CircuitPython_PN532 :target: https://travis-ci.org/adafruit/adafruit_CircuitPython_PN532
:alt: Build Status :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 Dependencies
============= =============
@ -29,7 +29,7 @@ This is easily achieved by downloading
Usage Example 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 Contributing
============ ============

View file

@ -23,7 +23,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
""" """
`adafruit_PN532` ``adafruit_pn532``
==================================================== ====================================================
This module will let you communicate with a PN532 RFID/NFC shield or breakout 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: * Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases 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 import time
from digitalio import DigitalInOut, Direction from digitalio import Direction
import adafruit_bus_device.i2c_device as i2c_device import adafruit_bus_device.i2c_device as i2c_device
import adafruit_bus_device.spi_device as spi_device import adafruit_bus_device.spi_device as spi_device
@ -58,7 +57,7 @@ from micropython import const
__version__ = "0.0.0-auto.0" __version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git"
# pylint: disable=bad-whitespace
_PREAMBLE = const(0x00) _PREAMBLE = const(0x00)
_STARTCODE1 = const(0x00) _STARTCODE1 = const(0x00)
_STARTCODE2 = const(0xFF) _STARTCODE2 = const(0xFF)
@ -174,8 +173,22 @@ _GPIO_P35 = const(5)
_ACK = b'\x00\x00\xFF\x00\xFF\x00' _ACK = b'\x00\x00\xFF\x00\xFF\x00'
_FRAME_START = b'\x00\x00\xFF' _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): 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 result = 0
for _ in range(8): for _ in range(8):
result <<= 1 result <<= 1
@ -197,18 +210,15 @@ class PN532:
""" """
self.debug = debug self.debug = debug
if reset: if reset:
reset.direction = Direction.OUTPUT if debug:
reset.value = True print("Resetting")
time.sleep(0.1) _reset(reset)
reset.value = False
time.sleep(0.1)
reset.value = True
time.sleep(1)
try: try:
self._wakeup() self._wakeup()
self.get_firmware_version() # first time often fails, try 2ce self.get_firmware_version() # first time often fails, try 2ce
return return
except: except (BusyError, RuntimeError):
pass pass
self.get_firmware_version() self.get_firmware_version()
@ -216,7 +226,7 @@ class PN532:
# Read raw data from device, not including status bytes: # Read raw data from device, not including status bytes:
# Subclasses MUST implement this! # Subclasses MUST implement this!
raise NotImplementedError raise NotImplementedError
def _write_data(self, framebytes): def _write_data(self, framebytes):
# Write raw bytestring data to device, not including status bytes: # Write raw bytestring data to device, not including status bytes:
# Subclasses MUST implement this! # Subclasses MUST implement this!
@ -227,10 +237,13 @@ class PN532:
# Subclasses MUST implement this! # Subclasses MUST implement this!
raise NotImplementedError raise NotImplementedError
def _wakeup(self):
# Send special command to wake up
raise NotImplementedError
def _write_frame(self, data): def _write_frame(self, data):
"""Write a frame to the PN532 with the specified data bytearray.""" """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: # Build frame to send as:
# - Preamble (0x00) # - Preamble (0x00)
# - Start code (0x00, 0xFF) # - Start code (0x00, 0xFF)
@ -266,6 +279,7 @@ class PN532:
response = self._read_data(length+8) response = self._read_data(length+8)
if self.debug: if self.debug:
print('Read frame:', [hex(i) for i in response]) print('Read frame:', [hex(i) for i in response])
# Swallow all the 0x00 values that preceed 0xFF. # Swallow all the 0x00 values that preceed 0xFF.
offset = 0 offset = 0
while response[offset] == 0x00: while response[offset] == 0x00:
@ -276,7 +290,7 @@ class PN532:
raise RuntimeError('Response frame preamble does not contain 0x00FF!') raise RuntimeError('Response frame preamble does not contain 0x00FF!')
offset += 1 offset += 1
if offset >= len(response): if offset >= len(response):
raise RuntimeError('Response contains no data!') raise RuntimeError('Response contains no data!')
# Check length & length checksum match. # Check length & length checksum match.
frame_len = response[offset] frame_len = response[offset]
if (frame_len + response[offset+1]) & 0xFF != 0: if (frame_len + response[offset+1]) & 0xFF != 0:
@ -288,7 +302,7 @@ class PN532:
# Return frame data. # Return frame data.
return response[offset+2:offset+2+frame_len] 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 """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 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 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. # Build frame data with command and parameters.
data = bytearray(2+len(params)) data = bytearray(2+len(params))
data[0] = _HOSTTOPN532 data[0] = _HOSTTOPN532
data[1] = command & 0xFF data[1] = command & 0xFF
for i in range(len(params)): for i, val in enumerate(params):
data[2+i] = params[i] data[2+i] = val
# Send frame and wait for response. # 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): if not self._wait_ready(timeout):
return None return None
# Verify ACK response and wait to be ready for function response. # Verify ACK response and wait to be ready for function response.
@ -328,7 +346,7 @@ class PN532:
raise RuntimeError('Failed to detect the PN532') raise RuntimeError('Failed to detect the PN532')
return tuple(response) return tuple(response)
def SAM_configuration(self): def SAM_configuration(self): # pylint: disable=invalid-name
"""Configure the PN532 to read MiFare cards.""" """Configure the PN532 to read MiFare cards."""
# Send SAM configuration command with configuration for: # Send SAM configuration command with configuration for:
# - 0x01, normal mode # - 0x01, normal mode
@ -347,7 +365,7 @@ class PN532:
try: try:
response = self.call_function(_COMMAND_INLISTPASSIVETARGET, response = self.call_function(_COMMAND_INLISTPASSIVETARGET,
params=[0x01, card_baud], params=[0x01, card_baud],
response_length=17, response_length=19,
timeout=timeout) timeout=timeout)
except BusyError: except BusyError:
return None # no card found! return None # no card found!
@ -362,7 +380,7 @@ class PN532:
# Return UID of card. # Return UID of card.
return response[6:6+response[5]] 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 """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 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 the block to authenticate, key number should be the key type (like
@ -378,7 +396,7 @@ class PN532:
params[1] = key_number & 0xFF params[1] = key_number & 0xFF
params[2] = block_number & 0xFF params[2] = block_number & 0xFF
params[3:3+keylen] = key params[3:3+keylen] = key
params[3+keylen:] = uid params[3+keylen:] = uid
# Send InDataExchange request and verify response is 0x00. # Send InDataExchange request and verify response is 0x00.
response = self.call_function(_COMMAND_INDATAEXCHANGE, response = self.call_function(_COMMAND_INDATAEXCHANGE,
params=params, params=params,
@ -420,11 +438,38 @@ class PN532:
response_length=1) response_length=1)
return response[0] == 0x0 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): class PN532_UART(PN532):
"""Driver for the PN532 connected over Serial UART""" """Driver for the PN532 connected over Serial UART"""
def __init__(self, uart, *, irq=None, reset=None, debug=False): 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.debug = debug
self._irq = irq self._irq = irq
@ -432,10 +477,12 @@ class PN532_UART(PN532):
super().__init__(debug=debug, reset=reset) super().__init__(debug=debug, reset=reset)
def _wakeup(self): def _wakeup(self):
"""Send any special commands/data to wake up PN532"""
#self._write_frame([_HOSTTOPN532, _COMMAND_SAMCONFIGURATION, 0x01]) #self._write_frame([_HOSTTOPN532, _COMMAND_SAMCONFIGURATION, 0x01])
self.SAM_configuration() self.SAM_configuration()
def _wait_ready(self, timeout=1): def _wait_ready(self, timeout=1):
"""Wait `timeout` seconds"""
time.sleep(timeout) time.sleep(timeout)
return True return True
@ -446,9 +493,12 @@ class PN532_UART(PN532):
raise BusyError("No data read from PN532") raise BusyError("No data read from PN532")
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame]) print("Reading: ", [hex(i) for i in frame])
else:
time.sleep(0.1)
return frame return frame
def _write_data(self, framebytes): 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 while self._uart.read(1): # this would be a lot nicer if we could query the # of bytes
pass pass
self._uart.write('\x55\x55\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') # wake up! 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): class PN532_I2C(PN532):
"""Driver for the PN532 connected over I2C.""" """Driver for the PN532 connected over I2C."""
def __init__(self, i2c, *, irq=None, reset=None, debug=False): def __init__(self, i2c, *, irq=None, reset=None, req=None, debug=False):
"""Create an instance of the PN532 class using either software SPI (if """Create an instance of the PN532 class using I2C. Note that PN532
the sclk, mosi, and miso pins are specified) or hardware SPI if a uses clock stretching. Optional IRQ pin (not used),
spi parameter is passed. The cs pin must be a digital GPIO pin. reset pin and debugging output.
Optionally specify a GPIO controller to override the default that uses
the board's GPIO pins.
""" """
self.debug = debug self.debug = debug
self._irq = irq self._irq = irq
self._req = req
if reset:
_reset(reset)
self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS) self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS)
super().__init__(debug=debug, reset=reset) 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) time.sleep(0.5)
def _wait_ready(self, timeout=1): def _wait_ready(self, timeout=1):
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
status = bytearray(1) status = bytearray(1)
t = time.monotonic() timestamp = time.monotonic()
while (time.monotonic() - t) < timeout: while (time.monotonic() - timestamp) < timeout:
with self._i2c: try:
self._i2c.readinto(status) with self._i2c:
self._i2c.readinto(status)
except OSError:
self._wakeup()
continue
if status == b'\x01': if status == b'\x01':
return True # No longer busy return True # No longer busy
else: else:
time.sleep(0.1) # lets ask again soon! time.sleep(0.05) # lets ask again soon!
# Timed out! # Timed out!
return False return False
@ -495,15 +559,19 @@ class PN532_I2C(PN532):
i2c.readinto(frame) # ok get the data, plus statusbyte i2c.readinto(frame) # ok get the data, plus statusbyte
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame[1:]]) print("Reading: ", [hex(i) for i in frame[1:]])
else:
time.sleep(0.1)
return frame[1:] # don't return the status byte return frame[1:] # don't return the status byte
def _write_data(self, framebytes): def _write_data(self, framebytes):
"""Write a specified count of bytes to the PN532"""
with self._i2c as i2c: with self._i2c as i2c:
i2c.write(framebytes) i2c.write(framebytes)
class PN532_SPI(PN532): class PN532_SPI(PN532):
"""Driver for the PN532 connected over SPI. Pass in a hardware or bitbang SPI device & chip select """Driver for the PN532 connected over SPI. Pass in a hardware or bitbang
digitalInOut pin. Optional IRQ pin (not used), reset pin and debugging output.""" 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): def __init__(self, spi, cs_pin, *, irq=None, reset=None, debug=False):
"""Create an instance of the PN532 class using SPI""" """Create an instance of the PN532 class using SPI"""
self.debug = debug self.debug = debug
@ -512,20 +580,25 @@ class PN532_SPI(PN532):
super().__init__(debug=debug, reset=reset) super().__init__(debug=debug, reset=reset)
def _wakeup(self): def _wakeup(self):
"""Send any special commands/data to wake up PN532"""
with self._spi as spi: with self._spi as spi:
time.sleep(1) time.sleep(1)
spi.write(bytearray([0x00]))
time.sleep(1)
def _wait_ready(self, timeout=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]) status = bytearray([reverse_bit(_SPI_STATREAD), 0])
t = time.monotonic() timestamp = time.monotonic()
while (time.monotonic() - t) < timeout: while (time.monotonic() - timestamp) < timeout:
with self._spi as spi: with self._spi as spi:
time.sleep(0.02) # required
spi.write_readinto(status, status) spi.write_readinto(status, status)
if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB
return True # Not busy anymore! return True # Not busy anymore!
else: 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! # We timed out!
return False return False
@ -535,21 +608,23 @@ class PN532_SPI(PN532):
frame = bytearray(count+1) frame = bytearray(count+1)
# Add the SPI data read signal byte, but LSB'ify it # Add the SPI data read signal byte, but LSB'ify it
frame[0] = reverse_bit(_SPI_DATAREAD) frame[0] = reverse_bit(_SPI_DATAREAD)
with self._spi as spi: with self._spi as spi:
time.sleep(0.01) # required time.sleep(0.02) # required
spi.write_readinto(frame, frame) spi.write_readinto(frame, frame)
for i in range(len(frame)): for i, val in enumerate(frame):
frame[i] = reverse_bit(frame[i]) # turn LSB data to MSB frame[i] = reverse_bit(val) # turn LSB data to MSB
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame[1:]]) print("Reading: ", [hex(i) for i in frame[1:]])
return frame[1:] return frame[1:]
def _write_data(self, framebytes): def _write_data(self, framebytes):
# start by making a frame with data write in front, then rest of bytes, and LSBify it """Write a specified count of bytes to the PN532"""
reversed = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes] # 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: 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: with self._spi as spi:
time.sleep(0.01) # required time.sleep(0.02) # required
spi.write(bytes(reversed)) spi.write(bytes(rev_frame))

View file

@ -20,7 +20,7 @@ extensions = [
# Uncomment the below if you use native CircuitPython modules such as # Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the # digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning. # 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)} 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)}

View file

@ -23,14 +23,11 @@ Table of Contents
.. toctree:: .. toctree::
:caption: Tutorials :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:: .. toctree::
:caption: Related Products :caption: Related Products
.. todo:: Add any product links here. If there are none, then simply delete this todo and leave `PN532 NFC/RFID Breakout <https://www.adafruit.com/product/364>` and `PN532 NFC/RFID Shield <https://www.adafruit.com/product/789>`_
the toctree above for use later.
.. toctree:: .. toctree::
:caption: Other Links :caption: Other Links

View file

@ -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 board
import time
import busio import busio
from digitalio import DigitalInOut
reset_pin = DigitalInOut(board.D3) from Adafruit_Circuitpython_PN532 import adafruit_pn532
# I2C connection: # I2C connection:
#i2c = busio.I2C(board.SCL, board.SDA) i2c = busio.I2C(board.SCL, board.SDA)
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin)
# 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 connection:
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
#cs_pin = DigitalInOut(board.D2) #cs_pin = DigitalInOut(board.D5)
#pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False, reset=reset_pin) #pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False)
# UART connection # UART connection
#uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=100) #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() ic, ver, rev, support = pn532.get_firmware_version()
print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev)) 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() pn532.SAM_configuration()
print('Waiting for MiFare card...') print('Waiting for RFID/NFC card...')
while True: while True:
# Check if a card is available to read # 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) print('.', end="", flush=True)
# Try again if no card is available. # Try again if no card is available.
if uid is None: if uid is None:

View 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)])

View file

@ -1,2 +1,3 @@
Adafruit-Blinka
adafruit-circuitpython-busdevice adafruit-circuitpython-busdevice
pyserial pyserial