TA的每日心情 | 奋斗 2017-5-1 09:20 |
---|
签到天数: 56 天 连续签到: 1 天 [LV.5]常住居民I
|
void SPI_RC522_Init(void)
{
GPIO_InitPara GPIO_InitStructure;
SPI_InitPara SPI_InitStructure;
RCC_AHBPeriphClock_Enable(RCC_AHBPERIPH_GPIOB, ENABLE);
RCC_APB2PeriphClock_Enable(RCC_APB2PERIPH_SPI1, ENABLE);
/* GPIO AF configuration */
GPIO_PinAFConfig(GPIOB, GPIO_PINSOURCE13, GPIO_AF_0);
GPIO_PinAFConfig(GPIOB, GPIO_PINSOURCE14, GPIO_AF_0);
GPIO_PinAFConfig(GPIOB, GPIO_PINSOURCE15, GPIO_AF_0);
/* SPI1_CLK(PB13), SPII_MISO(PB14) and SPII_MOSI(PB15) GPIO pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_50MHZ;
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OTYPE_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PUPD_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* SPII_CS(PD2) GPIO pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN_12;
GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_50MHZ;
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OTYPE_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PUPD_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* Chip select invalid*/
GPIO_SetBits(GPIOB, GPIO_PIN_12);
/* SPI1 configuration */
SPI_InitStructure.SPI_TransType = SPI_TRANSTYPE_FULLDUPLEX;
SPI_InitStructure.SPI_Mode = SPI_MODE_MASTER;
SPI_InitStructure.SPI_FrameFormat = SPI_FRAMEFORMAT_8BIT;
SPI_InitStructure.SPI_SCKPL = SPI_SCKPL_LOW;
SPI_InitStructure.SPI_SCKPH = SPI_SCKPH_1EDGE;
SPI_InitStructure.SPI_SWNSSEN = SPI_SWNSS_SOFT;
SPI_InitStructure.SPI_PSC = SPI_PSC_8;
SPI_InitStructure.SPI_FirstBit = SPI_FIRSTBIT_MSB;
SPI_InitStructure.SPI_CRCPOL = 7;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Enable(SPI1, ENABLE);
}
后面对RC522操作就简单了,直接使用固件库中SPI读写函数:
写一字节:
int32_t SPI_WriteByte(SPI_TypeDef* SPIx, uint16_t TxData)
{
uint8_t retry=0;
while (SPI_I2S_GetBitState(SPIx, SPI_FLAG_TBE) == RESET) //等待发送区空
{
retry++;
if(retry>200) return -1;
}
SPI_I2S_SendData(SPIx,TxData); //发送一个byte
}
读一字节:
注意该函数是接收缓存区返回的数据,对SPI接口没有操作。需要先检测是否收到数据
uint16_t SPI_ReadByte(SPI_TypeDef* SPIx)
{
uint8_t retry=0;
unit16_t result;
while (SPI_I2S_GetBitState(SPIx, SPI_FLAG_RBNE) == RESET) //等待接收完一个byte
{
retry++;
if(retry>200)return -1;
}
result=SPI_I2S_ReceiveData( SPIx );
return result; //返回收到的数据
}
|
|