Giter VIP home page Giter VIP logo

mfrc522-python's People

Contributors

death-droid avatar graingert avatar niels-post avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mfrc522-python's Issues

AUTH ERROR

When I'm trying to read, I am getting an error saying:
"AUTH ERROR!!
AUTH ERROR(status2reg & 0x08) != 0"
Afterwards the UID is printed out correctly, but the Text is empty.
If I write onto a completly new card, and read afterwards, it works fine, but if I'm write onto the card with an mobile app, it's not possible to read.
Is there some kind of Authentication going on and can I somehow bypass it?

Reader not reading

Hi all,

this is probably a really basic question -- my apologies --, but I'm really frustrated and have no idea how to continue.

I'm trying to connect an AZ-Delivery RC522 reader to a Raspberry Pi (have tried both 3A+ and Zero 2 W), but the reader just won't read the RFID chip and card that came in the package.

I am using the wiring with IRQ to GPIO24, and have double-checked that all wires are connected correctly.

I am using the current version of Raspberry Pi OS, and have enabled SPI in raspi-config. The kernel modules are loading:

$ uname -a
Linux raspberrypi 5.10.17-v7+ #1414 SMP Fri Apr 30 13:18:35 BST 2021 armv7l GNU/Linux

$ lsmod|grep spi
spidev                 20480  0
spi_bcm2835            20480  0

However, when I run the test program from the README, it hangs at the reader.read statement, no matter how long I hold the chip or card to the reader.

Any idea what I could try to make this work? Or how I would even debug this?

How to cancel read or write in large application / thread

Hey there, I wanted to use this framework in a larger application, where some actions trigger a read or write, which are in a side thread of the program. The issue is that the read or write locks the thread and can not be canceled because the read or write action may not be executed. When doing a read or write action again after not finishing the old one, it's no longer possible to read / write. A message "Segmentation Error" is shown when exiting the program.

Basic example code can be found below, full code can be found here. In summary, a thread is spun up which should run a loop of reading or writing. The cancel function breaks the loop. This does not work tough, because .read() and .write() will lock until the read or write did happen. Even if the component got cleaned up by the garbage collector, I assume some lower level read/write code is still running, and if using one of the both functions again will cause the described error. If I always read or write a card/chip after using the function (which is not always the case because it's optional) the program runs as intended.
Is there any option or possibility to cancel the read progress over the SimpleMFRC522, so I can implement an optional read into my program?

from mfrc522 import SimpleMFRC522 

class BasicMFRC522():
    def __init__(self) -> None:
        self.rfid = SimpleMFRC522()

    def read_card(self) -> Union[str, None]:
        _, text = self.rfid.read()
        if text is not None:
            text = text.strip()
        return text

    def write_card(self, text: str) -> bool:
        _id, _ = self.rfid.write(text)
        return _id is not None


class RFIDReader:
    def __init__(self) -> None:
        self.is_active = False
        self.rfid = BasicMFRC522()

    def read_rfid(self, side_effect: Callable[[str], None]):
        """Start the rfid reader, calls an side effect with the read value"""
        if self.is_active:
            return
        self.is_active = True
        rfid_thread = Thread(target=self._read_thread, args=(side_effect,), daemon=True)
        rfid_thread.start()

    def _read_thread(self, side_effect: Callable[[str], None]):
        """Execute the reading until reads a value or got canceled"""
        text = None
        while self.is_active:
            text = self.rfid.read_card()
            if text is not None:
                side_effect(text)
                break
            time.sleep(0.5)
        self.is_active = False

    def write_rfid(self, value: str, side_effect: Optional[Callable[[str], None]] = None):
        """Writes the value to the RFID"""
        if self.is_active:
            return
        self.is_active = True
        rfid_thread = Thread(target=self._write_thread, args=(value, side_effect,), daemon=True)
        rfid_thread.start()

    def _write_thread(self, text: str, side_effect: Optional[Callable[[str], None]] = None):
        """Executes the writing until successful or canceled"""
        while self.is_active:
            success = self.rfid.write_card(text)
            if success:
                if side_effect:
                    side_effect(text)
                break
            time.sleep(0.1)
        self.is_active = False

    def cancel_reading(self):
        """Cancels the reading loop"""
        self.is_active = False

Thanks for the time.

Update: After some more diving into the source code and talking to a friend, I think read_no_block and write_no_block instead of the read and write function should do the general job? Is there anything to look out for or do in addition when interrupting the read/write?

Different ID for MFRC522 and USB Reade

Hello all,
I used on a Pi the MFRC522 module with the SimpleMFRC522 library.
I read there the same RFID tag I get the number: 962106709424

With a USB reader (YARONGTECH) I get the number: 1426522848

Is there another conversion in the library? E.g. from a HEX value to a natural number?

How can I make both devices output the same?

Thank you

AttributeError: 'module' object has no attribute 'getmode'

Traceback (most recent call last):
File "read.py", line 6, in
reader = SimpleMFRC522()
File "/usr/local/lib/python2.7/dist-packages/mfrc522/SimpleMFRC522.py", line 14, in init
self.READER = MFRC522()
File "/usr/local/lib/python2.7/dist-packages/mfrc522/MFRC522.py", line 138, in init
gpioMode = GPIO.getmode()
AttributeError: 'module' object has no attribute 'getmode'

MRC522 and Max7219 simultaneously

More of a question than a specific issue which I am hoping you can help with.

I am trying to run both an RC522 and MAX7219 (8x8 segment array) both of which use SPI.
In theory I should be able to get both to work however both libraries use PIN24. (SPI0)
Is there a change that I can make to the MFRC library so that I can get both to work? In theory I should be able to use SPI1 (Pin 26) for the reader but then the reader does not work.

I am running Raspian Buster on a few different PI's to try to get this working. (Pi3, Pi Zero etc.)

Below is a short sample of what I am trying to run:
The text runs across the matrix fine, but then fills with random flashing dots and the RFID reader does not read anything.

from luma.core.interface.serial import spi, noop
from luma.core.render import canvas
from luma.core.virtual import viewport
from luma.core.legacy import text, show_message
from luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT, SINCLAIR_FONT, LCD_FONT

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

create matrix device

serial = spi(port=0, device=0, gpio=noop())
device = max7219(serial, cascaded=4, block_orientation=-90)
print("Created device")

show_message(device, "test", fill="white", font=proportional(CP437_FONT), scroll_delay=0.1)

try:
print("Put RFID on Pad")
id, text = reader.read()
print(id)
print(text)
finally:
GPIO.cleanup()

No module named MFRC522

Hello,

i try to install the MFRC522 Modull.

I have following the instruction from your Link https://pimylifeup.com/raspberry-pi-rfid-rc522/

but i become this error message: Traceback (most recent call last):
File "read_mfrc522.py", line 6, in
reader = SimpleMFRC522()
File "/usr/local/lib/python3.5/dist-packages/mfrc522-0.0.3-py3.5.egg/mfrc522/SimpleMFRC522.py", line 14, in init
AttributeError: module 'MFRC522' has no attribute 'MFRC522'

Wont work

I am trying to use this and have installed as it says so but I get an error when importing it

MFRC522 goes to sleep after hours without use

I developed a simple while true python script to read tags. It works fine but I noticed that after a few hours without using MFRC522 it goes to sleep.

Do you how to prevent this behaviour? Thanks in advance.

Regards.

read rfid

I want to read the rfid when I touch the sensor with the card.(It should return the id when I placed the card on sensor without removing it)
It reads when I remove it.
is it possible?

async function for reading rfid tags

As the title stated, I would like to know if someone tried asyncio to make async read and write, but specially read because I am trying to run several task at the same time but the rfid is not working properly and stuck the list of tasks. Other tasks freeze waiting for the rfid to return output.

High CPU usage on idle state

while True:
n = self.Read_MFRC522(self.CommIrqReg)
i -= 1
if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):
break

so CPU usage is really high, about 105% on idle state, the raspberry shutdown after a while and we have to restart the code again.

I tracked the problem the line 216 in MFRC522, I've added a simple sleep of 10 milliseconds and it seemed to lower the CPU usage a bit (about 45%); it still cause an issue and the reader stops randomly.

for the record, I didn't hook up the IRQ pin (i was following a tutorial that referred this code and they didn't hook it up), could this be the case? I could test since I've run out of pins in my IoT device.

System hang

Hi
I have a Raspberry Pi Zero W, kernel 5.10. I tried to use this library to read and write cards, but after running reader = SimpleMFRC522(), the Raspberry becomes unresponsive and I can't do anything.
Thanks in advance

Bad Code at mfrc522/MFRC522.py#L179

The code on MFRC522.py#L179 is as follows:

if (~(temp & 0x03)):

Let's take a look at how this code would actually run:

>>> if (~(0x00 & 0x03)): print('True')
True

Okay, so it looks fine so far. Lets try something else:

>>> if (~(0x03 & 0x03)): print('True')
True

Well that is not what was supposed to happen.

The line should actually be written as:

if ((temp & 0x3) != 0x3):

Status 2 with MFRC522_Request

Hi everyone,

I'm trying to run the SimpleMFRC522 on RPi 4B.
When I get the tag close to the near nothing happens. I have the power led on and wiring seems fine.

Trying to explore the code a bit, realized that calling READER.MFRC522_Request() returns status 2.

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

checker = SimpleMFRC522()
(status, TagType) = checker.READER.MFRC522_Request(checker.READER.PICC_REQIDL)
print(status)

GPIO.cleanup()

Result is:

2


------------------
(program exited with code: 0)
Press return to continue

So, something is starting wrong already...
any ideas?

Thanks,
André

Closing the SPI and GPIO

Hi

From the "MFRC522.py"-file I can see the "Close_MFRC522"-method.
Could you extend your example on how to call this method.

When I use your !!VERY GOOD!! files in my project I am unable to call this method. I would like to use this method in order to "nicely" close the SPI and GPIO.

PS: It is not an issue, it is rather a question on how to this.

Kind Regards
Olivier

Issue with Raspberry Pi 5

When I Tried to run SimpleMFRC522() function I get the following error on Pi 5.
raceback (most recent call last):
File "/home/pi/Documents/rfid_test/efid_read.py", line 4, in <module>
reader = SimpleMFRC522()
File "/home/pi/.local/lib/python3.7/site-packages/mfrc522/SimpleMFRC522.py", line 14, in __init__
self.READER = MFRC522()
File "/home/pi/.local/lib/python3.7/site-packages/mfrc522/MFRC522.py", line 151, in __init__
GPIO.setup(pin_rst, GPIO.OUT)
RuntimeError: Cannot determine SOC peripheral base address

Needs a way to adjust gain

There doesn't seem to be a way to adjust the receiver gain when using this library... At least not a way I can find.

Unicode/8-bit Error

I've set up a RC522 Card on my pi using this, and hacked together the Read.py and Write.py scripts into a Clone.py script:

#!usr/bin/env python

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

try:
    print("Scan Card Now")
    id, text = reader.read()
    print("Current ID:")
    print(id)
    print("Place Card for Write, Then Press ENTER")
    input("")
    reader.write(text)
    print("Write Complete")

Which works just fine when testing on blank cards.
However, when I tried to clone an old hotel keycard I get:

Traceback (most recent call last):
  File "clone.py, line 16 in <module>
    reader.write(text)
  File "/usr/local/lib/python3.7/dist-packages/mfrc522/SimpleMFRC522.py", line 60 in write
    id, text_in = self.write_no_block(text)
  File "/usr/local/lib/python3.7/dist-packages/mfrc522/SimpleMFRC522.py", line 78, in write_no_block
    data.extended(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii')))
UnicodeEncodeError: 'ascii' codec cant encode characters in position 1-2: ordinal not in range(128)

What can I do to fix this?

Impossible to install the Library on Thonny

Hello everyone, I'm pretty new to this and have close to no knwoledge in Installing Libraries.
When I try to install this library on Thonny, it says that it requires Visual Studio (that I installed, as well as Visual Studio Build Tools 2022).
Now it gets me this error:
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.32.31326\bin\HostX86\x86\cl.exe' failed with exit status 2

I've searched on the internet for a solution but with no success...
Thank you

Continous reading of Tag gives None ever other time

I want to detect when a tag is present and when it is removed. First I thought it might be a hardware issue, that my request frequency is to high. But even waiting for 10 seconds still gives me None every other time.

Is it possible to change pins?

Adding input parameters to "SimpleMRC522()" would be great. CE/SDA, RST and probably others have no reason to be hard-coded, IMHO. Thank you for consideration, Mark0l

Rfid and serial

Rfid and serial can't work togheter with GPIO.setmode(GPIO.BCM) in code

Predicate error causes long response times

Trying to read a card on a Pi 0 can take almost one second, and this delay is unnecessary. The problem is an error in MFRC522.py at line 219:
if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):
This line is using bit-wise complement instead of the proper logical not. It should be written as
if not ((i != 0) and not (n & 0x01) and not (n & waitIRq)):
instead. This significantly reduces the time needed to read a card, or to detect that a card is not present.

Error reading uid[x] in HEX format

Dear Coders,
Congratulations for your work. I use your code to read tags with a RC522. Also I use a second MF7 reader for double checking the tags.

PROBLEM: While testing the readings of UIDs of the tags, I found out there are missing "0" in some uid[] in the output of the RCC522 reader. The output of a single tag on both readers:

pi@raspberrypi:~/Desktop/Biovalley $ python rfid_read_GIGATEK_MF7.py
rfid_read.py -> rfid reader on port /dev/ttyUSB1
rfid_read.py -> tag hex AC8C5E0A
rfid_read.py -> tag dec  2894880266
pi@raspberrypi:~/Desktop/Biovalley $ python rfid_read_MFRC522.py 
Hold a tag near the reader. You have 5 s. Hurry up!
Card detected
bag tag UID: 10,94,140,172
bag tag endian: ('172', '140', '94', '10')
bag tag hex: ('0xac', '0x8c', '0x5e', '0xa')
bag tag hex string: ('ac', '8c', '5e', 'a')
bag tag hex string concatenated: ac8c5ea
bag tag dec: 180930026

As you can see the tag number in HEX of the MF7 is "AC8C5E0A". While the tag number in hex of the RC522 is "ac8c5ea". There is a "0" missing in the HEX transformation of "10" into "0xa". I have troubles finding the source of the problem in the code of the MFRC522.py and would really appreciate some help.

Reader not reading?

Hello.

I have a RC522 module in hopes of having it read cards, but to no avail will it read the provided tags. I have the following code:

#!/usr/bin/env python

import RPi.GPIO as GPIO
import mfrc522
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

try:
        print("Hold a tag near the reader")
        id, text = reader.read()
        print("ID: %s\nText: %s" % (id,text))
        print()
finally:
        GPIO.cleanup()

When run with python3 ./read.py it reads Hold a tag near the reader. Yet, despite my endless waving next to the reader, it does not detect the card. Is there anything I can do to make sure it is connected properly and troubleshoot? Could it possible I have a defective module?

Thanks!

Uses lib in SPI V2 and Asus Tinker

Hello, I try to run the lib, but it's just the Raspberry card. I changed the lib to use Asus.GPIO (Asus TInker), but it doesn't work with spiV2.

This lib has modifications that I can use with the RFID-RC522 reader with spi v2?

Code cannot be installed from Pip

We're looking to use this across multiple devices, and installing from Pip would be incredibly useful to us.

It does mean re-arranging some of the code, but the advantage is that we can then build this into our Raspberry Pi config management tooling and deploy it wherever we need to.

Reader appears to not read in thread

Using python3 - a simple read works outside the thread but not inside. This is in a Flask script - I will try a simple thread example as well.

Update - this problem appears to be related to running in Flask

More Update - I got this to work by just adding the instantiation statement in the main thread. The when the rfid thread was setup, the code below worked. I have no idea why.

This is the cocde

` self.reader = SimpleMFRC522()

   print(self.reader)

   while True:

      id, text = self.reader.read()

      print("The ID for this card is:", id)

      print(id)

      sleep(1)

`

indentation issue on SimpleMFRC522.py

I forked the project as I wanted to make an improvement on the read method in SimpleMFRC522.py. When I cloned my fork and opened SimpleMFRC522.py I found that indentation was 2 spaces. In Python we need 4 spaces indentation.

Strangely when I installed the package using pip install everything worked out fine.

AUTH ERROR

If I run the code, the output is: AUTH ERROR!!
AUTH ERROR(status2reg & 0x08) != 0
1045353198723

MFRC522 hexadecimal input

Hi
I am working on a project and want to enter Hexadecimal values for input data rather than ACII.
I am really new to RPi and also to Python. I dont know where to ask and how to get help.
Can someone help me with this

It won't find my card!

Hey there!
I have followed through emmet's tutorial on the pimylifeup site. When I run the code though, it cant seem to see my scanner. I have the correct code from the examples, the correct python version and the correct wiring. What am I doing wrong?
Thanks alot,
James

My RC522 don't work

Hello,
I'm trying this tutorial
https://pimylifeup.com/raspberry-pi-rfid-rc522/
Where is linked this code.
I verified many times the connections, but my sensor is always with red led active and Write.py or Read.py don't write or read the rfid card.
Is possible that my sensor is broke?
There are other tests to evaluate my sensor?
thanks

Storage is 4 bytes per page

I have Sticker Tags with two issues:

  • Storage is 4 bytes per page
  • Authentication is not working (don't need it anyway)

Is it possible to read out how many bytes per page the Tag supports?
NXP TagInfo showed me that info and I could change your script to write to that tag, but I thought it would be nicer for the script to read out this information by itself...

Info about the Tag (according to the Seller):
20 NFC Stickers NTAG203
Product dimensions: diameter 25mm
Material: white polypropylene, self-adhesive
Chip: NXP NTAG203 - NFC Forum Type 2 Tag - ISO 14 443-2 A, ISO 14 443-3 A
Memory case: 168 Byte - NDEF formatted: 137 Bytes

Info according to TagInfo:
NTAG213
144 bytes user memory
36 pages, with 4 bytes per page
Full product name: NT2H1311G0DUx
Supports: ISO/IEC 14443-3 (Type A), ISO/IEC 14443-2 (Type A)

__main__ not found?

pi2@raspberrypi:~/raphael-kit/python $ python3 2.2.10_write.py
Traceback (most recent call last):
File "2.2.10_write.py", line 6, in
reader = SimpleMFRC522()
File "/home/pi2/.local/lib/python3.7/site-packages/mfrc522/SimpleMFRC522.py", line 14, in init
self.READER = MFRC522()
File "/home/pi2/.local/lib/python3.7/site-packages/mfrc522/MFRC522.py", line 130, in init
self.spi.open(bus, device)
FileNotFoundError: [Errno 2] No such file or directory

That's what I'm getting

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.