Uncategorized

penzu pirc522 usage examples

5:27PM FRI. 4/10/2020
MRFC522 Programming V1.0 – pirc522 usage examples

penzi link: https://penzu.com/p/e2834d88

RFID Usage

https://github.com/ondryaso/pi-rc522/blob/master/README.md

from pirc522 import RFID
rdr = RFID()

while True:
rdr.wait_for_tag()
(error, tag_type) = rdr.request()
if not error:
print(“Tag detected”)
(error, uid) = rdr.anticoll()
if not error:
print(“UID: ” + str(uid))
# Select Tag is required before Auth
if not rdr.select_tag(uid):
# Auth for block 10 (block 2 of sector 2) using default shipping key A
if not rdr.card_auth(rdr.auth_a, 10, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], uid):
# This will print something like (False, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
print(“Reading block 10: ” + str(rdr.read(10)))
# Always stop crypto1 when done working
rdr.stop_crypto()

# Calls GPIO cleanup
rdr.cleanup()

# ***************************************************************************************

RFIDUtil Usage

https://github.com/ondryaso/pi-rc522/blob/master/README.md

from pirc522 import RFID
import signal
import time

rdr = RFID()
util = rdr.util()
# Set util debug to true – it will print what’s going on
util.debug = True

while True:
# Wait for tag
rdr.wait_for_tag()

# Request tag
(error, data) = rdr.request()
if not error:
print(“\nDetected”)

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

# Set tag as used in util. This will call RFID.select_tag(uid)
util.set_tag(uid)
# Save authorization info (key B) to util. It doesn’t call RFID.card_auth(), that’s called when needed
util.auth(rdr.auth_b, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])
# Print contents of block 4 in format “S1B0: [contents in decimal]”. RFID.card_auth() will be called now
util.read_out(4)
# Print it again – now auth won’t be called, because it doesn’t have to be
util.read_out(4)
# Print contents of different block – S1B2 – RFID.card_auth() will be called again
util.read_out(6)
# We can change authorization info if you have different key in other sector
util.auth(rdr.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])
#If you want to use methods from RFID itself, you can use this for authorization
# This will authorize for block 1 of sector 2 -> block 9
# This is once more called only if it’s not already authorized for this block
util.do_auth(util.block_addr(2, 1))
# Now we can do some “lower-level” stuff with block 9
rdr.write(9, [0x01, 0x23, 0x45, 0x67, 0x89, 0x98, 0x76, 0x54, 0x32, 0x10, 0x69, 0x27, 0x46, 0x66, 0x66, 0x64])
# We can rewrite specific bytes in block using this method. None means “don’t change this byte”
# Note that this won’t do authorization, because we’ve already called do_auth for block 9
util.rewrite(9, [None, None, 0xAB, 0xCD, 0xEF])
# This will write S2B1: [0x01, 0x23, 0xAB, 0xCD, 0xEF, 0x98, 0x76……] because we’ve rewritten third, fourth and fifth byte
util.read_out(9)
# Let’s see what do we have in whole tag
util.dump()
# We must stop crypto
util.deauth()

# .END

5:27PM FRI. 4/10/2020

1:55PM FRI. 4/10/2020
MRFC522 Programming V0.9 – ondryaso/pi-rc522 Rpi python library

penzi link: https://penzu.com/p/5d6537ce

ondryaso/pi-rc522 Rpi python library for SPI RFID RC522 module (Add support for interrupt driven tag detection) Latest commit
da9928a on Sep 12, 2019

Python RC522 library
pi-rc522 consists of two Python classes for controlling an SPI RFID module “RC522” using Raspberry Pi or Beaglebone Black. You can get this module on AliExpress or Ebay for $3.

Based on MFRC522-python.

Install using pip:

pip install pi-rc522
Or get source code from Github:

git clone https://github.com/ondryaso/pi-rc522.gitcd pi-rc522python setup.py install

You’ll also need to install the spidev and RPi.GPIO libraries on Raspberry PI, and Adafruit_BBIO on Beaglebone Black (which should be installed by default).

MIFARE datasheet can be useful.

Sectors? Blocks?
Classic 1K MIFARE tag has 16 sectors, each contains 4 blocks.

Each block has 16 bytes. All this stuff is indexed – you must count from zero.

The library uses “block addresses”, which are positions of blocks – so block address 5 is second block of second sector, thus it’s block 1 of sector 1 (indexes).

Block addresses 0, 1, 2, 3 are from the first sector – sector 0.

Block addresses 4, 5, 6, 7 are from the second sector – sector 1, and so on.

You should not write to first block – S0B0, because it contains manufacturer data.

Each sector has it’s sector trailer, which is located at it’s last block – block 3. This block contains keys and access bits for corresponding sector. For more info, look at page 10 of the datasheet.

You can use this useful utility to calculate access bits.

Connecting
Connecting RC522 module to SPI is pretty easy. You can use this neat website for reference.

Board pin name Board pin Physical RPi pin RPi pin name Beaglebone Black pin name
SDA 1 24 GPIO8, CE0 P9_17, SPI0_CS0
SCK 2 23 GPIO11, SCKL P9_22, SPI0_SCLK
MOSI 3 19 GPIO10, MOSI P9_18, SPI0_D1
MISO 4 21 GPIO9, MISO P9_21, SPI0_D0
IRQ 5 18 GPIO24 P9_15, GPIO_48
GND 6 6, 9, 20, 25 Ground Ground
RST 7 22 GPIO25 P9_23, GPIO_49
3.3V 8 1,17 3V3 VDD_3V3

You can also connect the SDA pin to CE1 (GPIO7, pin #26) and call the RFID constructor with bus=0, device=1 and you can connect RST pin to any other free GPIO pin and call the constructor with pin_rst=BOARD numbering pin.

Furthermore, the IRQ pin is configurable by passing pin_irq=BOARD numbering pin.

NOTE: For RPi A+/B+/2/3 with 40 pin connector, SPI1/2 is available on top of SPI0. Kernel 4.4.x or higher and dtoverlay configuration is required. For SPI1/2, pin_ce=BOARD numbering pin is required.

NOTE: On Beaglebone Black, use pin names (e.g. “P9_17”).

NOTE: On Beaglebone Black, generally you have to enable the SPI for the spidev device to show up; you can enable SPI0 by doing echo BB-SPIDEV0 > /sys/devices/bone_capemgr.9/slots. SPI1 is available only if you disable HDMI.

You may change BOARD pinout to BCM py passing pin_mode=RPi.GPIO.BCM. Please note, that you then have to define all pins (irq+rst, ce if neccessary). Otherwise they would default to perhaps wrong pins (rst to pin 15/GPIO22, irq to pin 12/GPIO18).

Usage
The library is split to two classes – RFID and RFIDUtil.

You can use only RFID, RFIDUtil just makes life a little bit better.

You basically want to start with while True loop and “poll” the tag state. That’s done using request method. Most of the methods return error state, which is simple boolean – True is error, False is not error. The request method returns True if tag is not present.

If request is successful, you should call anticoll method. It runs anti-collision algorithms and returns used tag UID, which you’ll use for select_tag method.

Now you can do whatever you want. Important methods are documented. You can also look at the Read and KeyChange examples for RFIDUtil usage.

from pirc522 import RFIDrdr = RFID()while True: rdr.wait_for_tag() (error, tag_type) = rdr.request() if not error: print(“Tag detected”) (error, uid) = rdr.anticoll() if not error: print(“UID: ” + str(uid)) # Select Tag is required before Auth if not rdr.select_tag(uid): # Auth for block 10 (block 2 of sector 2) using default shipping key A if not rdr.card_auth(rdr.auth_a, 10, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], uid): # This will print something like (False, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) print(“Reading block 10: ” + str(rdr.read(10))) # Always stop crypto1 when done working rdr.stop_crypto()# Calls GPIO cleanuprdr.cleanup()
Util usage
RFIDUtil contains a few useful methods for dealing with tags.

from pirc522 import RFIDimport signalimport timerdr = RFID()util = rdr.util()# Set util debug to true – it will print what’s going onutil.debug = Truewhile True: # Wait for tag rdr.wait_for_tag() # Request tag (error, data) = rdr.request() if not error: print(“\nDetected”) (error, uid) = rdr.anticoll() if not error: # Print UID print(“Card read UID: “+str(uid[0])+”,”+str(uid[1])+”,”+str(uid[2])+”,”+str(uid[3])) # Set tag as used in util. This will call RFID.select_tag(uid) util.set_tag(uid) # Save authorization info (key B) to util. It doesn’t call RFID.card_auth(), that’s called when needed util.auth(rdr.auth_b, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) # Print contents of block 4 in format “S1B0: [contents in decimal]”. RFID.card_auth() will be called now util.read_out(4) # Print it again – now auth won’t be called, because it doesn’t have to be util.read_out(4) # Print contents of different block – S1B2 – RFID.card_auth() will be called again util.read_out(6) # We can change authorization info if you have different key in other sector util.auth(rdr.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) #If you want to use methods from RFID itself, you can use this for authorization # This will authorize for block 1 of sector 2 -> block 9 # This is once more called only if it’s not already authorized for this block util.do_auth(util.block_addr(2, 1)) # Now we can do some “lower-level” stuff with block 9 rdr.write(9, [0x01, 0x23, 0x45, 0x67, 0x89, 0x98, 0x76, 0x54, 0x32, 0x10, 0x69, 0x27, 0x46, 0x66, 0x66, 0x64]) # We can rewrite specific bytes in block using this method. None means “don’t change this byte” # Note that this won’t do authorization, because we’ve already called do_auth for block 9 util.rewrite(9, [None, None, 0xAB, 0xCD, 0xEF]) # This will write S2B1: [0x01, 0x23, 0xAB, 0xCD, 0xEF, 0x98, 0x76……] because we’ve rewritten third, fourth and fifth byte util.read_out(9) # Let’s see what do we have in whole tag util.dump() # We must stop crypto util.deauth()
Setup Ondryaso

#!/usr/bin/env python

import os

import sys

from setuptools import setup, find_packages

from setuptools.command.test import test as TestCommand

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),

‘pirc522′)))

from pirc522 import __version__ # flake8: noqa

sys.path.pop(0)

setup(

name=’pi-rc522′,

packages=find_packages(),

include_package_data=True,

version=__version__,

description=’Raspberry Pi Python library for SPI RFID RC522 module.’,

long_description=’Raspberry Pi Python library for SPI RFID RC522 module.’,

classifiers=[

‘Development Status :: 4 – Beta’,

‘Intended Audience :: Developers’,

‘License :: OSI Approved :: MIT License’,

‘Operating System :: OS Independent’,

‘Topic :: Software Development’,

‘Programming Language :: Python :: 2’,

‘Programming Language :: Python :: 2.7’,

‘Programming Language :: Python :: 3’,

‘Programming Language :: Python :: 3.5′,

],

author=’ondryaso’,

author_email=’ondryaso@ondryaso.eu’,

url=’https://github.com/ondryaso/pi-rc522′,

license=’MIT’,

install_requires=[‘spidev’, ‘RPi.GPIO’],

)

ondryaso/pi-rc522
Watch32
Star287
Fork114

Code

Issues 28

Pull requests 4

Actions

Projects 0

Security

Insights
Browse files

Add support for interrupt driven tag detection

– bump version- adopt Read example- clean up imports

master

(#25)

LudwigKnuepfer committed on Jan 3, 2017

1 parent 3763e23 commit 709ca623f8e81c1b77dfa3474c5b2f00c71482dc

UnifiedSplit

Showing 4 changed files with 42 additions and 4 deletions.

2  examples/KeyChange.py

@@ -20,6 +20,8 @@ def end_read(signal,frame):

print(“Starting”)

while run:

rdr.wait_for_tag()

(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, [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF])

print(“\nWriting modified bytes”)

util.rewrite(4, [None, None, 0x69, 0x24, 0x40])

util.read_out(4)

“””

print(“\nWriting zero bytes”)

util.rewrite(2, [None, None, 0, 0, 0])

util.read_out(2)

print(“\nDeauthorizing”)

util.deauth()

“””

4  examples/Read.py

@@ -2,6 +2,7 @@

import signal

import time

import sys

from pirc522 import RFID

@@ -15,11 +16,14 @@ def end_read(signal,frame):

print(“\nCtrl+C captured, ending read.”)

run = False

rdr.cleanup()

sys.exit()

signal.signal(signal.SIGINT, end_read)

print(“Starting”)

while run:

rdr.wait_for_tag()

(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)
3  examples/UtilExample.py

@@ -11,6 +11,9 @@

util.debug = True

while True:

# Wait for tag

rdr.wait_for_tag()

# Request tag

(error, data) = rdr.request()

if not error:

print(“\nDetected”)

(error, uid) = rdr.anticoll()

if not error:

# Print UID

print(“Card read UID: “+str(uid[0])+”,”+str(uid[1])+”,”+str(uid[2])+”,”+str(uid[3]))

# Set tag as used in util. This will call RFID.select_tag(uid)

util.set_tag(uid)

# Save authorization info (key B) to util. It doesn’t call RFID.card_auth(), that’s called when needed

util.auth(rdr.auth_b, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])

# Print contents of block 4 in format “S1B0: [contents in decimal]”. RFID.card_auth() will be called now

util.read_out(4)

# Print it again – now auth won’t be called, because it doesn’t have to be

util.read_out(4)

# Print contents of different block – S1B2 – RFID.card_auth() will be called again

util.read_out(6)

# We can change authorization info if you have different key in other sector

util.auth(rdr.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])

# If you want to use methods from RFID itself, you can use this for authorization

37  pirc522/__init__.py

@@ -1,16 +1,16 @@

import time

import signal

import threading

import spidev

import RPi.GPIO as GPIO

__version__ = “2.0.0”

__version__ = “2.1.0”

class RFID(object):

pin_rst = 22

pin_ce = 0

pin_irq = 18

mode_idle = 0x00

mode_auth = 0x0E

mode_receive = 0x08

mode_transmit = 0x04

mode_transrec = 0x0C

mode_reset = 0x0F

mode_crc = 0x03

auth_a = 0x60

auth_b = 0x61

act_read = 0x30

act_write = 0xA0

act_increment = 0xC1

act_decrement = 0xC0

act_restore = 0xC2

act_transfer = 0xB0

act_reqidl = 0x26

act_reqall = 0x52

act_anticl = 0x93

act_select = 0x93

@@ -40,21 +40,30 @@

length = 16

authed = False

irq = threading.Event()

def __init__(self, bus=0, device=0, speed=1000000, pin_rst=22, pin_ce=0):

def __init__(self, bus=0, device=0, speed=1000000, pin_rst=22,

pin_ce=0, pin_irq=18):

self.pin_rst = pin_rst

self.pin_ce = pin_ce

self.pin_irq = pin_irq

self.spi = spidev.SpiDev()

self.spi.open(bus, device)

self.spi.max_speed_hz = speed

GPIO.setmode(GPIO.BOARD)

GPIO.setup(pin_rst, GPIO.OUT)

GPIO.setup(pin_irq, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.add_event_detect(pin_irq, GPIO.FALLING,

callback=self.irq_callback)

GPIO.output(pin_rst, 1)

if pin_ce != 0:

GPIO.setup(pin_ce, GPIO.OUT)

GPIO.output(pin_ce, 1)

self.init()

def init(self):

self.reset()

self.dev_write(0x2A, 0x8D)

self.dev_write(0x2B, 0x3E)

self.dev_write(0x2D, 30)

self.dev_write(0x2C, 0)

self.dev_write(0x15, 0x40)

self.dev_write(0x11, 0x3D)

self.set_antenna(True)

def spi_transfer(self, data):

if self.pin_ce != 0:

GPIO.output(self.pin_ce, 0)

r = self.spi.xfer2(data)

if self.pin_ce != 0:

GPIO.output(self.pin_ce, 1)

return r

def dev_write(self, address, value):

self.spi_transfer([(address << 1) & 0x7E, value])

def dev_read(self, address):

return self.spi_transfer([((address << 1) & 0x7E) | 0x80, 0])[1] def set_bitmask(self, address, mask): current = self.dev_read(address) self.dev_write(address, current | mask) def clear_bitmask(self, address, mask): current = self.dev_read(address) self.dev_write(address, current & (~mask)) def set_antenna(self, state): if state == True: current = self.dev_read(self.reg_tx_control) if ~(current & 0x03): self.set_bitmask(self.reg_tx_control, 0x03) else: self.clear_bitmask(self.reg_tx_control, 0x03) def card_write(self, command, data): back_data = [] back_length = 0 error = False irq = 0x00 irq_wait = 0x00 last_bits = None n = 0 if command == self.mode_auth: irq = 0x12 irq_wait = 0x10 if command == self.mode_transrec: irq = 0x77 irq_wait = 0x30 self.dev_write(0x02, irq | 0x80) self.clear_bitmask(0x04, 0x80) self.set_bitmask(0x0A, 0x80) self.dev_write(0x01, self.mode_idle) for i in range(len(data)): self.dev_write(0x09, data[i]) self.dev_write(0x01, command) if command == self.mode_transrec: self.set_bitmask(0x0D, 0x80) i = 2000 while True: n = self.dev_read(0x04) i -= 1 if ~((i != 0) and ~(n & 0x01) and ~(n & irq_wait)): break self.clear_bitmask(0x0D, 0x80) if i != 0: if (self.dev_read(0x06) & 0x1B) == 0x00: error = False if n & irq & 0x01: print(“E1”) error = True if command == self.mode_transrec: n = self.dev_read(0x0A) last_bits = self.dev_read(0x0C) & 0x07 if last_bits != 0: back_length = (n – 1) * 8 + last_bits else: back_length = n * 8 if n == 0: n = 1 if n > self.length:

n = self.length

for i in range(n):

back_data.append(self.dev_read(0x09))

else:

print(“E2”)

error = True

return (error, back_data, back_length)

def request(self, req_mode=0x26):

“””

Requests for tag.

Returns (False, None) if no tag is present, otherwise returns (True, tag type)

“””

error = True

back_bits = 0

self.dev_write(0x0D, 0x07)

(error, back_data, back_bits) = self.card_write(self.mode_transrec, [req_mode, ])

if error or (back_bits != 0x10):

return (True, None)

return (False, back_bits)

def anticoll(self):

“””

Anti-collision detection.

Returns tuple of (error state, tag ID).

“””

back_data = []

serial_number = []

serial_number_check = 0

self.dev_write(0x0D, 0x00)

serial_number.append(self.act_anticl)

serial_number.append(0x20)

(error, back_data, back_bits) = self.card_write(self.mode_transrec, serial_number)

if not error:

if len(back_data) == 5:

for i in range(4):

serial_number_check = serial_number_check ^ back_data[i]

if serial_number_check != back_data[4]:

error = True

else:

error = True

return (error, back_data)

def calculate_crc(self, data):

self.clear_bitmask(0x05, 0x04)

self.set_bitmask(0x0A, 0x80)

for i in range(len(data)):

self.dev_write(0x09, data[i])

self.dev_write(0x01, self.mode_crc)

i = 255

while True:

n = self.dev_read(0x05)

i -= 1

if not ((i != 0) and not (n & 0x04)):

break

ret_data = []

ret_data.append(self.dev_read(0x22))

ret_data.append(self.dev_read(0x21))

return ret_data

def select_tag(self, uid):

“””

Selects tag for further usage.

uid — list or tuple with four bytes tag ID

Returns error state.

“””

back_data = []

buf = []

buf.append(self.act_select)

buf.append(0x70)

for i in range(5):

buf.append(uid[i])

crc = self.calculate_crc(buf)

buf.append(crc[0])

buf.append(crc[1])

(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)

if (not error) and (back_length == 0x18):

return False

else:

return True

def card_auth(self, auth_mode, block_address, key, uid):

“””

Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.

auth_mode — RFID.auth_a or RFID.auth_b

key — list or tuple with six bytes key

uid — list or tuple with four bytes tag ID

Returns error state.

“””

buf = []

buf.append(auth_mode)

buf.append(block_address)

for i in range(len(key)):

buf.append(key[i])

for i in range(4):

buf.append(uid[i])

(error, back_data, back_length) = self.card_write(self.mode_auth, buf)

if not (self.dev_read(0x08) & 0x08) != 0:

error = True

if not error:

self.authed = True

return error

def stop_crypto(self):

“””Ends operations with Crypto1 usage.”””

self.clear_bitmask(0x08, 0x08)

self.authed = False

def halt(self):

“””Switch state to HALT”””

buf = []

buf.append(self.act_end)

buf.append(0)

crc = self.calculate_crc(buf)

self.clear_bitmask(0x08, 0x80)

self.card_write(self.mode_transrec, buf)

self.clear_bitmask(0x08, 0x08)

self.authed = False

def read(self, block_address):

“””

Reads data from block. You should be authenticated before calling read.

Returns tuple of (error state, read data).

“””

buf = []

buf.append(self.act_read)

buf.append(block_address)

crc = self.calculate_crc(buf)

buf.append(crc[0])

buf.append(crc[1])

(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)

if len(back_data) != 16:

error = True

return (error, back_data)

def write(self, block_address, data):

“””

Writes data to block. You should be authenticated before calling write.

Returns error state.

“””

buf = []

buf.append(self.act_write)

buf.append(block_address)

crc = self.calculate_crc(buf)

buf.append(crc[0])

buf.append(crc[1])

(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)

if not(back_length == 4) or not((back_data[0] & 0x0F) == 0x0A):

error = True

if not error:

buf_w = []

for i in range(16):

buf_w.append(data[i])

crc = self.calculate_crc(buf_w)

buf_w.append(crc[0])

buf_w.append(crc[1])

@@ -344,7 +353,27 @@

return error

def irq_callback(self, pin):

self.irq.set()

def wait_for_tag(self):

# enable IRQ on detect

self.init()

self.irq.clear()

self.dev_write(0x04, 0x00)

self.dev_write(0x02, 0xA0)

# wait for it

waiting = True

while waiting:

self.dev_write(0x09, 0x26)

self.dev_write(0x01, 0x0C)

self.dev_write(0x0D, 0x87)

waiting = not self.irq.wait(0.1)

self.irq.clear()

self.init()

def reset(self):

authed = False

self.dev_write(0x01, self.mode_reset)

def cleanup(self):

0 comments on commit 709ca62
Please sign in to comment.

1:55PM FRI. 4/10/2020
2:38pm Thu. 4/9/2020

MRFC522 Programming V0.8 – Mario Gomez’s read01.py

penzi link: https://penzu.com/p/e8830994

2:42PM THU. 4/9/2020
import RPi.GPIO as GPIO
import MFRC522

MIFAREReader = MFRC522.MFRC522()

# Welcome message
print “Welcome to the MFRC522 data read example”
print “Press Ctrl-C to stop.”

# This loop keeps checking for chips. If one is near it will get the UID and authenticate

while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print “Authentication error”

**Important notice:** This library has not being actively updated in almost four years.

It might not work as intended on more recent Raspberry Pi devices. You might want to
take a look to the open pull-requests and forks to see other implementations and bug-fixes.

## Requirements

This code requires you to have SPI-Py installed from the following repository:

https://github.com/lthiery/SPI-Py

MFRC522-python
==============
A small class to interface with the NFC reader Module MFRC522 on the Raspberry Pi.
This is a Python port of the example code for the NFC module MF522-AN.

**Important notice:** This library has not being actively updated in almost four years.
It might not work as intended on more recent Raspberry Pi devices. You might want to
take a look to the open pull-requests and forks to see other implementations and bug-fixes.

## Requirements

This code requires you to have SPI-Py installed from the following repository:

https://github.com/lthiery/SPI-Py

## Examples
This repository includes a couple of examples showing how to read, write, and dump data from a chip. They are thoroughly commented, and should be easy to understand.

## Pins
You can use [this](http://i.imgur.com/y7Fnvhq.png) image for reference.

| Name | Pin # | Pin name   |
|:——:|:——-:|:————:|
| SDA  | 24    | GPIO8      |
| SCK  | 23    | GPIO11     |
| MOSI | 19    | GPIO10     |
| MISO | 21    | GPIO9      |
| IRQ  | None  | None       |
| GND  | Any   | Any Ground |
| RST  | 22    | GPIO25     |
| 3.3V | 1     | 3V3        |

## Usage

Import the class by importing MFRC522 in the top of your script. For more info see the examples.

## License

This code and examples are licensed under the GNU Lesser General Public License 3.0.

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print “Welcome to the MFRC522 data read example”
print “Press Ctrl-C to stop.”

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print “Authentication error”

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
print “\n”

# Check if authenticated
if status == MIFAREReader.MI_OK:

# Variable for the data to write
data = []

# Fill the data with 0xFF
for x in range(0,16):
data.append(0xFF)

print “Sector 8 looked like this:”
# Read block 8
MIFAREReader.MFRC522_Read(8)
print “\n”

print “Sector 8 will now be filled with 0xFF:”
# Write the data
MIFAREReader.MFRC522_Write(8, data)
print “\n”

print “It now looks like this:”
# Check to see if it was written
MIFAREReader.MFRC522_Read(8)
print “\n”

data = []
# Fill the data with 0x00
for x in range(0,16):
data.append(0x00)

print “Now we fill it with 0x00:”
MIFAREReader.MFRC522_Write(8, data)
print “\n”

print “It is now empty:”
# Check to see if it was written
MIFAREReader.MFRC522_Read(8)
print “\n”

# Stop
MIFAREReader.MFRC522_StopCrypto1()

# Make sure to stop reading for cards
continue_reading = False
else:
print “Authentication error”

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Dump the data
MIFAREReader.MFRC522_DumpClassic1K(key, uid)

# Stop
MIFAREReader.MFRC522_StopCrypto1()

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#

import RPi.GPIO as GPIO
import spi
import signal
import time

class MFRC522:
NRSTPD = 22

MAX_LEN = 16

PCD_IDLE       = 0x00
PCD_AUTHENT    = 0x0E
PCD_RECEIVE    = 0x08
PCD_TRANSMIT   = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC    = 0x03

PICC_REQIDL    = 0x26
PICC_REQALL    = 0x52
PICC_ANTICOLL  = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ      = 0x30
PICC_WRITE     = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE   = 0xC2
PICC_TRANSFER  = 0xB0
PICC_HALT      = 0x50

MI_OK       = 0
MI_NOTAGERR = 1
MI_ERR      = 2

Reserved00     = 0x00
CommandReg     = 0x01
CommIEnReg     = 0x02
DivlEnReg      = 0x03
CommIrqReg     = 0x04
DivIrqReg      = 0x05
ErrorReg       = 0x06
Status1Reg     = 0x07
Status2Reg     = 0x08
FIFODataReg    = 0x09
FIFOLevelReg   = 0x0A
WaterLevelReg  = 0x0B
ControlReg     = 0x0C
BitFramingReg  = 0x0D
CollReg        = 0x0E
Reserved01     = 0x0F

Reserved10     = 0x10
ModeReg        = 0x11
TxModeReg      = 0x12
RxModeReg      = 0x13
TxControlReg   = 0x14
TxAutoReg      = 0x15
TxSelReg       = 0x16
RxSelReg       = 0x17
RxThresholdReg = 0x18
DemodReg       = 0x19
Reserved11     = 0x1A
Reserved12     = 0x1B
MifareReg      = 0x1C
Reserved13     = 0x1D
Reserved14     = 0x1E
SerialSpeedReg = 0x1F

Reserved20        = 0x20
CRCResultRegM     = 0x21
CRCResultRegL     = 0x22
Reserved21        = 0x23
ModWidthReg       = 0x24
Reserved22        = 0x25
RFCfgReg          = 0x26
GsNReg            = 0x27
CWGsPReg          = 0x28
ModGsPReg         = 0x29
TModeReg          = 0x2A
TPrescalerReg     = 0x2B
TReloadRegH       = 0x2C
TReloadRegL       = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F

Reserved30      = 0x30
TestSel1Reg     = 0x31
TestSel2Reg     = 0x32
TestPinEnReg    = 0x33
TestPinValueReg = 0x34
TestBusReg      = 0x35
AutoTestReg     = 0x36
VersionReg      = 0x37
AnalogTestReg   = 0x38
TestDAC1Reg     = 0x39
TestDAC2Reg     = 0x3A
TestADCReg      = 0x3B
Reserved31      = 0x3C
Reserved32      = 0x3D
Reserved33      = 0x3E
Reserved34      = 0x3F

serNum = []

def __init__(self, dev=’/dev/spidev0.0′, spd=1000000):
spi.openSPI(device=dev,speed=spd)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.NRSTPD, GPIO.OUT)
GPIO.output(self.NRSTPD, 1)
self.MFRC522_Init()

def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

def Write_MFRC522(self, addr, val):
spi.transfer(((addr<<1)&0x7E,val))

def Read_MFRC522(self, addr):
val = spi.transfer((((addr<<1)&0x7E) | 0x80,0))
return val[1]

def SetBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp | mask)

def ClearBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg);
self.Write_MFRC522(reg, tmp & (~mask))

def AntennaOn(self):
temp = self.Read_MFRC522(self.TxControlReg)
if(~(temp & 0x03)):
self.SetBitMask(self.TxControlReg, 0x03)

def AntennaOff(self):
self.ClearBitMask(self.TxControlReg, 0x03)

def MFRC522_ToCard(self,command,sendData):
backData = []
backLen = 0
status = self.MI_ERR
irqEn = 0x00
waitIRq = 0x00
lastBits = None
n = 0
i = 0

if command == self.PCD_AUTHENT:
irqEn = 0x12
waitIRq = 0x10
if command == self.PCD_TRANSCEIVE:
irqEn = 0x77
waitIRq = 0x30

self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
self.ClearBitMask(self.CommIrqReg, 0x80)
self.SetBitMask(self.FIFOLevelReg, 0x80)

self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);

while(i<len(sendData)):       self.Write_MFRC522(self.FIFODataReg, sendData[i])       i = i+1          self.Write_MFRC522(self.CommandReg, command)            if command == self.PCD_TRANSCEIVE:       self.SetBitMask(self.BitFramingReg, 0x80)          i = 2000     while True:       n = self.Read_MFRC522(self.CommIrqReg)       i = i – 1       if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):         break          self.ClearBitMask(self.BitFramingReg, 0x80)        if i != 0:       if (self.Read_MFRC522(self.ErrorReg) & 0x1B)==0x00:         status = self.MI_OK         if n & irqEn & 0x01:           status = self.MI_NOTAGERR                if command == self.PCD_TRANSCEIVE:           n = self.Read_MFRC522(self.FIFOLevelReg)           lastBits = self.Read_MFRC522(self.ControlReg) & 0x07           if lastBits != 0:             backLen = (n-1)*8 + lastBits           else:             backLen = n*8                      if n == 0:             n = 1           if n > self.MAX_LEN:
n = self.MAX_LEN

i = 0
while i<n:
backData.append(self.Read_MFRC522(self.FIFODataReg))
i = i + 1;
else:
status = self.MI_ERR

return (status,backData,backLen)

def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []

self.Write_MFRC522(self.BitFramingReg, 0x07)

TagType.append(reqMode);
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)

if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR

return (status,backBits)

def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0

serNum = []

self.Write_MFRC522(self.BitFramingReg, 0x00)

serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)

(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)

if(status == self.MI_OK):
i = 0
if len(backData)==5:
while i<4:
serNumCheck = serNumCheck ^ backData[i]
i = i + 1
if serNumCheck != backData[i]:
status = self.MI_ERR
else:
status = self.MI_ERR

return (status,backData)

def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80);
i = 0
while i<len(pIndata):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
i = i + 1
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i = i – 1
if not ((i != 0) and not (n&0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData

def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
i = 0
while i<5:
buf.append(serNum[i])
i = i + 1
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)

if (status == self.MI_OK) and (backLen == 0x18):
print “Size: ” + str(backData[0])
return    backData[0]
else:
return 0

def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []

# First byte should be the authMode (A or B)
buff.append(authMode)

# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)

# Now we need to append the authKey which usually is 6 bytes of 0xFF
i = 0
while(i < len(Sectorkey)):
buff.append(Sectorkey[i])
i = i + 1
i = 0

# Next we append the first 4 bytes of the UID
while(i < 4):
buff.append(serNum[i])
i = i +1

# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)

# Check if an error occurred
if not(status == self.MI_OK):
print “AUTH ERROR!!”
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
print “AUTH ERROR(status2reg & 0x08) != 0”

# Return the status
return status

def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)

def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not(status == self.MI_OK):
print “Error while reading!”
i = 0
if len(backData) == 16:
print “Sector “+str(blockAddr)+” “+str(backData)

def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR

print “%s backdata &0x0F == 0x0A %s” % (backLen, backData[0]&0x0F)
if status == self.MI_OK:
i = 0
buf = []
while i < 16:
buf.append(writeData[i])
i = i + 1
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
print “Error while writing”
if status == self.MI_OK:
print “Data written”

def MFRC522_DumpClassic1K(self, key, uid):
i = 0
while i < 64:
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
print “Authentication error”
i = i+1

def MFRC522_Init(self):
GPIO.output(self.NRSTPD, 1)

self.MFRC522_Reset();

self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)

self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

2:38PM THU. 4/9/2020

8:58PM THU. 4/2/2020
MRFC522 Programming V0.7 – read01.py

penzi link: https://penzu.com/p/df27d289

Read01.py tlfong01  2020apr01hkt2103

Description – Mario Gomez’s read.py simplified

import RPi.GPIO as GPIO
import MFRC522

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print “Welcome!”

while True:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print “Authentication error”

# End

8:58PM THU. 4/2/2020

6:59PM THU. 4/2/2020

MRFC522 Programming V0.6 – Mario Gomez MFRC522 Class

penzi link: https://penzu.com/p/dff77f0d

Contents

Readme

Requirements

Read.py

Write.py

Dump.py

MFRC522.py

MFRC522-python README

==============

A small class to interface with the NFC reader Module MFRC522 on the Raspberry Pi.
This is a Python port of the example code for the NFC module MF522-AN.

** Important notice: **

This library has not being actively updated in almost four years.
It might not work as intended on more recent Raspberry Pi devices. You might want to
take a look to the open pull-requests and forks to see other implementations and bug-fixes.

## Requirements

This code requires you to have SPI-Py installed from the following repository:

https://github.com/lthiery/SPI-Py

## Examples

This repository includes a couple of examples showing how to read, write, and dump data from a chip. They are thoroughly commented, and should be easy to understand.

## Pins

You can use [this](http://i.imgur.com/y7Fnvhq.png) image for reference.

| Name | Pin # | Pin name   |

|:——:|:——-:|:————:|

| SDA  | 24    | GPIO8      |
| SCK  | 23    | GPIO11     |
| MOSI | 19    | GPIO10     |
| MISO | 21    | GPIO9      |
| IRQ  | None  | None       |
| GND  | Any   | Any Ground |
| RST  | 22    | GPIO25     |
| 3.3V | 1     | 3V3        |

## Usage

Import the class by importing MFRC522 in the top of your script. For more info see the examples.

## License

This code and examples are licensed under the GNU Lesser General Public License 3.0.

Requirements

RPi.GPIO==0.6.3
-e git+https://github.com/lthiery/SPI-Py.git#egg=spi-pi

Read.py

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted

def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print “Welcome to the MFRC522 data read example”
print “Press Ctrl-C to stop.”

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print “Authentication error”

Write.py

#!/usr/bin/env python
# -*- coding: utf8 -*-
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted

def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
print “\n”

# Check if authenticated
if status == MIFAREReader.MI_OK:

# Variable for the data to write
data = []

# Fill the data with 0xFF
for x in range(0,16):
data.append(0xFF)

print “Sector 8 looked like this:”
# Read block 8
MIFAREReader.MFRC522_Read(8)
print “\n”

print “Sector 8 will now be filled with 0xFF:”
# Write the data
MIFAREReader.MFRC522_Write(8, data)
print “\n”

print “It now looks like this:”
# Check to see if it was written
MIFAREReader.MFRC522_Read(8)
print “\n”

data = []
# Fill the data with 0x00
for x in range(0,16):
data.append(0x00)

print “Now we fill it with 0x00:”
MIFAREReader.MFRC522_Write(8, data)
print “\n”

print “It is now empty:”
# Check to see if it was written
MIFAREReader.MFRC522_Read(8)
print “\n”

# Stop
MIFAREReader.MFRC522_StopCrypto1()

# Make sure to stop reading for cards
continue_reading = False
else:
print “Authentication error”

Dump.Py

#!/usr/bin/env python
# -*- coding: utf8 -*-
#

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted

def end_read(signal,frame):
global continue_reading
print “Ctrl+C captured, ending read.”
continue_reading = False
GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

# If a card is found
if status == MIFAREReader.MI_OK:
print “Card detected”

# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()

# If we have the UID, continue
if status == MIFAREReader.MI_OK:

# Print UID
print “Card read UID: %s,%s,%s,%s” % (uid[0], uid[1], uid[2], uid[3])

# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)

# Dump the data
MIFAREReader.MFRC522_DumpClassic1K(key, uid)

# Stop
MIFAREReader.MFRC522_StopCrypto1()

MFRC522.py

#!/usr/bin/env python
# -*- coding: utf8 -*-

#

import RPi.GPIO as GPIO
import spi
import signal
import time

class MFRC522:
NRSTPD = 22

MAX_LEN = 16

PCD_IDLE       = 0x00
PCD_AUTHENT    = 0x0E
PCD_RECEIVE    = 0x08
PCD_TRANSMIT   = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC    = 0x03

PICC_REQIDL    = 0x26
PICC_REQALL    = 0x52
PICC_ANTICOLL  = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ      = 0x30
PICC_WRITE     = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE   = 0xC2
PICC_TRANSFER  = 0xB0
PICC_HALT      = 0x50

MI_OK       = 0
MI_NOTAGERR = 1
MI_ERR      = 2

Reserved00     = 0x00
CommandReg     = 0x01
CommIEnReg     = 0x02
DivlEnReg      = 0x03
CommIrqReg     = 0x04
DivIrqReg      = 0x05
ErrorReg       = 0x06
Status1Reg     = 0x07
Status2Reg     = 0x08
FIFODataReg    = 0x09
FIFOLevelReg   = 0x0A
WaterLevelReg  = 0x0B
ControlReg     = 0x0C
BitFramingReg  = 0x0D
CollReg        = 0x0E
Reserved01     = 0x0F

Reserved10     = 0x10
ModeReg        = 0x11
TxModeReg      = 0x12
RxModeReg      = 0x13
TxControlReg   = 0x14
TxAutoReg      = 0x15
TxSelReg       = 0x16
RxSelReg       = 0x17
RxThresholdReg = 0x18
DemodReg       = 0x19
Reserved11     = 0x1A
Reserved12     = 0x1B
MifareReg      = 0x1C
Reserved13     = 0x1D
Reserved14     = 0x1E
SerialSpeedReg = 0x1F

Reserved20        = 0x20
CRCResultRegM     = 0x21
CRCResultRegL     = 0x22
Reserved21        = 0x23
ModWidthReg       = 0x24
Reserved22        = 0x25
RFCfgReg          = 0x26
GsNReg            = 0x27
CWGsPReg          = 0x28
ModGsPReg         = 0x29
TModeReg          = 0x2A
TPrescalerReg     = 0x2B
TReloadRegH       = 0x2C
TReloadRegL       = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F

Reserved30      = 0x30
TestSel1Reg     = 0x31
TestSel2Reg     = 0x32
TestPinEnReg    = 0x33
TestPinValueReg = 0x34
TestBusReg      = 0x35
AutoTestReg     = 0x36
VersionReg      = 0x37
AnalogTestReg   = 0x38
TestDAC1Reg     = 0x39
TestDAC2Reg     = 0x3A
TestADCReg      = 0x3B
Reserved31      = 0x3C
Reserved32      = 0x3D
Reserved33      = 0x3E
Reserved34      = 0x3F

serNum = []

def __init__(self, dev=’/dev/spidev0.0′, spd=1000000):
spi.openSPI(device=dev,speed=spd)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.NRSTPD, GPIO.OUT)
GPIO.output(self.NRSTPD, 1)
self.MFRC522_Init()

def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

def Write_MFRC522(self, addr, val):
spi.transfer(((addr<<1)&0x7E,val))

def Read_MFRC522(self, addr):
val = spi.transfer((((addr<<1)&0x7E) | 0x80,0))
return val[1]

def SetBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp | mask)

def ClearBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg);
self.Write_MFRC522(reg, tmp & (~mask))

def AntennaOn(self):
temp = self.Read_MFRC522(self.TxControlReg)
if(~(temp & 0x03)):
self.SetBitMask(self.TxControlReg, 0x03)

def AntennaOff(self):
self.ClearBitMask(self.TxControlReg, 0x03)

def MFRC522_ToCard(self,command,sendData):
backData = []
backLen = 0
status = self.MI_ERR
irqEn = 0x00
waitIRq = 0x00
lastBits = None
n = 0
i = 0

if command == self.PCD_AUTHENT:
irqEn = 0x12
waitIRq = 0x10
if command == self.PCD_TRANSCEIVE:
irqEn = 0x77
waitIRq = 0x30

self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
self.ClearBitMask(self.CommIrqReg, 0x80)
self.SetBitMask(self.FIFOLevelReg, 0x80)

self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);

while(i<len(sendData)):       self.Write_MFRC522(self.FIFODataReg, sendData[i])       i = i+1          self.Write_MFRC522(self.CommandReg, command)            if command == self.PCD_TRANSCEIVE:       self.SetBitMask(self.BitFramingReg, 0x80)          i = 2000     while True:       n = self.Read_MFRC522(self.CommIrqReg)       i = i – 1       if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):         break          self.ClearBitMask(self.BitFramingReg, 0x80)        if i != 0:       if (self.Read_MFRC522(self.ErrorReg) & 0x1B)==0x00:         status = self.MI_OK         if n & irqEn & 0x01:           status = self.MI_NOTAGERR                if command == self.PCD_TRANSCEIVE:           n = self.Read_MFRC522(self.FIFOLevelReg)           lastBits = self.Read_MFRC522(self.ControlReg) & 0x07           if lastBits != 0:             backLen = (n-1)*8 + lastBits           else:             backLen = n*8                      if n == 0:             n = 1           if n > self.MAX_LEN:
n = self.MAX_LEN

i = 0
while i<n:
backData.append(self.Read_MFRC522(self.FIFODataReg))
i = i + 1;
else:
status = self.MI_ERR

return (status,backData,backLen)

def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []

self.Write_MFRC522(self.BitFramingReg, 0x07)

TagType.append(reqMode);
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)

if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR

return (status,backBits)

def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0

serNum = []

self.Write_MFRC522(self.BitFramingReg, 0x00)

serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)

(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)

if(status == self.MI_OK):
i = 0
if len(backData)==5:
while i<4:
serNumCheck = serNumCheck ^ backData[i]
i = i + 1
if serNumCheck != backData[i]:
status = self.MI_ERR
else:
status = self.MI_ERR

return (status,backData)

def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80);
i = 0
while i<len(pIndata):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
i = i + 1
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i = i – 1
if not ((i != 0) and not (n&0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData

def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
i = 0
while i<5:
buf.append(serNum[i])
i = i + 1
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)

if (status == self.MI_OK) and (backLen == 0x18):
print “Size: ” + str(backData[0])
return    backData[0]
else:
return 0

def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []

# First byte should be the authMode (A or B)
buff.append(authMode)

# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)

# Now we need to append the authKey which usually is 6 bytes of 0xFF
i = 0
while(i < len(Sectorkey)):
buff.append(Sectorkey[i])
i = i + 1
i = 0

# Next we append the first 4 bytes of the UID
while(i < 4):
buff.append(serNum[i])
i = i +1

# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)

# Check if an error occurred
if not(status == self.MI_OK):
print “AUTH ERROR!!”
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
print “AUTH ERROR(status2reg & 0x08) != 0”

# Return the status
return status

def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)

def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not(status == self.MI_OK):
print “Error while reading!”
i = 0
if len(backData) == 16:
print “Sector “+str(blockAddr)+” “+str(backData)

def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR

print “%s backdata &0x0F == 0x0A %s” % (backLen, backData[0]&0x0F)
if status == self.MI_OK:
i = 0
buf = []
while i < 16:
buf.append(writeData[i])
i = i + 1
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
print “Error while writing”
if status == self.MI_OK:
print “Data written”

def MFRC522_DumpClassic1K(self, key, uid):
i = 0
while i < 64:
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
print “Authentication error”
i = i+1

def MFRC522_Init(self):
GPIO.output(self.NRSTPD, 1)

self.MFRC522_Reset();

self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)

self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

6:59PM THU. 4/2/2020

9:16pm Tue. 3/31/2020
MRFC522 Programming V0.5 Short Listing

https://penzu.com/p/585c2995

# simplemfrc52201.py – 2020mar3101 Short Listing
# Simon Monk

from . import MFRC522
import RPi.GPIO as GPIO

class SimpleMFRC522:

READER = None

KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]

def __init__(self):
self.READER = MFRC522()

def read(self):
return id, text

def read_id(self):
return id

def read_id_no_block(self):
return self.uid_to_num(uid)

def read_no_block(self):
return id, text_read

def write(self, text):
return id, text_in

def write_no_block(self, text):
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]

def uid_to_num(self, uid):
return n

# mfrc52201.py – 2020mar3101 Short Listing

# Mario Gomez 2014/2018

import RPi.GPIO as GPIO
import spidev
import signal
import time
import logging

class MFRC522:

def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1,                 debugLevel=’WARNING’):

self.spi = spidev.SpiDev()
self.spi.open(bus, device)
self.spi.max_speed_hz = spd

self.logger = logging.getLogger(‘mfrc522Logger’)
self.logger.addHandler(logging.StreamHandler())
level = logging.getLevelName(debugLevel)
self.logger.setLevel(level)

gpioMode = GPIO.getmode()

if gpioMode is None:
GPIO.setmode(pin_mode)
else:
pin_mode = gpioMode

if pin_rst == -1:
if pin_mode == 11:
pin_rst = 15
else:
pin_rst = 22

GPIO.setup(pin_rst, GPIO.OUT)
GPIO.output(pin_rst, 1)

self.MFRC522_Init()

def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

def Write_MFRC522(self, addr, val):
val = self.spi.xfer2([(addr << 1) & 0x7E, val])

def Read_MFRC522(self, addr):
val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])
return val[1]

def Close_MFRC522(self):

def SetBitMask(self, reg, mask):

def ClearBitMask(self, reg, mask):

def AntennaOn(self):

def AntennaOff(self):

def MFRC522_ToCard(self, command, sendData):

def MFRC522_Request(self, reqMode):

def MFRC522_Anticoll(self):

def CalulateCRC(self, pIndata):

def MFRC522_SelectTag(self, serNum):

def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):

def MFRC522_StopCrypto1(self):

def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not (status == self.MI_OK):
self.logger.error(“Error while reading!”)

if len(backData) == 16:
self.logger.debug(“Sector ” + str(blockAddr) + ” ” + str(backData))
return backData
else:
return None

def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR

self.logger.debug(“%s backdata &0x0F == 0x0A %s” % (backLen, backData[0] & 0x0F))
if status == self.MI_OK:
buf = []
for i in range(16):
buf.append(writeData[i])

crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
self.logger.error(“Error while writing”)
if status == self.MI_OK:
self.logger.debug(“Data written”)

def MFRC522_DumpClassic1K(self, key, uid):

def MFRC522_Init(self):
self.MFRC522_Reset()

self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)

self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

9:16pm Tue. 3/31/2020

5:25pm Tue. 3/31/2020
MRFC522 Programming V0.3

https://penzu.com/p/08d4fdf2

mfrc522 Reading Notes
# simplemfrc52201.py – 2020mar3101
# Simon Monk

from . import MFRC522
import RPi.GPIO as GPIO

class SimpleMFRC522:

READER = None

KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]

def __init__(self):
self.READER = MFRC522()

def read(self):
id, text = self.read_no_block()
while not id:
id, text = self.read_no_block()
return id, text

def read_id(self):
id = self.read_id_no_block()
while not id:
id = self.read_id_no_block()
return id

def read_id_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None
return self.uid_to_num(uid)

def read_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
data = []
text_read = ”
if status == self.READER.MI_OK:
for block_num in self.BLOCK_ADDRS:
block = self.READER.MFRC522_Read(block_num)
if block:
data += block
if data:
text_read = ”.join(chr(i) for i in data)
self.READER.MFRC522_StopCrypto1()
return id, text_read

def write(self, text):
id, text_in = self.write_no_block(text)
while not id:
id, text_in = self.write_no_block(text)
return id, text_in

def write_no_block(self, text):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
self.READER.MFRC522_Read(11)
if status == self.READER.MI_OK:
data = bytearray()
data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode(‘ascii’)))
i = 0
for block_num in self.BLOCK_ADDRS:
self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16])
i += 1
self.READER.MFRC522_StopCrypto1()
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]

def uid_to_num(self, uid):
n = 0
for i in range(0, 5):
n = n * 256 + uid[i]
return n

# ***************************************************************************
def main():
print(‘Begin simplemfrc52201(), …’)
print(‘End   simplemfrc52201().’)
return

if __name__ == ‘__main__’:
main()

#.END

# mfrc52201.py – 2020mar3101

# Mario Gomez 2014/2018

import RPi.GPIO as GPIO
import spidev
import signal
import time
import logging

class MFRC522:
MAX_LEN = 16

PCD_IDLE = 0x00
PCD_AUTHENT = 0x0E
PCD_RECEIVE = 0x08
PCD_TRANSMIT = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC = 0x03

PICC_REQIDL = 0x26
PICC_REQALL = 0x52
PICC_ANTICOLL = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ = 0x30
PICC_WRITE = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE = 0xC2
PICC_TRANSFER = 0xB0
PICC_HALT = 0x50

MI_OK = 0
MI_NOTAGERR = 1
MI_ERR = 2

Reserved00 = 0x00
CommandReg = 0x01
CommIEnReg = 0x02
DivlEnReg = 0x03
CommIrqReg = 0x04
DivIrqReg = 0x05
ErrorReg = 0x06
Status1Reg = 0x07
Status2Reg = 0x08
FIFODataReg = 0x09
FIFOLevelReg = 0x0A
WaterLevelReg = 0x0B
ControlReg = 0x0C
BitFramingReg = 0x0D
CollReg = 0x0E
Reserved01 = 0x0F

Reserved10 = 0x10
ModeReg = 0x11
TxModeReg = 0x12
RxModeReg = 0x13
TxControlReg = 0x14
TxAutoReg = 0x15
TxSelReg = 0x16
RxSelReg = 0x17
RxThresholdReg = 0x18
DemodReg = 0x19
Reserved11 = 0x1A
Reserved12 = 0x1B
MifareReg = 0x1C
Reserved13 = 0x1D
Reserved14 = 0x1E
SerialSpeedReg = 0x1F

Reserved20 = 0x20
CRCResultRegM = 0x21
CRCResultRegL = 0x22
Reserved21 = 0x23
ModWidthReg = 0x24
Reserved22 = 0x25
RFCfgReg = 0x26
GsNReg = 0x27
CWGsPReg = 0x28
ModGsPReg = 0x29
TModeReg = 0x2A
TPrescalerReg = 0x2B
TReloadRegH = 0x2C
TReloadRegL = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F

Reserved30 = 0x30
TestSel1Reg = 0x31
TestSel2Reg = 0x32
TestPinEnReg = 0x33
TestPinValueReg = 0x34
TestBusReg = 0x35
AutoTestReg = 0x36
VersionReg = 0x37
AnalogTestReg = 0x38
TestDAC1Reg = 0x39
TestDAC2Reg = 0x3A
TestADCReg = 0x3B
Reserved31 = 0x3C
Reserved32 = 0x3D
Reserved33 = 0x3E
Reserved34 = 0x3F

serNum = []

def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10,                 pin_rst=-1, debugLevel=’WARNING’):

self.spi = spidev.SpiDev()
self.spi.open(bus, device)
self.spi.max_speed_hz = spd

self.logger = logging.getLogger(‘mfrc522Logger’)
self.logger.addHandler(logging.StreamHandler())
level = logging.getLevelName(debugLevel)
self.logger.setLevel(level)

gpioMode = GPIO.getmode()

if gpioMode is None:
GPIO.setmode(pin_mode)
else:
pin_mode = gpioMode

if pin_rst == -1:
if pin_mode == 11:
pin_rst = 15
else:
pin_rst = 22

GPIO.setup(pin_rst, GPIO.OUT)
GPIO.output(pin_rst, 1)

self.MFRC522_Init()

def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

def Write_MFRC522(self, addr, val):
val = self.spi.xfer2([(addr << 1) & 0x7E, val])

def Read_MFRC522(self, addr):
val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])         return val[1]         def Close_MFRC522(self):         self.spi.close()         GPIO.cleanup()         def SetBitMask(self, reg, mask):         tmp = self.Read_MFRC522(reg)         self.Write_MFRC522(reg, tmp | mask)         def ClearBitMask(self, reg, mask):         tmp = self.Read_MFRC522(reg)         self.Write_MFRC522(reg, tmp & (~mask))         def AntennaOn(self):         temp = self.Read_MFRC522(self.TxControlReg)         if (~(temp & 0x03)):             self.SetBitMask(self.TxControlReg, 0x03)         def AntennaOff(self):         self.ClearBitMask(self.TxControlReg, 0x03)         def MFRC522_ToCard(self, command, sendData):         backData = []         backLen = 0         status = self.MI_ERR         irqEn = 0x00         waitIRq = 0x00         lastBits = None         n = 0         if command == self.PCD_AUTHENT:             irqEn = 0x12             waitIRq = 0x10         if command == self.PCD_TRANSCEIVE:             irqEn = 0x77             waitIRq = 0x30         self.Write_MFRC522(self.CommIEnReg, irqEn | 0x80)         self.ClearBitMask(self.CommIrqReg, 0x80)         self.SetBitMask(self.FIFOLevelReg, 0x80)         self.Write_MFRC522(self.CommandReg, self.PCD_IDLE)         for i in range(len(sendData)):             self.Write_MFRC522(self.FIFODataReg, sendData[i])         self.Write_MFRC522(self.CommandReg, command)         if command == self.PCD_TRANSCEIVE:             self.SetBitMask(self.BitFramingReg, 0x80)         i = 2000         while True:             n = self.Read_MFRC522(self.CommIrqReg)             i -= 1             if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):                 break         self.ClearBitMask(self.BitFramingReg, 0x80)         if i != 0:             if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00:                 status = self.MI_OK                 if n & irqEn & 0x01:                     status = self.MI_NOTAGERR                 if command == self.PCD_TRANSCEIVE:                     n = self.Read_MFRC522(self.FIFOLevelReg)                     lastBits = self.Read_MFRC522(self.ControlReg) & 0x07                     if lastBits != 0:                         backLen = (n – 1) * 8 + lastBits                     else:                         backLen = n * 8                     if n == 0:                         n = 1                     if n > self.MAX_LEN:
n = self.MAX_LEN

for i in range(n):
backData.append(self.Read_MFRC522(self.FIFODataReg))
else:
status = self.MI_ERR

return (status, backData, backLen)

def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []

self.Write_MFRC522(self.BitFramingReg, 0x07)

TagType.append(reqMode)
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)

if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR

return (status, backBits)

def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0

serNum = []

self.Write_MFRC522(self.BitFramingReg, 0x00)

serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)

(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum)

if (status == self.MI_OK):
i = 0
if len(backData) == 5:
for i in range(4):
serNumCheck = serNumCheck ^ backData[i]
if serNumCheck != backData[4]:
status = self.MI_ERR
else:
status = self.MI_ERR

return (status, backData)

def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80)

for i in range(len(pIndata)):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])

self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i -= 1
if not ((i != 0) and not (n & 0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData

def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)

for i in range(5):
buf.append(serNum[i])

pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)

if (status == self.MI_OK) and (backLen == 0x18):
self.logger.debug(“Size: ” + str(backData[0]))
return backData[0]
else:
return 0

def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []

# First byte should be the authMode (A or B)
buff.append(authMode)

# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)

# Now we need to append the authKey which usually is 6 bytes of 0xFF
for i in range(len(Sectorkey)):
buff.append(Sectorkey[i])

# Next we append the first 4 bytes of the UID
for i in range(4):
buff.append(serNum[i])

# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff)

# Check if an error occurred
if not (status == self.MI_OK):
self.logger.error(“AUTH ERROR!!”)
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
self.logger.error(“AUTH ERROR(status2reg & 0x08) != 0”)

# Return the status
return status

def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)

def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not (status == self.MI_OK):
self.logger.error(“Error while reading!”)

if len(backData) == 16:
self.logger.debug(“Sector ” + str(blockAddr) + ” ” + str(backData))
return backData
else:
return None

def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR

self.logger.debug(“%s backdata &0x0F == 0x0A %s” % (backLen, backData[0] & 0x0F))
if status == self.MI_OK:
buf = []
for i in range(16):
buf.append(writeData[i])

crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
self.logger.error(“Error while writing”)
if status == self.MI_OK:
self.logger.debug(“Data written”)

def MFRC522_DumpClassic1K(self, key, uid):
for i in range(64):
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
self.logger.error(“Authentication error”)

def MFRC522_Init(self):
self.MFRC522_Reset()

self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)

self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

# ***************************************************************************
def main():
print(‘Begin mfrc52201(), …’)
print(‘End   mfrc52201().’)
return

if __name__ == ‘__main__’:
main()

#.END

5:25pm Tue. 3/31/2020
3:12pm Tue. 3/31/2020
How to setup a Raspberry Pi RFID RC522 Chip – Gus PiMyLifeUp, 2017oct03 Updated Nov 17, 2019
https://pimylifeup.com/raspberry-pi-rfid-rc522/

# Read.py
#!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

try:
id, text = reader.read()
print(id)
print(text)
finally:
GPIO.cleanup()

# Write.py
#!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

try:
text = input(‘New data:’)
print(“Now place your tag to write”)
reader.write(text)
print(“Written”)
finally:
GPIO.cleanup()

How to set up a Raspberry Pi RFID RC522 Reader and record data on IOTA – Roberto Rey 2019jan12
View at Medium.com

# Read.py

#!/usr/bin/env python
import RPi.GPIO as GPIO
import sys
sys.path.append(‘/home/pi/MFRC522-python’)
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()
print(“Hold a tag near the reader”)
try:
id, text = reader.read()
print(id)
print(text)

finally:
GPIO.cleanup()

Writing Data onto a RFID Tag Roberto Rey Roberto Rey Follow Jan 27, 2019
View at Medium.com

# Write.py

#!/usr/bin/env python

import RPi.GPIO as GPIO
import sys

sys.path.append(‘/home/pi/MFRC522-python’)
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
try:
while True:
text = raw_input(‘Your Name: ‘)
print(“Now place tag next to the scanner to write”)
id, text = reader.write(text)
print(“recorded”)
print(id)
print(text)
break

finally:
GPIO.cleanup()

pimylifeup/MFRC522-python – death-droid 2029apr02
https://github.com/pimylifeup/MFRC522-python

# Read.py
from time import sleep
import sys
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()

try:
while True:
print(“Hold a tag near the reader”)
id, text = reader.read()
print(“ID: %s\nText: %s” % (id,text))
sleep(5)
except KeyboardInterrupt:
GPIO.cleanup()
raise

pimylifeup/MFRC522-python
https://github.com/pimylifeup/MFRC522-python/blob/master/mfrc522/SimpleMFRC522.py
death-droid Improve compataibility with Python 3 – 741e9d9 on Mar 26, 2019

https://github.com/pimylifeup/MFRC522-python
death-droid Update setup.py Latest commit 970e903 on Apr 2, 2019

# Read.py

from time import sleep
import sys
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()

try:
while True:
print(“Hold a tag near the reader”)
id, text = reader.read()
print(“ID: %s\nText: %s” % (id,text))
sleep(5)
except KeyboardInterrupt:
GPIO.cleanup()
raise

.END

3:12pm Tue. 3/31/2020

5:02pm Mon. 3/30/2020

MFRC522 Program Listing

https://penzu.com/p/08d4fdf2

# mfrc52201.py  tlfong01  2020mar3001hkt1646

#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#    Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
#    This file is part of MFRC522-Python
#    MFRC522-Python is a simple Python implementation for
#    the MFRC522 NFC Card Reader for the Raspberry Pi.
#
#    MFRC522-Python is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    MFRC522-Python is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with MFRC522-Python.  If not, see <http://www.gnu.org/licenses/&gt;.
#
import RPi.GPIO as GPIO
import spidev
import signal
import time
import logging

class MFRC522:
MAX_LEN = 16

PCD_IDLE = 0x00
PCD_AUTHENT = 0x0E
PCD_RECEIVE = 0x08
PCD_TRANSMIT = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC = 0x03

PICC_REQIDL = 0x26
PICC_REQALL = 0x52
PICC_ANTICOLL = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ = 0x30
PICC_WRITE = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE = 0xC2
PICC_TRANSFER = 0xB0
PICC_HALT = 0x50

MI_OK = 0
MI_NOTAGERR = 1
MI_ERR = 2

Reserved00 = 0x00
CommandReg = 0x01
CommIEnReg = 0x02
DivlEnReg = 0x03
CommIrqReg = 0x04
DivIrqReg = 0x05
ErrorReg = 0x06
Status1Reg = 0x07
Status2Reg = 0x08
FIFODataReg = 0x09
FIFOLevelReg = 0x0A
WaterLevelReg = 0x0B
ControlReg = 0x0C
BitFramingReg = 0x0D
CollReg = 0x0E
Reserved01 = 0x0F

Reserved10 = 0x10
ModeReg = 0x11
TxModeReg = 0x12
RxModeReg = 0x13
TxControlReg = 0x14
TxAutoReg = 0x15
TxSelReg = 0x16
RxSelReg = 0x17
RxThresholdReg = 0x18
DemodReg = 0x19
Reserved11 = 0x1A
Reserved12 = 0x1B
MifareReg = 0x1C
Reserved13 = 0x1D
Reserved14 = 0x1E
SerialSpeedReg = 0x1F

Reserved20 = 0x20
CRCResultRegM = 0x21
CRCResultRegL = 0x22
Reserved21 = 0x23
ModWidthReg = 0x24
Reserved22 = 0x25
RFCfgReg = 0x26
GsNReg = 0x27
CWGsPReg = 0x28
ModGsPReg = 0x29
TModeReg = 0x2A
TPrescalerReg = 0x2B
TReloadRegH = 0x2C
TReloadRegL = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F

Reserved30 = 0x30
TestSel1Reg = 0x31
TestSel2Reg = 0x32
TestPinEnReg = 0x33
TestPinValueReg = 0x34
TestBusReg = 0x35
AutoTestReg = 0x36
VersionReg = 0x37
AnalogTestReg = 0x38
TestDAC1Reg = 0x39
TestDAC2Reg = 0x3A
TestADCReg = 0x3B
Reserved31 = 0x3C
Reserved32 = 0x3D
Reserved33 = 0x3E
Reserved34 = 0x3F

serNum = []

def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1,             debugLevel=’WARNING’):
self.spi = spidev.SpiDev()
self.spi.open(bus, device)
self.spi.max_speed_hz = spd

self.logger = logging.getLogger(‘mfrc522Logger’)
self.logger.addHandler(logging.StreamHandler())
level = logging.getLevelName(debugLevel)
self.logger.setLevel(level)

gpioMode = GPIO.getmode()

if gpioMode is None:
GPIO.setmode(pin_mode)
else:
pin_mode = gpioMode

if pin_rst == -1:
if pin_mode == 11:
pin_rst = 15
else:
pin_rst = 22

GPIO.setup(pin_rst, GPIO.OUT)
GPIO.output(pin_rst, 1)
self.MFRC522_Init()

def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

def Write_MFRC522(self, addr, val):
val = self.spi.xfer2([(addr << 1) & 0x7E, val])

def Read_MFRC522(self, addr):
val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])         return val[1]     def Close_MFRC522(self):         self.spi.close()         GPIO.cleanup()     def SetBitMask(self, reg, mask):         tmp = self.Read_MFRC522(reg)         self.Write_MFRC522(reg, tmp | mask)     def ClearBitMask(self, reg, mask):         tmp = self.Read_MFRC522(reg)         self.Write_MFRC522(reg, tmp & (~mask))     def AntennaOn(self):         temp = self.Read_MFRC522(self.TxControlReg)         if (~(temp & 0x03)):             self.SetBitMask(self.TxControlReg, 0x03)     def AntennaOff(self):         self.ClearBitMask(self.TxControlReg, 0x03)     def MFRC522_ToCard(self, command, sendData):         backData = []         backLen = 0         status = self.MI_ERR         irqEn = 0x00         waitIRq = 0x00         lastBits = None         n = 0         if command == self.PCD_AUTHENT:             irqEn = 0x12             waitIRq = 0x10         if command == self.PCD_TRANSCEIVE:             irqEn = 0x77             waitIRq = 0x30         self.Write_MFRC522(self.CommIEnReg, irqEn | 0x80)         self.ClearBitMask(self.CommIrqReg, 0x80)         self.SetBitMask(self.FIFOLevelReg, 0x80)         self.Write_MFRC522(self.CommandReg, self.PCD_IDLE)         for i in range(len(sendData)):             self.Write_MFRC522(self.FIFODataReg, sendData[i])         self.Write_MFRC522(self.CommandReg, command)         if command == self.PCD_TRANSCEIVE:             self.SetBitMask(self.BitFramingReg, 0x80)         i = 2000         while True:             n = self.Read_MFRC522(self.CommIrqReg)             i -= 1             if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):                 break         self.ClearBitMask(self.BitFramingReg, 0x80)         if i != 0:             if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00:                 status = self.MI_OK                 if n & irqEn & 0x01:                     status = self.MI_NOTAGERR                 if command == self.PCD_TRANSCEIVE:                     n = self.Read_MFRC522(self.FIFOLevelReg)                     lastBits = self.Read_MFRC522(self.ControlReg) & 0x07                     if lastBits != 0:                         backLen = (n – 1) * 8 + lastBits                     else:                         backLen = n * 8                     if n == 0:                         n = 1                     if n > self.MAX_LEN:
n = self.MAX_LEN

for i in range(n):
backData.append(self.Read_MFRC522(self.FIFODataReg))
else:
status = self.MI_ERR

return (status, backData, backLen)

def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []

self.Write_MFRC522(self.BitFramingReg, 0x07)

TagType.append(reqMode)
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)

if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR

return (status, backBits)

def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0

serNum = []

self.Write_MFRC522(self.BitFramingReg, 0x00)

serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)

(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum)

if (status == self.MI_OK):
i = 0
if len(backData) == 5:
for i in range(4):
serNumCheck = serNumCheck ^ backData[i]
if serNumCheck != backData[4]:
status = self.MI_ERR
else:
status = self.MI_ERR

return (status, backData)

def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80)

for i in range(len(pIndata)):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])

self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i -= 1
if not ((i != 0) and not (n & 0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData

def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)

for i in range(5):
buf.append(serNum[i])

pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)

if (status == self.MI_OK) and (backLen == 0x18):
self.logger.debug(“Size: ” + str(backData[0]))
return backData[0]
else:
return 0

def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []

# First byte should be the authMode (A or B)
buff.append(authMode)

# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)

# Now we need to append the authKey which usually is 6 bytes of 0xFF
for i in range(len(Sectorkey)):
buff.append(Sectorkey[i])

# Next we append the first 4 bytes of the UID
for i in range(4):
buff.append(serNum[i])

# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff)

# Check if an error occurred
if not (status == self.MI_OK):
self.logger.error(“AUTH ERROR!!”)
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
self.logger.error(“AUTH ERROR(status2reg & 0x08) != 0”)

# Return the status
return status

def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)

def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not (status == self.MI_OK):
self.logger.error(“Error while reading!”)

if len(backData) == 16:
self.logger.debug(“Sector ” + str(blockAddr) + ” ” + str(backData))
return backData
else:
return None

def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR

self.logger.debug(“%s backdata &0x0F == 0x0A %s” % (backLen, backData[0] & 0x0F))
if status == self.MI_OK:
buf = []
for i in range(16):
buf.append(writeData[i])

crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) ==                 0x0A):
self.logger.error(“Error while writing”)
if status == self.MI_OK:
self.logger.debug(“Data written”)

def MFRC522_DumpClassic1K(self, key, uid):
for i in range(64):
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
self.logger.error(“Authentication error”)

def MFRC522_Init(self):
self.MFRC522_Reset()

self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)

self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

# simple_mrfc522_01.py  tlfong01  2020mar3001

# Code by Simon Monk https://github.com/simonmonk/

from . import MFRC522
import RPi.GPIO as GPIO

class SimpleMFRC522:

READER = None

KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]

def __init__(self):
self.READER = MFRC522()

def read(self):
id, text = self.read_no_block()
while not id:
id, text = self.read_no_block()
return id, text

def read_id(self):
id = self.read_id_no_block()
while not id:
id = self.read_id_no_block()
return id

def read_id_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None
return self.uid_to_num(uid)

def read_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
data = []
text_read = ”
if status == self.READER.MI_OK:
for block_num in self.BLOCK_ADDRS:
block = self.READER.MFRC522_Read(block_num)
if block:
data += block
if data:
text_read = ”.join(chr(i) for i in data)
self.READER.MFRC522_StopCrypto1()
return id, text_read

def write(self, text):
id, text_in = self.write_no_block(text)
while not id:
id, text_in = self.write_no_block(text)
return id, text_in

def write_no_block(self, text):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
self.READER.MFRC522_Read(11)
if status == self.READER.MI_OK:
data = bytearray()
data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode(‘ascii’)))
i = 0
for block_num in self.BLOCK_ADDRS:
self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16])
i += 1
self.READER.MFRC522_StopCrypto1()
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]

def uid_to_num(self, uid):
n = 0
for i in range(0, 5):
n = n * 256 + uid[i]
return n

mfrc522_init01.py

from .MFRC522 import MFRC522
from .SimpleMFRC522 import SimpleMFRC522

name = “mfrc522″

5:02pm Mon. 3/30/2020

12:30pm Wed. 3/4/2020

SPI Testing Notes V4.0

penzu link: https://penzu.com/p/6d5601f6

8:56pm Wed. 10/30/2019

SPI LoopBack and Repeat send byte program Rpi3B+ 2019apr07

penzu link: https://penzu.com/p/8b11a6b1

https://raspberrypi.stackexchange.com/questions/97869/how-to-check-if-spi-is-enabled-and-functional-on-raspi-3b

I have been using raspi-config always found it working. Sometimes my modules are not working. So I usually use two little test programs to check. One program is to repeatedly send out bytes and use a scope to make sure the waveform looks OK. The other test program is a loop back test. I connect MOSI to MISO, send a byte and read back.

You might like to try my test program. It is plug and play, no libraries are required. – tlfong01

I have tested my program with IDLE python. To run in terminal mode:

Don’t forget to run with sudo – otherwise the loopback test recvByte returns 0x0. – @glenneroo 2019 Apr 24 at 20:49

# spi_test05 tlfong01 2019apr07hkt2043 ***

# Computer = Rpi3B+
# Linux    = $ hostnamectl = raspberrypi Raspbian GNU/Linux 9 (stretch) Linux 4.14.34-v7+ arm
# Python   = >>> sys.version = 3.5.3 Jan 19 2017

# Test 1   – repeatSendByte() – SPI port repeatedly send out single bytes.
# Function – Repeat many times sending a byte, pause after each byte.

# Test 2   – loopBackTest()   – SPI port send and receive one byte.
# Function – Send one byte to MSOI and read it back from MISO.
# Setup    – Connet MOSI pin to MISO pin to form a loop.

from   time import sleep
import spidev

spiPort0 = spidev.SpiDev()
spiPort0.open(0,0)
spiPort0.max_speed_hz = 100000

def spiSendRecvOneByte(spiPort, sendByte):
sendByteArray = [sendByte]
recvByteArray = spiPort.xfer(sendByteArray)
return recvByteArray

def repeatSendOneByte(spiPort, sendByte, pauseTimeBetweenBytes, repeatCount):
print(‘\nBegin repeatSendByte(),….’)
for i in range(repeatCount):
spiSendRecvOneByte(spiPort, sendByte)
sleep(pauseTimeBetweenBytes)
print(‘End   repeatSendByte().’)
return

def loopBackOneByte(spiPort, sendByte):
recvByteArray     = spiSendRecvOneByte(spiPort, sendByte)
recvByte          = recvByteArray[0]

print(‘\nBegin testLoopbackOneByte(),….’)
#print(”)
print(‘      sendByte  = ‘, hex(sendByte))
print(‘      recvByte  = ‘, hex(recvByte))
#print(”)
print(‘End   testLoopbackOneByte(),….’)
return

def testRepeatSendOneByte():
repeatSendOneByte(spiPort0, 0x5b, 0.0001, 20000000)
return

def testLoopbackOneByte():
loopBackOneByte(spiPort0, 0x5b)
return

# testRepeatSendOneByte()
testLoopbackOneByte()

”’ Smple output tlfong 01 2019apr07hkt2047
Begin testLoopbackOneByte(),….
sendByte  =  0x5b
recvByte  =  0x5b
End   testLoopbackOneByte(),….
”’

# *** End ***

Appendices

Appendix A – SPI Pinouts

share edit delete flag edited May 30 at 6:20 answered 2019 Apr 24 at 14:05

tlfong01

.END

9:00pm Wed. 10/30/2019

12:30pm Wed. 3/4/2020

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.