RC522 RF Identification IC Card Sensing Module
Near Field Communication (NFC), also known as short-range wireless communication, is a short-distance high-frequency wireless communication technology that allows non-contact point-to-point data transfer (within ten centimeters) between electronic devices to exchange data. This technology evolved from contactless radio frequency identification (RFID) and is backward compatible with RFID. It was first successfully developed by SONY and PHILIPS independently, and is mainly used in handheld devices such as mobile phones to provide M2M (Machine to Machine) communication. Because near field communication has natural security, NFC technology is considered to have great application prospects in fields such as mobile phone payments. At the same time, NFC is also considered by the China Internet of Things School-Enterprise Alliance as a "secure dialog" between machines because of its better security compared to other wireless communication technologies.
Module Source
Purchase link: https://item.taobao.com/item.htm?spm=a21n57.1.0.0.33fb523cor6YaQ&id=19376862391&ns=1&abbucket=0#detail Materials download: https://pan.baidu.com/s/1pGSaohXnOi8tu6M3i3KFcQ Extraction code: suah
Specifications
Operating voltage: 3.3V Operating current: 10-26mA Module size: 40mm×60mm Supported card types: mifare1 S50, mifare1 S70, mifare UltraLight, mifare Pro, mifare Desfire Control method: SPI
View Materials
The S50 contactless IC card is divided into 16 sectors, each sector consists of 4 blocks (block 0, block 1, block 2, block 3). (We also number the 64 blocks of the 16 sectors with absolute addresses 0~63. The storage structure is shown in the figure below:
- Block 0 of sector 0 (i.e., absolute address block 0) is used to store the manufacturer code and is already fixed and cannot be changed.
- Blocks 0, 1, and 2 of each sector are data blocks that can be used to store data. Data blocks can be used in two ways:
- Used for general data storage, supporting read and write operations.
- Used as data values, supporting initialization, increment, decrement, and read operations.
- Block 3 of each sector is a control block, including password A, access control, and password B. The specific structure is as follows:
- The password and access control of each sector are independent, and you can set their own passwords and access controls according to actual needs. The access control is 4 bytes, 32 bits in total. The access conditions for each block (including data blocks and control blocks) in the sector are jointly determined by the password and access control. Each block has three corresponding control bits in the access control, defined as follows:
The three control bits exist in both normal and inverted forms in the access control bytes, determining the access rights of the block (e.g., decrement operations must verify KEY A, increment operations must verify KEY B, etc.).
- Access control for data blocks (block 0, block 1, block 2) is as follows:
File Download
(KeyA|B means password A or password B, Never means cannot be implemented under any conditions) For example: when the access control bits C10 C20 C30 of block 0 are 1 0 0, it can be read after verifying password A or password B is correct; it can be written after verifying password B is correct; increment and decrement operations cannot be performed.
- The access control of control block 3 is different from data blocks (block 0, 1, 2). Its access control is as follows:
For example: when the access control bits C13 C23 C33 of block 3 are 1 0 0, it means:
Password A: Not readable, can be written (changed) after verifying KEYA or KEYB is correct.
Access control: Can be read and written after verifying KEYA or KEYB is correct.
Password B: Can be read and written after verifying KEYA or KEYB is correct.
- Communication between M1 RF card and reader
Porting Process
Pin Selection
Port to Project
Our goal is to port the example to the ESP32-S3 dev board. Complete driver code has been provided for you. Follow the steps below to complete the porting. For detailed instructions on creating folders and new .c and .h files, refer to section 1.4.2 in the [DHT11 Temperature and Humidity Sensor] chapter; we will not repeat it here. However, here we replace the file names bsp_dht11.c and bsp_dht11.h with bsp_rc522.c and bsp_rc522.h, and change the folder name to RC522_IC.
Write Code
In the file bsp_rc522.c, write the following code.
/*
* LCSC-Openkits (LCKFB) software and hardware materials and related expansion board software and hardware materials are all open source on the official website.
* Dev board official website: www.lckfb.com
* Technical support resides on the forum; any technical questions are welcome for exchange and learning at any time.
* LCKFB Forum: club.szlcsc.com
* Follow our Bilibili account: [LCSC-Openkits (LCKFB)] to keep up with our latest updates!
* We do not make money by selling boards; we take cultivating engineers as our mission.
* Change Logs:
* Date Author Notes
* 2024-01-10 LCKFB-lp first version
*/
#include "bsp_rc522.h"
void delay_ms(unsigned int ms)
{
vTaskDelay(ms / portTICK_PERIOD_MS);
}
void delay_us(unsigned int us)
{
ets_delay_us(us);
}
void delay_1ms(unsigned int ms)
{
vTaskDelay(ms / portTICK_PERIOD_MS);
}
void delay_1us(unsigned int us)
{
ets_delay_us(us);
}
/******************************************************************
* Function Name: RC522_Init
* Function Description: IC card sensing module configuration
* Function Parameters: None
* Function Return: None
* Author: LC
* Notes:
******************************************************************/
void RC522_Init(void)
{
gpio_config_t out_config = {
.pin_bit_mask = (1ULL<<GPIO_CS)|(1ULL<<GPIO_SCK)|(1ULL<<GPIO_MOSI)|(1ULL<<GPIO_RST), //Configure pins
.mode =GPIO_MODE_OUTPUT, //Output mode
.pull_up_en = GPIO_PULLUP_ENABLE, //Enable pull-up
.pull_down_en = GPIO_PULLDOWN_DISABLE, //Disable pull-down
.intr_type = GPIO_INTR_DISABLE //Disable pin interrupt
};
gpio_config(&out_config);
gpio_config_t in_config = {
.pin_bit_mask = (1ULL<<GPIO_MISO), //Configure pins
.mode =GPIO_MODE_INPUT, //Output mode
.pull_up_en = GPIO_PULLUP_DISABLE, //Disable pull-up
.pull_down_en = GPIO_PULLDOWN_DISABLE, //Disable pull-down
.intr_type = GPIO_INTR_DISABLE //Disable pin interrupt
};
gpio_config(&in_config);
}
////////////////Software-simulated SPI communication with RC522///////////////////////////////////////////
/* Software-simulated SPI sends one byte of data, MSB first */
void RC522_SPI_SendByte( uint8_t byte )
{
uint8_t n;
for( n=0;n<8;n++ )
{
if( byte&0x80 )
RC522_MOSI_1();
else
RC522_MOSI_0();
delay_us(200);
RC522_SCK_0();
delay_us(200);
RC522_SCK_1();
delay_us(200);
byte<<=1;
}
}
/* Software-simulated SPI reads one byte of data, reads MSB first */
uint8_t RC522_SPI_ReadByte( void )
{
uint8_t n;
uint8_t data = 0;
for( n=0;n<8;n++ )
{
data <<= 1;
RC522_SCK_0();
delay_us(200);
if( RC522_MISO_GET()==1 )
{
data|=0x01;
}
delay_us(200);
RC522_SCK_1();
delay_us(200);
}
return data;
}
//////////////////////////GD32 operations on RC522 registers//////////////////////////////////
/* Read the value of a specified RC522 register
Write specified data to a specified RC522 register
Set a specified bit of a specified RC522 register
Clear a specified bit of a specified RC522 register
*/
/**
* @brief : Read the value of a specified RC522 register
* @param : Address: Register address
* @retval : Register value
*/
uint8_t RC522_Read_Register( uint8_t Address )
{
uint8_t data,Addr;
Addr = ( (Address<<1)&0x7E )|0x80;
RC522_CS_Enable();
RC522_SPI_SendByte( Addr );
data = RC522_SPI_ReadByte();//Read the value in the register
RC522_CS_Disable();
return data;
}
/**
* @brief : Write specified data to a specified RC522 register
* @param : Address: Register address
data: Data to write to the register
* @retval : None
*/
void RC522_Write_Register( uint8_t Address, uint8_t data )
{
uint8_t Addr;
Addr = ( Address<<1 )&0x7E;
RC522_CS_Enable();
RC522_SPI_SendByte( Addr );
RC522_SPI_SendByte( data );
RC522_CS_Disable();
}
/**
* @brief : Set a specified bit of a specified RC522 register
* @param : Address: Register address
mask: Set value
* @retval : None
*/
void RC522_SetBit_Register( uint8_t Address, uint8_t mask )
{
uint8_t temp;
/* Get the current register value */
temp = RC522_Read_Register( Address );
/* Set the specified bit, then write the value back to the register */
RC522_Write_Register( Address, temp|mask );
}
/**
* @brief : Clear a specified bit of a specified RC522 register
* @param : Address: Register address
mask: Clear value
* @retval : None
*/
void RC522_ClearBit_Register( uint8_t Address, uint8_t mask )
{
uint8_t temp;
/* Get the current register value */
temp = RC522_Read_Register( Address );
/* Clear the specified bit, then write the value back to the register */
RC522_Write_Register( Address, temp&(~mask) );
}
///////////////////GD32 basic communication with RC522///////////////////////////////////
/*
Turn on the antenna
Turn off the antenna
Reset RC522
Set RC522 working mode
*/
/**
* @brief : Turn on the antenna
* @param : None
* @retval : None
*/
void RC522_Antenna_On( void )
{
uint8_t k;
k = RC522_Read_Register( TxControlReg );
/* Check whether the antenna is on */
if( !( k&0x03 ) )
RC522_SetBit_Register( TxControlReg, 0x03 );
}
/**
* @brief : Turn off the antenna
* @param : None
* @retval : None
*/
void RC522_Antenna_Off( void )
{
/* Directly clear the corresponding bits */
RC522_ClearBit_Register( TxControlReg, 0x03 );
}
/**
* @brief : Reset RC522
* @param : None
* @retval : None
*/
void RC522_Rese( void )
{
RC522_Reset_Disable();
delay_us ( 1 );
RC522_Reset_Enable();
delay_us ( 1 );
RC522_Reset_Disable();
delay_us ( 1 );
RC522_Write_Register( CommandReg, 0x0F );
while( RC522_Read_Register( CommandReg )&0x10 )
;
/* Buffer a bit */
delay_us ( 1 );
RC522_Write_Register( ModeReg, 0x3D ); //Define common send and receive mode
RC522_Write_Register( TReloadRegL, 30 ); //16-bit timer low byte
RC522_Write_Register( TReloadRegH, 0 ); //16-bit timer high byte
RC522_Write_Register( TModeReg, 0x8D ); //Internal timer settings
RC522_Write_Register( TPrescalerReg, 0x3E ); //Set timer divider coefficient
RC522_Write_Register( TxAutoReg, 0x40 ); //Modulate transmit signal to 100% ASK
}
/**
* @brief : Set RC522 working mode
* @param : Type: Working mode
* @retval : None
M500PcdConfigISOType
*/
void RC522_Config_Type( char Type )
{
if( Type=='A' )
{
RC522_ClearBit_Register( Status2Reg, 0x08 );
RC522_Write_Register( ModeReg, 0x3D );
RC522_Write_Register( RxSelReg, 0x86 );
RC522_Write_Register( RFCfgReg, 0x7F );
RC522_Write_Register( TReloadRegL, 30 );
RC522_Write_Register( TReloadRegH, 0 );
RC522_Write_Register( TModeReg, 0x8D );
RC522_Write_Register( TPrescalerReg, 0x3E );
delay_us(2);
/* Turn on antenna */
RC522_Antenna_On();
}
}
/////////////////////////GD32 controls RC522 to communicate with M1 card///////////////////////////////////////
/*
Communicate with M1 card through RC522 (bidirectional data transmission)
Seek card
Anti-collision
Use RC522 to calculate CRC16 (cyclic redundancy check)
Select card
Verify card password
Write specified data to a specified block address of M1 card
Read data from a specified block address of M1 card
Put the card into sleep mode
*/
/**
* @brief : Communicate with ISO14443 card through RC522
* @param : ucCommand: RC522 command word
* pInData: Data sent to the card through RC522
* ucInLenByte: Byte length of data sent
* pOutData: Received card return data
* pOutLenBit: Bit length of returned data
* @retval : Status value MI_OK, success
*/
char PcdComMF522 ( uint8_t ucCommand, uint8_t * pInData, uint8_t ucInLenByte, uint8_t * pOutData, uint32_t * pOutLenBit )
{
char cStatus = MI_ERR;
uint8_t ucIrqEn = 0x00;
uint8_t ucWaitFor = 0x00;
uint8_t ucLastBits;
uint8_t ucN;
uint32_t ul;
switch ( ucCommand )
{
case PCD_AUTHENT: //Mifare authentication
ucIrqEn = 0x12; //Enable error interrupt request ErrIEn Enable idle interrupt IdleIEn
ucWaitFor = 0x10; //When authenticating and seeking card, query idle interrupt flag bit
break;
case PCD_TRANSCEIVE: //Receive send send receive
ucIrqEn = 0x77; //Enable TxIEn RxIEn IdleIEn LoAlertIEn ErrIEn TimerIEn
ucWaitFor = 0x30; //When seeking card, query receive interrupt flag bit and idle interrupt flag bit
break;
default:
break;
}
RC522_Write_Register ( ComIEnReg, ucIrqEn | 0x80 ); //IRqInv set, pin IRQ is inverted from IRq bit value of Status1Reg
RC522_ClearBit_Register ( ComIrqReg, 0x80 ); //Set1, when this bit is cleared, the mask bits of CommIRqReg are cleared
RC522_Write_Register ( CommandReg, PCD_IDLE ); //Write idle command
RC522_SetBit_Register ( FIFOLevelReg, 0x80 ); //Set FlushBuffer to clear internal FIFO read and write pointers and BufferOvfl flag of ErrReg is cleared
for ( ul = 0; ul < ucInLenByte; ul ++ )
RC522_Write_Register ( FIFODataReg, pInData [ ul ] ); //Write data into FIFOdata
RC522_Write_Register ( CommandReg, ucCommand ); //Write command
if ( ucCommand == PCD_TRANSCEIVE )
RC522_SetBit_Register(BitFramingReg,0x80); //StartSend set to start data transmission; this bit is only effective when used with transceiver command
ul = 1000;//Adjust according to clock frequency, maximum wait time for M1 card operation is 25ms
do //Authentication and seek card wait time
{
ucN = RC522_Read_Register ( ComIrqReg ); //Query event interrupt
ul --;
} while ( ( ul != 0 ) && ( ! ( ucN & 0x01 ) ) && ( ! ( ucN & ucWaitFor ) ) ); //Exit conditions: i=0, timer interrupt, and write idle command
RC522_ClearBit_Register ( BitFramingReg, 0x80 ); //Clear StartSend enable bit
if ( ul != 0 )
{
if ( ! ( RC522_Read_Register ( ErrorReg ) & 0x1B ) ) //Read error flag register BufferOfI CollErr ParityErr ProtocolErr
{
cStatus = MI_OK;
if ( ucN & ucIrqEn & 0x01 ) //Whether timer interrupt occurred
cStatus = MI_NOTAGERR;
if ( ucCommand == PCD_TRANSCEIVE )
{
ucN = RC522_Read_Register ( FIFOLevelReg ); //Read number of bytes saved in FIFO
ucLastBits = RC522_Read_Register ( ControlReg ) & 0x07; //Valid bits of the last received byte
if ( ucLastBits )
* pOutLenBit = ( ucN - 1 ) * 8 + ucLastBits; //N bytes minus 1 (last byte) + last bit count = total bits of read data
else
* pOutLenBit = ucN * 8; //The last received byte is entirely valid
if ( ucN == 0 )
ucN = 1;
if ( ucN > MAXRLEN )
ucN = MAXRLEN;
for ( ul = 0; ul < ucN; ul ++ )
pOutData [ ul ] = RC522_Read_Register ( FIFODataReg );
}
}
else
cStatus = MI_ERR;
}
RC522_SetBit_Register ( ControlReg, 0x80 ); // stop timer now
RC522_Write_Register ( CommandReg, PCD_IDLE );
return cStatus;
}
/**
* @brief : Seek card
* @param ucReq_code, seek card method
* = 0x52: Seek all cards conforming to 14443A standard within sensing area
* = 0x26: Seek cards not in sleep state
* pTagType, card type code
* = 0x4400: Mifare_UltraLight
* = 0x0400: Mifare_One(S50)
* = 0x0200: Mifare_One(S70)
* = 0x0800: Mifare_Pro(X))
* = 0x4403: Mifare_DESFire
* @retval : Status value MI_OK, success
*/
char PcdRequest ( uint8_t ucReq_code, uint8_t * pTagType )
{
char cStatus;
uint8_t ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
RC522_ClearBit_Register ( Status2Reg, 0x08 ); //Clear indication that MIFARECyptol unit is connected and all card data communication is encrypted
RC522_Write_Register ( BitFramingReg, 0x07 ); // Seven bits of the last byte sent
RC522_SetBit_Register ( TxControlReg, 0x03 ); //The output signals of TX1 and TX2 pins transmit modulated 13.56 energy carrier signals
ucComMF522Buf [ 0 ] = ucReq_code; //Store seek card method
/* PCD_TRANSCEIVE: command to send and receive data, RC522 sends seek card command to the card, the card returns the card model code to ucComMF522Buf */
cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 1, ucComMF522Buf, & ulLen ); //Seek card
if ( ( cStatus == MI_OK ) && ( ulLen == 0x10 ) ) //Seek card successful, returns card type
{
/* Receive card model code */
* pTagType = ucComMF522Buf [ 0 ];
* ( pTagType + 1 ) = ucComMF522Buf [ 1 ];
}
else
{
cStatus = MI_ERR;
}
return cStatus;
}
/**
* @brief : Anti-collision
* @param : Snr: Card serial number, 4 bytes, will return the serial number of the selected card
* @retval : Status value MI_OK, success
*/
char PcdAnticoll ( uint8_t * pSnr )
{
char cStatus;
uint8_t uc, ucSnr_check = 0;
uint8_t ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
RC522_ClearBit_Register ( Status2Reg, 0x08 ); //Clear MFCryptol On bit, only after successful execution of MFAuthent command can this bit be set
RC522_Write_Register ( BitFramingReg, 0x00); //Clear register, stop transceiving
RC522_ClearBit_Register ( CollReg, 0x80 ); //Clear ValuesAfterColl, all received bits after collision are cleared
ucComMF522Buf [ 0 ] = 0x93; //Card anti-collision command
ucComMF522Buf [ 1 ] = 0x20;
/* Send the card anti-collision command to the card through RC522, returns the serial number of the selected card */
cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 2, ucComMF522Buf, & ulLen);//Communicate with card
if ( cStatus == MI_OK) //Communication successful
{
for ( uc = 0; uc < 4; uc ++ )
{
* ( pSnr + uc ) = ucComMF522Buf [ uc ]; //Read UID
ucSnr_check ^= ucComMF522Buf [ uc ];
}
if ( ucSnr_check != ucComMF522Buf [ uc ] )
cStatus = MI_ERR;
}
RC522_SetBit_Register ( CollReg, 0x80 );
return cStatus;
}
/**
* @brief : Use RC522 to calculate CRC16 (cyclic redundancy check)
* @param : pIndata: Array to calculate CRC16
* ucLen: Byte length of array to calculate CRC16
* pOutData: Start address to store calculation results
* @retval : Status value MI_OK, success
*/
void CalulateCRC ( uint8_t * pIndata, u8 ucLen, uint8_t * pOutData )
{
uint8_t uc, ucN;
RC522_ClearBit_Register(DivIrqReg,0x04);
RC522_Write_Register(CommandReg,PCD_IDLE);
RC522_SetBit_Register(FIFOLevelReg,0x80);
for ( uc = 0; uc < ucLen; uc ++)
RC522_Write_Register ( FIFODataReg, * ( pIndata + uc ) );
RC522_Write_Register ( CommandReg, PCD_CALCCRC );
uc = 0xFF;
do
{
ucN = RC522_Read_Register ( DivIrqReg );
uc --;
} while ( ( uc != 0 ) && ! ( ucN & 0x04 ) );
pOutData [ 0 ] = RC522_Read_Register ( CRCResultRegL );
pOutData [ 1 ] = RC522_Read_Register ( CRCResultRegM );
}
/**
* @brief : Select card
* @param : pSnr: Card serial number, 4 bytes
* @retval : Status value MI_OK, success
*/
char PcdSelect ( uint8_t * pSnr )
{
char ucN;
uint8_t uc;
uint8_t ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
/* PICC_ANTICOLL1: Anti-collision command */
ucComMF522Buf [ 0 ] = PICC_ANTICOLL1;
ucComMF522Buf [ 1 ] = 0x70;
ucComMF522Buf [ 6 ] = 0;
for ( uc = 0; uc < 4; uc ++ )
{
ucComMF522Buf [ uc + 2 ] = * ( pSnr + uc );
ucComMF522Buf [ 6 ] ^= * ( pSnr + uc );
}
CalulateCRC ( ucComMF522Buf, 7, & ucComMF522Buf [ 7 ] );
RC522_ClearBit_Register ( Status2Reg, 0x08 );
ucN = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 9, ucComMF522Buf, & ulLen );
if ( ( ucN == MI_OK ) && ( ulLen == 0x18 ) )
ucN = MI_OK;
else
ucN = MI_ERR;
return ucN;
}
/**
* @brief : Verify card password
* @param : ucAuth_mode: Password verification mode
* = 0x60, Verify Key A
* = 0x61, Verify Key B
* ucAddr: Block address
* pKey: Password
* pSnr: Card serial number, 4 bytes
* @retval : Status value MI_OK, success
*/
char PcdAuthState ( uint8_t ucAuth_mode, uint8_t ucAddr, uint8_t * pKey, uint8_t * pSnr )
{
char cStatus;
uint8_t uc, ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
ucComMF522Buf [ 0 ] = ucAuth_mode;
ucComMF522Buf [ 1 ] = ucAddr;
/* First two bytes store verification mode and block address, bytes 2~8 store password (6 bytes), bytes 8~14 store serial number */
for ( uc = 0; uc < 6; uc ++ )
ucComMF522Buf [ uc + 2 ] = * ( pKey + uc );
for ( uc = 0; uc < 6; uc ++ )
ucComMF522Buf [ uc + 8 ] = * ( pSnr + uc );
/* Perform redundancy check, bytes 14~16 store verification results */
cStatus = PcdComMF522 ( PCD_AUTHENT, ucComMF522Buf, 12, ucComMF522Buf, & ulLen );
/* Determine whether verification was successful */
if ( ( cStatus != MI_OK ) || ( ! ( RC522_Read_Register ( Status2Reg ) & 0x08 ) ) )
cStatus = MI_ERR;
return cStatus;
}
/**
* @brief : Write specified data to a specified block address of M1 card
* @param : ucAddr: Block address
* pData: Data to write, 16 bytes
* @retval : Status value MI_OK, success
*/
char PcdWrite ( uint8_t ucAddr, uint8_t * pData )
{
char cStatus;
uint8_t uc, ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
ucComMF522Buf [ 0 ] = PICC_WRITE;//Write block command
ucComMF522Buf [ 1 ] = ucAddr;//Write block address
/* Perform cyclic redundancy check, store the result in & ucComMF522Buf [ 2 ] */
CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );
/* PCD_TRANSCEIVE: Send and receive data command, send write block command to the card through RC522 */
cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, & ulLen );
/* Based on the information returned by the card, determine whether RC522 communicated with the card normally */
if ( ( cStatus != MI_OK ) || ( ulLen != 4 ) || ( ( ucComMF522Buf [ 0 ] & 0x0F ) != 0x0A ) )
cStatus = MI_ERR;
if ( cStatus == MI_OK )
{
//memcpy(ucComMF522Buf, pData, 16);
/* Pass the 16 bytes of data to be written into the ucComMF522Buf array */
for ( uc = 0; uc < 16; uc ++ )
ucComMF522Buf [ uc ] = * ( pData + uc );
/* Redundancy check */
CalulateCRC ( ucComMF522Buf, 16, & ucComMF522Buf [ 16 ] );
/* Through RC522, write 16 bytes of data including 2 bytes of check result to the card */
cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 18, ucComMF522Buf, & ulLen );
/* Determine whether the write to address was successful */
if ( ( cStatus != MI_OK ) || ( ulLen != 4 ) || ( ( ucComMF522Buf [ 0 ] & 0x0F ) != 0x0A ) )
cStatus = MI_ERR;
}
return cStatus;
}
/**
* @brief : Read data from a specified block address of M1 card
* @param : ucAddr: Block address
* pData: Data read out, 16 bytes
* @retval : Status value MI_OK, success
*/
char PcdRead ( uint8_t ucAddr, uint8_t * pData )
{
char cStatus;
uint8_t uc, ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
ucComMF522Buf [ 0 ] = PICC_READ;
ucComMF522Buf [ 1 ] = ucAddr;
/* Redundancy check */
CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );
/* Pass the command to the card through RC522 */
cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, & ulLen );
/* If transmission is normal, pass the read data into pData */
if ( ( cStatus == MI_OK ) && ( ulLen == 0x90 ) )
{
for ( uc = 0; uc < 16; uc ++ )
* ( pData + uc ) = ucComMF522Buf [ uc ];
}
else
cStatus = MI_ERR;
return cStatus;
}
/**
* @brief : Put the card into sleep mode
* @param : None
* @retval : Status value MI_OK, success
*/
char PcdHalt( void )
{
uint8_t ucComMF522Buf [ MAXRLEN ];
uint32_t ulLen;
ucComMF522Buf [ 0 ] = PICC_HALT;
ucComMF522Buf [ 1 ] = 0;
CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );
PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, & ulLen );
return MI_OK;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
In the file bsp_rc522.h, write the following code.
/*
* LCSC-Openkits (LCKFB) software and hardware materials and related expansion board software and hardware materials are all open source on the official website.
* Dev board official website: www.lckfb.com
* Technical support resides on the forum; any technical questions are welcome for exchange and learning at any time.
* LCKFB Forum: club.szlcsc.com
* Follow our Bilibili account: [LCSC-Openkits (LCKFB)] to keep up with our latest updates!
* We do not make money by selling boards; we take cultivating engineers as our mission.
* Change Logs:
* Date Author Notes
* 2024-01-10 LCKFB-lp first version
*/
#ifndef _BSP_RC522_H
#define _BSP_RC522_H
#include "driver/i2c.h"
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "freertos/queue.h"
#include <inttypes.h>
#include "sdkconfig.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "rom/ets_sys.h"
#include "esp_system.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "driver/spi_common.h"
#include "hal/gpio_types.h"
#ifndef u8
#define u8 uint8_t
#endif
#ifndef u16
#define u16 uint16_t
#endif
#ifndef u32
#define u32 uint32_t
#endif
// SDA/CS
#define GPIO_CS 1
//SCK
#define GPIO_SCK 2
//MOSI
#define GPIO_MOSI 3
//RST
#define GPIO_RST 5
//MISO
#define GPIO_MISO 4
/* IO port operation functions */
#define RC522_CS_Enable() gpio_set_level(GPIO_CS, 0)
#define RC522_CS_Disable() gpio_set_level(GPIO_CS, 1)
#define RC522_Reset_Enable() gpio_set_level(GPIO_RST, 0)
#define RC522_Reset_Disable() gpio_set_level(GPIO_RST, 1)
#define RC522_SCK_0() gpio_set_level(GPIO_SCK, 0)
#define RC522_SCK_1() gpio_set_level(GPIO_SCK, 1)
#define RC522_MOSI_0() gpio_set_level(GPIO_MOSI, 0)
#define RC522_MOSI_1() gpio_set_level(GPIO_MOSI, 1)
#define RC522_MISO_GET() gpio_get_level(GPIO_MISO)
//RC522 command words
#define PCD_IDLE 0x00 //Cancel current command
#define PCD_AUTHENT 0x0E //Verify key
#define PCD_RECEIVE 0x08 //Receive data
#define PCD_TRANSMIT 0x04 //Send data
#define PCD_TRANSCEIVE 0x0C //Send and receive data
#define PCD_RESETPHASE 0x0F //Reset
#define PCD_CALCCRC 0x03 //CRC calculation
//Mifare_One card command words
#define PICC_REQIDL 0x26 //Seek cards not in sleep state within antenna area
#define PICC_REQALL 0x52 //Seek all cards within antenna area
#define PICC_ANTICOLL1 0x93 //Anti-collision
#define PICC_ANTICOLL2 0x95 //Anti-collision
#define PICC_AUTHENT1A 0x60 //Verify Key A
#define PICC_AUTHENT1B 0x61 //Verify Key B
#define PICC_READ 0x30 //Read block
#define PICC_WRITE 0xA0 //Write block
#define PICC_DECREMENT 0xC0 //Decrement
#define PICC_INCREMENT 0xC1 //Increment
#define PICC_RESTORE 0xC2 //Transfer block data to buffer
#define PICC_TRANSFER 0xB0 //Save data in buffer
#define PICC_HALT 0x50 //Sleep
/* RC522 FIFO length definition */
#define DEF_FIFO_LENGTH 64 //FIFO size=64byte
#define MAXRLEN 18
/* RC522 register definitions */
// PAGE 0
#define RFU00 0x00 //Reserved
#define CommandReg 0x01 //Start and stop command execution
#define ComIEnReg 0x02 //Enable/Disable interrupt request passing
#define DivlEnReg 0x03 //Enable interrupt request passing
#define ComIrqReg 0x04 //Contains interrupt request flags
#define DivIrqReg 0x05 //Contains interrupt request flags
#define ErrorReg 0x06 //Error flag, indicates the error status of the last executed command
#define Status1Reg 0x07 //Contains communication status identifiers
#define Status2Reg 0x08 //Contains receiver and transmitter status flags
#define FIFODataReg 0x09 //Input and output of 64-byte FIFO buffer
#define FIFOLevelReg 0x0A //Indicates the number of bytes stored in FIFO
#define WaterLevelReg 0x0B //Defines FIFO depth for underflow and overflow alarms
#define ControlReg 0x0C //Various control registers
#define BitFramingReg 0x0D //Adjustment for bit-oriented framing
#define CollReg 0x0E //Position of the first bit collision detected on the RF interface
#define RFU0F 0x0F //Reserved
// PAGE 1
#define RFU10 0x10 //Reserved
#define ModeReg 0x11 //Defines common send and receive modes
#define TxModeReg 0x12 //Defines data transmission rate during transmission
#define RxModeReg 0x13 //Defines data transmission rate during reception
#define TxControlReg 0x14 //Controls the logical characteristics of antenna driver pins TX1 and TX2
#define TxAutoReg 0x15 //Controls antenna driver settings
#define TxSelReg 0x16 //Selects the internal source of the antenna driver
#define RxSelReg 0x17 //Selects internal receiver settings
#define RxThresholdReg 0x18 //Selects the threshold of the bit decoder
#define DemodReg 0x19 //Defines demodulator settings
#define RFU1A 0x1A //Reserved
#define RFU1B 0x1B //Reserved
#define MifareReg 0x1C //Controls 106kbit/s communication in ISO 14443/MIFARE mode
#define RFU1D 0x1D //Reserved
#define RFU1E 0x1E //Reserved
#define SerialSpeedReg 0x1F //Selects the rate of the serial UART interface
// PAGE 2
#define RFU20 0x20 //Reserved
#define CRCResultRegM 0x21 //Displays the actual MSB value of CRC calculation
#define CRCResultRegL 0x22 //Displays the actual LSB value of CRC calculation
#define RFU23 0x23 //Reserved
#define ModWidthReg 0x24 //Controls ModWidth settings
#define RFU25 0x25 //Reserved
#define RFCfgReg 0x26 //Configures receiver gain
#define GsNReg 0x27 //Selects modulation conductance of antenna driver pins (TX1 and TX2)
#define CWGsCfgReg 0x28 //Selects modulation conductance of antenna driver pins
#define ModGsCfgReg 0x29 //Selects modulation conductance of antenna driver pins
#define TModeReg 0x2A //Defines internal timer settings
#define TPrescalerReg 0x2B //Defines internal timer settings
#define TReloadRegH 0x2C //Describes 16-bit timer reload value
#define TReloadRegL 0x2D //Describes 16-bit timer reload value
#define TCounterValueRegH 0x2E
#define TCounterValueRegL 0x2F //Displays actual 16-bit timer value
// PAGE 3
#define RFU30 0x30 //Reserved
#define TestSel1Reg 0x31 //Common test signal configuration
#define TestSel2Reg 0x32 //Common test signal configuration and PRBS control
#define TestPinEnReg 0x33 //Enable pins for D1-D7 output drivers (only for serial interface)
#define TestPinValueReg 0x34 //Defines values when D1-D7 are used as I/O bus
#define TestBusReg 0x35 //Displays internal test bus status
#define AutoTestReg 0x36 //Controls digital self-test
#define VersionReg 0x37 //Displays version
#define AnalogTestReg 0x38 //Controls pins AUX1 and AUX2
#define TestDAC1Reg 0x39 //Defines test value of TestDAC1
#define TestDAC2Reg 0x3A //Defines test value of TestDAC2
#define TestADCReg 0x3B //Displays actual values of ADCI and Q channels
#define RFU3C 0x3C //Reserved
#define RFU3D 0x3D //Reserved
#define RFU3E 0x3E //Reserved
#define RFU3F 0x3F //Reserved
/* Error codes returned when communicating with RC522 */
#define MI_OK 0x26
#define MI_NOTAGERR 0xcc
#define MI_ERR 0xbb
/**********************************************************************/
void RC522_Init(void);/* IO port initialization */
////////////////Software-simulated SPI communication with RC522///////////////////////////////////////////
void RC522_SPI_SendByte( uint8_t byte );/* Software-simulated SPI sends one byte of data, MSB first */
uint8_t RC522_SPI_ReadByte( void );/* Software-simulated SPI reads one byte of data, reads MSB first */
uint8_t RC522_Read_Register( uint8_t Address );//Read the value of a specified RC522 register
void RC522_Write_Register( uint8_t Address, uint8_t data );//Write specified data to a specified RC522 register
void RC522_SetBit_Register( uint8_t Address, uint8_t mask );//Set a specified bit of a specified RC522 register
void RC522_ClearBit_Register( uint8_t Address, uint8_t mask );//Clear a specified bit of a specified RC522 register
/////////////////////GD32 basic communication with RC522///////////////////////////////////
void RC522_Antenna_On( void );//Turn on antenna
void RC522_Antenna_Off( void );//Turn off antenna
void RC522_Rese( void );//Reset RC522
void RC522_Config_Type( char Type );//Set RC522 working mode
/////////////////////////GD32 controls RC522 to communicate with M1///////////////////////////////////////
char PcdComMF522 ( uint8_t ucCommand, uint8_t * pInData, uint8_t ucInLenByte, uint8_t * pOutData, uint32_t * pOutLenBit );//Communicate with ISO14443 card through RC522
char PcdRequest ( uint8_t ucReq_code, uint8_t * pTagType );//Seek card
char PcdAnticoll ( uint8_t * pSnr );//Anti-collision
void CalulateCRC ( uint8_t * pIndata, u8 ucLen, uint8_t * pOutData );//Use RC522 to calculate CRC16 (cyclic redundancy check)
char PcdSelect ( uint8_t * pSnr );//Select card
char PcdAuthState ( uint8_t ucAuth_mode, uint8_t ucAddr, uint8_t * pKey, uint8_t * pSnr );//Verify card password
char PcdWrite ( uint8_t ucAddr, uint8_t * pData );//Write specified data to a specified block address of M1 card
char PcdRead ( uint8_t ucAddr, uint8_t * pData );//Read data from a specified block address of M1 card
char PcdHalt( void );//Put the card into sleep mode
void delay_1ms(unsigned int ms);
void delay_ms(unsigned int ms);
void delay_1us(unsigned int us);
void delay_us(unsigned int us);
#endif2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
Porting Verification
In the main function of your own project, write the following code.
/*
* LCSC-Openkits (LCKFB) software and hardware materials and related expansion board software and hardware materials are all open source on the official website.
* Dev board official website: www.lckfb.com
* Technical support resides on the forum; any technical questions are welcome for exchange and learning at any time.
* LCKFB Forum: club.szlcsc.com
* Follow our Bilibili account: [LCSC-Openkits (LCKFB)] to keep up with our latest updates!
* We do not make money by selling boards; we take cultivating engineers as our mission.
* Change Logs:
* Date Author Notes
* 2024-01-10 LCKFB-lp first version
*/
#include <stdio.h>
#include "RC522_IC/bsp_rc522.h"
/* Card ID storage, 32 bits, 4 bytes */
u8 ucArray_ID [ 4 ];
uint8_t ucStatusReturn; //Return status
void app_main(void)
{
int i = 0;
uint8_t read_write_data[16]={0};//Read/write data buffer
uint8_t card_KEY[6] ={0xff,0xff,0xff,0xff,0xff,0xff};//Default password
printf ("Init\r\n");
RC522_Init( );//IC card IO port initialization
RC522_Rese( );//Reset RC522
printf ("Start\r\n");
while(1)
{
/* Seek card (method: all within range), if the first seek fails, try again. When successful, the card serial is passed into the ucArray_ID array */
if ( ( ucStatusReturn = PcdRequest ( PICC_REQALL, ucArray_ID ) ) != MI_OK )
{
ucStatusReturn = PcdRequest ( PICC_REQALL, ucArray_ID );
}
if ( ucStatusReturn == MI_OK )
{
/* Anti-collision operation, the selected card serial is passed into the ucArray_ID array */
if ( PcdAnticoll ( ucArray_ID ) == MI_OK )
{
//Output card ID
printf("ID: %X %X %X %X\r\n", ucArray_ID [ 0 ], ucArray_ID [ 1 ], ucArray_ID [ 2 ], ucArray_ID [ 3 ]);
//Select card
if( PcdSelect(ucArray_ID) != MI_OK )
{ printf("PcdSelect failure\r\n"); }
//Verify card password
//Verify Key A of data block 6 (all passwords default to 16 bytes of 0xff)
if( PcdAuthState(PICC_AUTHENT1A, 6, card_KEY, ucArray_ID) != MI_OK )
{ printf("PcdAuthState failure\r\n"); }
//Write data read_write_data to data block 4
read_write_data[0] = 0xaa;//Change the first byte of read_write_data to 0xaa
if( PcdWrite(4,read_write_data) != MI_OK )
{ printf("PcdWrite failure\r\n"); }
//Fill the 16 bytes of read_write_data with 0 (clear data)
for(int i = 0; i < 16; i++)
{
read_write_data[i] = 0;
}
delay_us(8);
//Read data from data block 4
if( PcdRead(4,read_write_data) != MI_OK )
{ printf("PcdRead failure\r\n"); }
//Output the read data
for( i = 0; i < 16; i++ )
{
printf("%x ",read_write_data[i]);
}
printf("\r\n");
}
}
delay_ms(50);
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
Power-on effect: Place the IC card on the RC522 for one or two seconds.
Driver code:
File Download
📌 Materials Download Center (click to jump)
📌 In the Materials Download Center -> Module Porting Materials Download, inside the compressed package of this chapter.