Package: mfrc522-python
MFRC522-pythonThe mfrc522-python library is used to interact with RFID readers that use the MFRC522 chip interfaced with a Raspberry Pi.Table of ContentsIntroductionInstallationConnectionsUsageUsingmfrc522.MFRC522Usingmfrc522.SimpleMFRC522Usingmfrc522.BasicMFRC522Example CodeUsingmfrc522.MFRC522Usingmfrc522.SimpleMFRC522Usingmfrc522.BasicMFRC522ContributionsLicenseIntroductionMFRC522The MFRC522 is a popular RFID module that supports contactless communication using the 13.56 MHz frequency. It can read and write data to RFID cards or tags, making it ideal for projects that require identification or access control. This repository provides a library and example code to interact with the MFRC522 module using various microcontroller platforms.Sectors and BlocksSectors and Blocks refer to the organization and structure of memory on an RFID tag or card.The memory of card is divided into16 sectors(for classic MIFARE 1k). Each sector contains4 blocksand each block can hold upto16 bytes of data.So a classic MIFARE 1k has16 sectors, 64 blocks (16  sectors x 4 blocks)  and can hold upto 1024 bytes (64 blocks x 16 bytes)in total.Not Every blocks are writeable, the first block of the first sector and the last block of every sectors are not writeable.
The first block offirst sector typically holds the manufaturer's details(likemanufacturer's identification number (MID) and the application identifier (AID). The MID is a unique number that identifies the manufacturer of the card. The AID is a unique number that identifies the application that is stored on the card.).The last block of every sector is called a trailer block, the trailer block contains information about the sector, such as thesector number, the number of blocks in the sector, and the checksum. The checksum is used to verify the integrity of the data in the sector.If you ever write to a trailer block then the entire sector will be unwritable.SectorsBlock Number00, 1, 2, 314, 5, 6, 728, 9, 10, 11312, 13, 14, 15416, 17, 18, 19520, 21, 22, 23624, 25, 26, 27728, 29, 30, 31832, 33, 34, 35936, 37, 38, 391040, 41, 42, 431144, 45, 46, 471248, 49, 50, 511352, 53, 54, 551456, 57, 58, 591560, 61, 62, 63Manfacturer's details is stored in block number 0  and
Trailer blocks are 3, 7, 11, etc,.( Tips: It's better to not store any data in the first sector. Start from the first sector )Note: Different cards have diiferent number of sectors and blocks. For example, Classic MIFARE 4k has 40 Sectors. It's better to check the datasheet for the RFID tag/card you use before writing data to it.Installation1. From PyPI (Stable)pip install mfrc522-python2. From Github ( Beta/dev version)pip install git+https://github.com/1AdityaX/mfrc522-pythonConnectionsRF522 ModuleRaspberry PiSDAPin 24 / GPIO8 (CE0)SCKPin 23 / GPIO11 (SCKL)MOSIPin 19 / GPIO10 (MOSI)MISOPin 21 / GPIO9 (MISO)IRQ–GNDGNDRSTPin 22 / GPIO253.3V3.3VUsageUsingMFRC522classImport and create an instance of classMFRC522frommfrc522module.frommfrc522importMFRC522reader=MFRC522()Request communication with a PICC(Proximity Integrated Circuit Card A.K.A rfid card)and check if the communication is established.status=Nonewhilestatus!=reader.MI_OK:(status,TagType)=reader.Request(reader.PICC_REQIDL)ifstatus==reader.MI_OK:print("Connection Success!")Perform an Anti-collision Algorithm(Picks one rfid card if multiple cards are placed )and return the UID.(status,uid)=reader.Anticoll()ifstatus==reader.MI_OK:print(uid)Select the tag to Authenticate and perform funtions like reading or writing data to the card.reader.SelectTag(uid)Authenticate a particular sector with a key to read or write data to it.trailer_block=11#This is the default key for MIFARE Cardskey=[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]status=reader.Authenticate(reader.PICC_AUTHENT1A,trailer_block,key,uid)Now read or write to the block numbers in the sector that you have authenticated.To readblock_nums=[8,9,10]data=[]forblock_numinblock_nums:block_data=reader.ReadTag(block_num)ifblock_data:data+=block_dataifdata:print(''.join(chr(i)foriindata))To writeblock_nums=[8,9,10]text="Hello, World"data=bytearray()data.extend(bytearray(text.ljust(len(block_addrs)*16).encode('ascii')))i=0forblock_numinblock_addrs:reader.WriteTag(block_num,data[(i*16):(i+1)*16])i+=1Once you business with the RFID card or Tag is over. Always Stop the Authenciation/communiction with the card.Note: If you miss out this step, you won't be able to use a different card.reader.StopAuth()UsingSimpleMFRC522classImport and create an instance of classSimpleMFRC522frommfrc522modulefrommfrc522importSimpleMFRC522reader=SimpleMFRC522()Useread()to read andwrite()to writeTo readid,text=reader.read()print(f"ID:{id}")print(f"Text:{text}")To writetext="hello_world"id,text_written=reader.write(text)print(f"ID:{id}")print(f"Text Written:{text_written}")mfrc522.SimpleMFRC522()Methods__init__()Initializes aSimpleMFRC522instance. It sets up the MFRC522 module, defines the default authentication key, sets the trailer block number to 11, and initializes the BasicMFRC522 module.read()Reads data from the RFID tag.Returns: A tuple containing the tag ID (as an integer) and the data read (as a string).read_id()Reads the tag ID from the RFID tag.Returns: The tag ID as an integer.write(text)Writes the given text to an RFID tag.Args:text(str): A string to be written to the RFID tag.Returns: A tuple containing the ID of the tag and the text that was written to the tag.UsingBasicMFRC522classImport and create an instance of the classBasicMFRC522frommfrc522modulefrommfrc522importBasicMFRC522reader=BasicMFRC522()Use any methods.mfrc522.BasicMFRC522Methods__init__(KEY=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])Initializes aBasicMFRC522instance.Args:KEY(list): The authentication key used for reading and writing data. The default key is[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF].read_sector(trailer_block=11)Reads data from a sector of the RFID tag.Args:trailer_block(int): The block number of the sector trailer.Returns:tuple: A tuple containing the tag ID (as an integer) and the data read (as a string).read_sectors(trailer_blocks=[11])Reds data from multiple sectors of the RFID tag.Args:trailer_blocks(list): The list of block numbers of the sector trailers.Returns:tuple: A tuple containing the tag ID (as an integer) and the concatenated data read from all sectors (as a string).read_id()Reads the tag ID from the RFID tag.Returns:int: The tag ID as an integer.read_id_no_block()Attempts to read the tag ID from the RFID tag without blocking.Returns:int: The tag ID as an integer, orNoneif the operation fails.read_no_block(trailer_block)Attempts to read data from the RFID tag without blocking.Args:trailer_block(int): The block number of the sector trailer.block_addr(tuple): The block numbers of the data blocks to read.Returns:tuple: A tuple containing the tag ID (as an integer) and the data read (as a string), or(None, None)if the operation fails.write_sector(text, trailer_block=11)Writes data to a sector of the RFID tag.Args:text(str): The data to write.trailer_block(int): The block number of the sector trailer.Returns:tuple: A tuple containing the tag ID (as an integer) and the data written (as a string).write_sectors(text, trailer_blocks=[11])Writes data to multiple sectors of the RFID tag.Args:text(str): The data to write.trailer_blocks(list): The list of block numbers of the sector trailers.Returns:tuple: A tuple containing the tag ID (as an integer) and the concatenated data written to all sectors (as a string).write_no_block(text, trailer_block)Attempts to write data to the RFID tag without blocking.Args:text(str): The data to write.trailer_block(int): The block number of the sector trailer.block_addr(tuple): The block numbers.clear_sector(trailer_block=11)Clears a sector of the RFID tag by writing empty data to all blocks.Args:trailer_block(int): The block number of the sector trailer.Returns:tuple: A tuple containing the tag ID (as an integer) and the cleared data (as an empty string).clear_sectors(trailer_blocks=[11])Clears multiple sectors of the RFID tag by writing empty data to all blocks.Args:trailer_blocks(list): The list of block numbers of the sector trailers.Returns:tuple: A tuple containing the tag ID (as an integer) and the concatenated cleared data (as an empty string).clear_no_block(trailer_block)Attempts to clear a sector of the RFID tag without blocking.Args:trailer_block(int): The block number of the sector trailer.block_addr(tuple): The block numbers of the data blocks to clear.Returns:tuple: A tuple containing the tag ID (as an integer) and the cleared data (as an empty string), or(None, None)if the operation fails.Note: Clearing a sector will permanently erase the data stored in the blocks of that sector. Use with caution as this operation cannot be undone.Example CodeUsingMFRC522classread.pyTo read a particular sector and convert the bytes to plain string/text.frommfrc522importMFRC522reader=MFRC522()defread(trailer_block,key,block_addrs):(status,TagType)=reader.Request(reader.PICC_REQIDL)ifstatus!=reader.MI_OK:returnNone,None(status,uid)=reader.Anticoll()ifstatus!=reader.MI_OK:returnNone,Noneid=uidreader.SelectTag(uid)status=reader.Authenticate(reader.PICC_AUTHENT1A,trailer_block,key,uid)data=[]text_read=''ifstatus==reader.MI_OK:forblock_numinblock_addrs:block=reader.ReadTag(block_num)ifblock:data+=blockifdata:text_read=''.join(chr(i)foriindata)reader.StopAuth()returnid,text_readtrailer_block=11key=[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]block_addrs=[8,9,10]id,text=read(trailer_block,key,block_addrs)whilenotid:id,text=read(trailer_block,key,block_addrs)print(id)print(text)write.pyTo write a particular sector.frommfrc522importMFRC522reader=MFRC522()defwrite(trailer_block,key,block_addrs,text):(status,TagType)=reader.Request(reader.PICC_REQIDL)ifstatus!=reader.MI_OK:returnNone,None(status,uid)=reader.Anticoll()ifstatus!=reader.MI_OK:returnNone,Nonereader.SelectTag(uid)status=reader.Authenticate(reader.PICC_AUTHENT1A,trailer_block,key,uid)reader.ReadTag(trailer_block)ifstatus==reader.MI_OK:data=bytearray()data.extend(bytearray(text.ljust(len(block_addrs)*16).encode('ascii')))i=0forblock_numinblock_addrs:reader.WriteTag(block_num,data[(i*16):(i+1)*16])i+=1reader.StopAuth()returnuid,text[0:(len(block_addrs)*16)]trailer_block=11block_addrs=[8,9,10]key=[0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]text="some random text"uid,text_in=write(trailer_block,key,block_addrs,text)whilenotuid:uid,text_in=write(trailer_block,key,block_addrs,text)print(uid)print(text_in)UsingSimpleMFRC522classread.pyfrommfrc522importSimpleMFRC522reader=SimpleMFRC522()id,text=reader.read()print(f"ID:{id}")print(f"Text:{text}")write.pyfrommfrc522importSimpleMFRC522writer=SimpleMFRC522()text="Hello, world"id,text_written=writer.write(text)print(f"ID:{id}")print(f"Text Written:{text_written}")UsingBasicMFRC522classread_sector.pyTo read a particular sectorfrommfrc522importBasicMFRC522reader=BasicMFRC522()sector=15id,text=reader.read_sector(sector)print(f"ID:{id}")print(f"Text:{text}")read_sectors.pyTo read multiple sectorsfrommfrc522importBasicMFRC522reader=BasicMFRC522()sectors=[11,15]id,text=reader.read_sectors(sectors)print(f"ID:{id}")print(f"Text:{text}")write_sector.pyTo write a particular sectorfrommfrc522importBasicMFRC522writer=BasicMFRC522()sector=15text="Example to use write_sector method"id,text_written=writer.write_sector(text,sector)print(f"ID:{id}")print(f"Text Written:{text_written}")write_sectors.pyTo write multiple sectorsfrommfrc522importBasicMFRC522writer=BasicMFRC522()sector=[11,15]text="Example to use write_sector method"id,text_written=writer.write_sectors(text,sector)print(f"ID:{id}")print(f"Text Written:{text_written}")clear_sector.pyTo clear data written in a sectorfrommfrc522importBasicMFRC522writer=BasicMFRC522()sector=11id=writer.clear_sector(sector)print("Cleared")clear_sectors.pyTo clear data written in multiple sectorsfrommfrc522importBasicMFRC522writer=BasicMFRC522()sectors=[11,15]id=writer.clear_sectors(sectors)print("Cleared")ContributionsContributions to themfrc522-pythonlibrary are welcome. To contribute, follow these steps:Fork the repository on GitHub.Create a new branch for your changes.Make your changes and commit them.Push your changes to your forked repository.Submit a pull request to the main repository.That's it! By submitting a pull request, you can contribute your changes to themfrc522-pythonlibrary.
Provide a clear description of your changes in the pull request.
If you have any questions or need further assistance, feel free to open an issue.LicenseThis project is licensed under the GNU General Public License (GPL) version 3.0. You can find the full text of the license in theLICENSEfile.