可以看出 有两路spi,spi0和spi1,本节使用spi1。
开发板 rc522 PB12 <----------------------------->SDA(NSS) PB13 <----------------------------->SCK PB14 <----------------------------->MISO PB15 <----------------------------->MOSI PB0 <----------------------------->RST 3.3V <----------------------------->3V3 GND <----------------------------->GND
void SpiIoInit(void)
{
rcu_periph_clock_enable(RCU_GPIOB);
gpio_mode_set(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN_0 );
gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_0);
/* SPI1 GPIO configuration: NSS/PB12 */
gpio_mode_set(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN_12 );
gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_12);
/* SPI1 GPIO configuration: SCK/PB13, MISO/PB14, MOSI/PB15 */
gpio_af_set(GPIOB, GPIO_AF_6, GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);
gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);
gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);
}
void SpiInit(void)
{
spi_parameter_struct spi_init_struct;
rcu_periph_clock_enable(RCU_SPI1);
/* deinitilize SPI and the parameters */
spi_i2s_deinit(SPI1);
spi_struct_para_init(&spi_init_struct);
/* SPI1 parameter configuration */
spi_init_struct.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
spi_init_struct.device_mode = SPI_MASTER;
spi_init_struct.frame_size = SPI_FRAMESIZE_8BIT;
spi_init_struct.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
spi_init_struct.nss = SPI_NSS_SOFT;
spi_init_struct.prescale = SPI_PSC_8;
spi_init_struct.endian = SPI_ENDIAN_MSB;
spi_init(SPI1, &spi_init_struct);
spi_crc_polynomial_set(SPI1, 7);
spi_enable(SPI1);
}
uint8_t SPIWriteByte(uint8_t Byte)
{
uint16_t ret=0;
while(RESET == spi_i2s_flag_get(SPI1, SPI_FLAG_TBE)) {}; //等待发送区空
spi_i2s_data_transmit(SPI1, Byte); //发送一个byte
while(RESET == spi_i2s_flag_get(SPI1, SPI_FLAG_RBNE)) {}; //等待接收完一个byte
ret=spi_i2s_data_receive(SPI1); //返回收到的数据
return (ret&0x0ff);
}
void RC522Init(void)
{
uint8_t ver=0;
SpiIoInit();
SpiInit();
PcdReset();
ver=ReadRawRC(VersionReg);
if(ver==0x91||ver==0x92)
{
printf("rc522 exist\r\n");
}
else
{
printf("rc522 not exist\r\n");
}
PcdAntennaOff();
DelayMs(2);
PcdAntennaOn();
M500PcdConfigISOType( 'A' );
}
unsigned char CT[2];//卡类型
unsigned char SN[4]; //卡号
void RC522Polling(void)
{
unsigned char status;
uint8_t j;
status = PcdRequest(PICC_REQALL,CT);/*尋卡*/
if(status==MI_OK)//尋卡成功
{
status=MI_ERR;
status = PcdAnticoll(SN);/*防冲撞*/
}
if(status==MI_OK)//防衝撞成功
{
status=MI_ERR;
printf("\r\nThe Card ID is:");
for(j=0;j<4;j++)
{
printf("%02X",SN[j]);
}
printf("\r\n");
status =PcdSelect(SN);
}
}