void SPI1_Configuration(void)
{
GPIO_Config_T gpioConfig;
SPI_Config_T spiConfig;
/* Enable related Clock */
RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_SPI1);
RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_GPIOA);
RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_AFIO);
//RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_SYSCFG);
/* config PIN_6 MISO */
gpioConfig.pin = GPIO_PIN_6 ;
gpioConfig.mode = GPIO_MODE_IN_PD;//GPIO_Mode_IPD//下拉输入模式
gpioConfig.speed = GPIO_SPEED_50MHz;
GPIO_Config(GPIOA, &gpioConfig);
/* config PIN_5->SCK , PIN_7->MOSI */
gpioConfig.pin = GPIO_PIN_5 | GPIO_PIN_7;
gpioConfig.mode = GPIO_MODE_AF_PP;//GPIO_Mode_AF_PP//复用推挽输出模式
gpioConfig.speed = GPIO_SPEED_50MHz;
GPIO_Config(GPIOA, &gpioConfig);
/* config PIN_4->NSS片选 */
gpioConfig.pin = GPIO_PIN_4;
gpioConfig.mode = GPIO_MODE_OUT_PP;
gpioConfig.speed = GPIO_SPEED_50MHz;
GPIO_Config(GPIOA, &gpioConfig);
GPIO_SetBit(GPIOA,GPIO_PIN_4);//拉高片选
spiConfig.baudrateDiv = SPI_BAUDRATE_DIV_64;//波特率
spiConfig.crcPolynomial = 7;//CRC计算多项式
spiConfig.direction = SPI_DIRECTION_2LINES_FULLDUPLEX;//全双工模式
spiConfig.firstBit = SPI_FIRSTBIT_MSB;//数据传输从MSB开始
spiConfig.length = SPI_DATA_LENGTH_8B;//8字节数据通信
spiConfig.mode = SPI_MODE_MASTER;//配置为主机模式
spiConfig.nss = SPI_NSS_SOFT;//软件控制NSS(CSN)位
spiConfig.phase = SPI_CLKPHA_1EDGE;//时钟奇数边沿采样
spiConfig.polarity = SPI_CLKPOL_LOW;//时钟空闲时为低电平
SPI_ConfigStructInit(&spiConfig);
/* SPI config */
SPI_Config(SPI1, &spiConfig);
SPI_ConfigDataSize(SPI1, SPI_DATA_LENGTH_8B);
SPI_Enable(SPI1);
}
unsigned char SPI1_ReadWriteByte(unsigned char TxData)
{
unsigned char RxData;
uint32_t SPITimeout = 0x1000;
while (SPI_I2S_ReadStatusFlag(SPI1, SPI_FLAG_TXBE) == RESET) //检测发送缓存区是否为空
{
if((SPITimeout--) == 0)
return 0;
}
SPI1->DATA = TxData;
while (SPI_I2S_ReadStatusFlag(SPI1, SPI_FLAG_RXBNE) == RESET) //检测接收缓存区是否为空
{
if((SPITimeout--) == 0) return 0;
}
RxData = SPI1->DATA;
return RxData;
} |