StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

RFID w/ RPi2

Sun Oct 28, 2018 8:26 pm

I recently purchased an RFID read/write module which i have been trying to use with my RPi2 running Jessie.

I went into raspi-config and enabled SPI
cloned SPI-Py
cloned MFRC522 to my Pi

I go to install SPI-Py and it gives me an error:

Code: Select all

running install
running build
running built_ext
building 'spi' extension
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -02 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat _Werror=format-security -fPIC -I/usr/include/python2.7 -c spi.c -0 build/temp.linux-armv7l-2.7/spi.o
spi.c:20:20: fatal error: Python.h: No such file or directory
  #include <Python.h>
                                  ^
compilation terminated.
error; command 'arm-linux-gnueabihf-gcc' failed without exit status
There is nothing concerning SPI in /boot/config.txt
No /etc/modprobe.d/raspi-blacklist

Any help is appreciated. Will update should i magically figure it out

Andyroo

Re: RFID w/ RPi2

Sun Oct 28, 2018 8:49 pm

You need to download the python dev library and rerun the compile.

Code: Select all

sudo apt-get install python-dev
If you are using Python 3 replace the python-dev with python3-dev in the above command.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Oct 28, 2018 9:39 pm

Thanks, must've missed that in my searching.

Have you tinkered with RFID coding projects before?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Oct 28, 2018 11:14 pm

So with some help, i did get the MFRC522 working. Using the read and write examples that accompanied the device, i can read the default UID and key. I would like to be able to write a custom UID and key but no idea as to how I would do such a thing since i have yet to mess with hexadecimal coding

Andyroo

Re: RFID w/ RPi2

Sun Oct 28, 2018 11:47 pm

StangPi wrote:
Sun Oct 28, 2018 9:39 pm
Thanks, must've missed that in my searching.

Have you tinkered with RFID coding projects before?
Onyly professionally at +5 to -16C using handhelds and specialist toolkits / dev tools :lol:

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Nov 04, 2018 3:27 pm

So far I can only get the RFID to read the card, but when i try to write it it will not fo anything.

Here is the MFRC522 Write Code:

Code: Select all

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"
Lines 38 and 39 are where the default key is. How do alter this and create a new key to be written to the RFID modules?? Can i just change the 0xFFs' to different expressions and hope it works?

The kit i purchased came with both a card, and RFID fob. So naturally I will be wanting to create a library that lets my security program understand who is trying to gain access and who is not. Libraries are not my strong suit.
Will post what i make, and help would be appreciated. Thanks, have a good day.

Andyroo

Re: RFID w/ RPi2

Sun Nov 04, 2018 4:46 pm

Normally you would not change the ID of the card as that’s unique but change only the data blocks and all FFs should let you write to available blocks.

Not all cards can be written to and not all readers are writers :D

This GITHUB library is quite handy https://github.com/ondryaso/pi-rc522

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Nov 04, 2018 10:53 pm

So i meddled with an example read code that came in a github repository. I modified it to only find the UID and print it if one was found.

Working 1st mod

Code: Select all

#Imports
import time
import RPi.GPIO as GPIO
import MFRC522

#Create Object of Class MFRC522
MIFAREReader = MFRC522.MFRC522()

#Welcome Message
print("Searching for Card")
print("Ctrl+C to Stop")

#Loop to Find Chip, and Get UID if Found
try:

    while True:

        #Scan For Tag
        (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

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

        #Continue if UID is Present
        if status == MIFAREReader.MI_OK:
            print("UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]))

            time.sleep(2)

except KeyboardInterrupt:
    GPIO.cleanup()
Once it worked, i tried a second modification

Code: Select all

#Imports
import time
import RPi.GPIO as GPIO
import MFRC522

UID = 00000000000

#Create Object of Class MFRC522
MIFAREReader = MFRC522.MFRC522()

#Welcome Message
print("Searching for Card")
print("Ctrl+C to Stop")

#Loop to Find Chip, and Get UID if Found
while True:

    #Scan For Tag
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

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

    #Verify
    if UID == (status,uid):
	print('verified')

    else:
	print('wrong')

        time.sleep(2)

except KeyboardInterrupt:
    GPIO.cleanup()
Upon attempting this mod, i get an error:

Code: Select all

File "atV2.py", line 34
    except KeyboardInterrupt:
               ^
SyntaxError: invalid syntax
If i capitalize Except, the indicator arrow shifts to the last 't' in Interrupt but still a syntax error.

Andyroo

Re: RFID w/ RPi2

Sun Nov 04, 2018 11:18 pm

Double quotes for the text in the print() functions? :?:

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Nov 04, 2018 11:27 pm

Nope, tried that after post about error.

Andyroo

Re: RFID w/ RPi2

Sun Nov 04, 2018 11:44 pm

Ok you’ll need to hack this about to get it to work (head not in a coding space at the mo) but pop a try into the loop

Code: Select all

while True:
    Try:
        ....
     
    except something other than keyboard interrupt
You need to add a get out to the While True - possibly a break?

Wonder if something is getting an error and the except is having a bit of a problem?

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Mon Nov 05, 2018 12:04 am

I did insert a "try:" before the while true and it worked, but wouldnt scan for the card. Once i reset it back to just finding a card it worked again.
After the (status,uid) is where i would like to have it verify the card's UID against a predefined UID hich would obviously be the card's own, and use that as a security check or a authentication of the user which would then lead to a password entry script etc etc etc.
After the #Get UID portion, i did attempt a

Code: Select all

while status(True) == MIFAREReader,MI_OK:
    if uid == UID:
         print("Verified")
         nextScript.nextScript()
did not work. im guessing im trying to make something work that isnt supposed to??

Andyroo

Re: RFID w/ RPi2

Mon Nov 05, 2018 1:00 am

Almost, the UID returned by the function is a list rather than string!

Convert to string with str(uid[0])+str(uid[1])+str(uid[2]) etc

Or define the other value as a list :lol:

I don’t think you need to order them for the == to work if you get the byte order correct. Maybe worth check the output first? In fact thinking about it - ordering the lists could lead to duplicate card numbers so just check the byte order.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Mon Nov 05, 2018 1:20 am

When it finds the UID, it does get printed as 00,000,000,000.

im working on having it authenticate the card's UID against the predefined one. Once i get that part down, i can move on.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Mon Nov 05, 2018 1:41 am

Some ''progress'' i think

Code: Select all

#if found
while status == MIFAREReader.MI_OK:
        if UID == (+str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])):
        print(''verified'')
i get this error:

Code: Select all

Traceback (most recent call last):
  File "atV2.py", line 28, in <module>
    if UID == (+str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3])):
TypeError: bad operand type for unary +: 'str'
Im guessing that it doesnt like me starting that comparison line with ''+''. Does this mean i have to enclose the str line within brackets''{ }'' or box brackets ''[ ]''?

Andyroo

Re: RFID w/ RPi2

Mon Nov 05, 2018 3:24 pm

I would not name two variable UID and uid as you're bound to get them mixed up at some point :mrgreen:
As for the '+' - never tried it...
I would add something like this to convert the list into a string before the compare:

Code: Select all

# Both of these are Python 3 code
# In both examples, the '' are TWO single quotes not one double

readuid = ''.join(uid)
if UID == readuid:

# Or if that fails as the list elements are numeric

readuid = ''.join(str(e) for e in uid)
if UID == readuid:
Obviously indent as needed but first it maybe worth just hacking together a simple read program that does nothing else but read a card and print it till you understand exactly what you are getting back :lol:

This may need tweaking if the reader returns commas in the list.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Tue Nov 06, 2018 12:44 am

I cut down a total read program (UID and key), to just read and display the UID.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Tue Nov 06, 2018 12:59 am

I couldn't use the examples you gave as I am working with Python2, but they did push me top try a different approach.

Code: Select all

#if found
while status == MIFAREReader.MI_OK:
        if UID == (uid(str)):
        print("verified")
Now the program does try to compare my UID definition, and the uid that is read. but i get this error:

Code: Select all

Traceback (most recent call last):
  File "atV2.py", line 28, in <module>
    if UID == (uid(str)):
TypeError: 'list' object is not callable
at first i did try

Code: Select all

if UID == (str(uid)):
but it wouldnt read the card

danjperron
Posts: 3421
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: RFID w/ RPi2

Tue Nov 06, 2018 2:16 pm

Amazing how many people want to use the mifare card reader at the same time.

You should check this post.

viewtopic.php?f=41&t=225948#p1387383


I did modify MFC522 python code to use spidev instead. It is also able to read the 7 and 10 bytes cards,
In the github I put an 'HowTo' for a system with an sql database. Work is in progress .
I'm adding the php code for administration.

B.T.W. I'm doing it on a Pi2.

Enjoy.

StangPi
Posts: 68
Joined: Wed Feb 24, 2016 9:26 pm
Location: Indiana, USA

Re: RFID w/ RPi2

Sun Nov 11, 2018 10:59 pm

@danjperron
I appreciate the link to the github repository. It has helped me to understand a few things.

how is spidev better/spi? This is my first attempt at using spi for anything. Hopefully when i can understand it better, i can integrate it into a security program/device i am building.

danjperron
Posts: 3421
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: RFID w/ RPi2

Sun Nov 11, 2018 11:40 pm

how is spidev better/spi?
- spidev already in raspbian.
- spidev is compatible with python3. This is enough for me.

My modified version also read 7 bytes ad 10 bytes mifare card,

Return to “Troubleshooting”