B4R Library MFRC522 - RFID reader / writer

SS-2016-05-22_16.19.26.jpg


This library is based on this open source project: https://github.com/miguelbalboa/rfid

It allows reading and writing to RFID cards using RC522 modules. The RFID modules and the cards (or stickers) are inexpensive.

The pins layout is described here: https://github.com/miguelbalboa/rfid#pin-layout
Make sure to connect the module 3.3v pin to the Arduino 3V3 pin.

Each card has a unique UID.

Complete program that reads UIDs:
B4X:
'depends on rRandomAccessFile and rMFRC522 libraries
Sub Process_Globals
   Public Serial1 As Serial
   Private rfid As MFRC522
   Private bc As ByteConverter
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   Log("AppStart")
   rfid.Initialize(10, 9, "rfid_CardPresent")
   rfid.LogVersion
End Sub

Sub rfid_CardPresent (UID() As Byte, CardType As Byte)
   Log("UID: ", bc.HexFromBytes(UID))
End Sub

The library also supports reading and writing to Mifare cards. This requires some knowledge of the card structure. Overall it is quite simple.

The card is organized into sectors. Each sector includes 4 blocks and each block is made of 16 bytes (the Mifare 4k also has larger sectors).
The last block in each sector is a special block that holds authentication data about the sector. This means that you shouldn't write to block numbers 3, 7, 11, etc. Block 0 is also readonly as it stores the UID.

You need to authenticate before you can read or write. This is done with
MifareAuthenticate or MifareAuthenticate2 methods.

Example that writes and reads from block #1:
B4X:
Sub rfid_CardPresent (UID() As Byte, CardType As Byte)
   Log("UID: ", bc.HexFromBytes(UID))
   Log("Type: ", CardType, ", Is it Mifare: ", rfid.IsMifare)
   If rfid.IsMifare Then
     If rfid.MifareAuthenticate(1) = False Then
       Log("Failed to authenticate")
       Return
     End If
     Dim buffer(18) As Byte
     For i = 0 To buffer.Length - 1
       buffer(i) = i
     Next
     'write 16 bytes to block number 1
     Log("Write: ", rfid.MifareWrite(1, buffer))
     If rfid.MifareRead(1, buffer) > 0 Then 'buffer size must be 18 bytes or more
       Log(bc.HexFromBytes(buffer))
     Else
       Log("Failed to read")
     End If
   End If
End Sub

Updates

V1.02 - Based on the latest version of the open source project (March 2019).
 

Attachments

  • rMFRC522.zip
    80.2 KB · Views: 1,046
Last edited:

Michael1968

Active Member
Licensed User
Longtime User
have you test this ?
B4X:
rfid.Initialize(d1pins.D4, d1pins.D8, "rfid_CardPresent")
    rfid.LogVersion
 

petr4ppc

Well-Known Member
Licensed User
Longtime User
Michael1968
Thank you for your tip
With your settings I get :
Firmware Version: 0x0 = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?

I will test Arduino Uno
 
Last edited:
Top