注:
<1> SPI不存在在中断读写,SPI通信时序是读的同时写,写的同时读,读写不分离,所以没必要配置中断。
1、SPI初始化
/*******************************************************************************
* function name : SPI1_Init
* brief : SPI1 initialize
* param[in] : None
* param[out] : None
* retval : None
* attention : None
*******************************************************************************/
void SPI1_Init(void)
{
spi_parameter_struct spi_init_s;
rcu_periph_clock_enable(RCU_GPIOB);
rcu_periph_clock_enable(RCU_SPI1);
rcu_periph_clock_enable(RCU_AF);
/* SPI1_SCK(PB3), SPI1_MISO(PB4) and SPI1_MOSI(PB5) GPIO pin configuration */
gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_MAX, GPIO_PIN_3 | GPIO_PIN_5);
gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_MAX, GPIO_PIN_4);
/* SPI0_CS(PB2) GPIO pin configuration */
gpio_init(GPIOB, GPIO_MODE_OUT_PP, GPIO_OSPEED_MAX, GPIO_PIN_2);
/* chip select invalid*/
gpio_bit_set(GPIOB, GPIO_PIN_2);
/* SPI1 parameter config */
spi_init_s.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
spi_init_s.device_mode = SPI_MASTER;
spi_init_s.frame_size = SPI_FRAMESIZE_8BIT;
spi_init_s.clock_polarity_phase = SPI_CK_PL_HIGH_PH_2EDGE; //mode3
spi_init_s.nss = SPI_NSS_SOFT;
spi_init_s.prescale = SPI_PSC_16;
spi_init_s.endian = SPI_ENDIAN_MSB;
spi_init(SPI1, &spi_init_s);
/* enable SPI1 */
spi_enable(SPI1);
}
2、SPI写
/*******************************************************************************
* Function Name : SPI_WR_byte
* Brief : SPI1 read/write byte
* Param[in] : byte
* Param[out] : none
* Retval : none
* Attention : none
*******************************************************************************/
uint8_t SPI_RW_byte (uint8_t byte)
{
/* loop while data register in not emplty */
while (RESET == spi_i2s_flag_get(SPI1, SPI_FLAG_TBE));
/* send byte through the SPI0 peripheral */
spi_i2s_data_transmit(SPI1, byte);
/* wait to receive a byte */
while(RESET == spi_i2s_flag_get(SPI1, PI_FLAG_RBNE));
/* return the byte read from the SPI bus */
return (spi_i2s_data_receive(SPI1));
}
/*******************************************************************************
* Function Name : SPIWrite
* Brief : SPIWrite
* Param[in] : byte
* Param[out] : none
* Retval : none
* Attention : none
*******************************************************************************/
void SPIWrite(UINT8 data)
{
SPI_RW_byte(data);
}
3、SPI读
/*******************************************************************************
* Function Name : SPIRead
* Brief : SPIRead
* Param[in] : byte
* Param[out] : none
* Retval : none
* Attention : none
*******************************************************************************/
UINT8 SPIRead(void)
{
UINT8 data;
data = SPI_RW_byte(0);
return (data);
}