写一个stm32下的SPI驱动代码
时间: 2023-03-10 20:54:37 浏览: 201
STM32 SPI驱动代码
请参考下面的代码:// Initialize SPI
// SPIx is the SPI peripheral e.g. SPI1
void SPI_init (SPI_TypeDef* SPIx){
// Enable clock for SPIx
if (SPIx == SPI1)
RCC_APB2PeriphClockCmd (RCC_APB2Periph_SPI1, ENABLE);
else if (SPIx == SPI2)
RCC_APB1PeriphClockCmd (RCC_APB1Periph_SPI2, ENABLE); // Set MOSI, MISO and SCK as AF
GPIO_PinAFConfig (GPIOA, GPIO_PinSource7, GPIO_AF_SPI1);
GPIO_PinAFConfig (GPIOA, GPIO_PinSource6, GPIO_AF_SPI1);
GPIO_PinAFConfig (GPIOA, GPIO_PinSource5, GPIO_AF_SPI1);
// Configure SPI pins: SCK, MISO and MOSI
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init (GPIOA, &GPIO_InitStructure);
// SPI configuration
SPI_InitTypeDef SPI_InitStructure;
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_Init (SPIx, &SPI_InitStructure);
// Enable SPIx
SPI_Cmd (SPIx, ENABLE);
}// SPI write and read
// SPIx is the SPI peripheral e.g. SPI1
// dataOut is the byte to transmit
// dataIn is the received byte
// return the received byte
uint8_t SPI_write_read (SPI_TypeDef* SPIx, uint8_t dataOut){
uint8_t dataIn;
// Wait until the transmit buffer is empty
while (SPI_I2S_GetFlagStatus (SPIx, SPI_I2S_FLAG_TXE) == RESET);
// Send the byte
SPI_I2S_SendData (SPIx, dataOut);
// Wait to receive a byte
while (SPI_I2S_GetFlagStatus (SPIx, SPI_I2S_FLAG_RXNE) == RESET);
// Return the byte read from the SPI bus
dataIn = SPI_I2S_ReceiveData (SPIx);
return dataIn;
}
阅读全文