基于固件库stm32f072 spi代码
时间: 2023-08-15 14:05:00 浏览: 208
以下是基于STM32固件库的STM32F072 SPI驱动代码示例:
```c
#include "stm32f0xx.h"
/* SPI GPIO configuration */
void MX_SPI_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
/* Configure SPI SCK, MOSI and MISO pins */
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStruct);
/* Connect SPI pins to AF */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource5, GPIO_AF_0); //SCK
GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_0); //MISO
GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_0); //MOSI
/* SPI configuration */
SPI_InitTypeDef SPI_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
SPI_InitStruct.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStruct.SPI_Mode = SPI_Mode_Master;
SPI_InitStruct.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStruct.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStruct.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStruct.SPI_NSS = SPI_NSS_Soft;
SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStruct.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStruct);
SPI_Cmd(SPI1, ENABLE);
}
/* SPI write function */
void SPI_Write(uint8_t *pData, uint16_t Size)
{
while (Size--)
{
/* Wait until TX buffer is empty */
while (!(SPI1->SR & SPI_SR_TXE));
/* Send data */
SPI1->DR = *pData++;
/* Wait until RX buffer is not empty */
while (!(SPI1->SR & SPI_SR_RXNE));
/* Read received data to clear RX buffer */
(void)SPI1->DR;
}
}
/* SPI read function */
void SPI_Read(uint8_t *pData, uint16_t Size)
{
while (Size--)
{
/* Wait until TX buffer is empty */
while (!(SPI1->SR & SPI_SR_TXE));
/* Send dummy data */
SPI1->DR = 0xFF;
/* Wait until RX buffer is not empty */
while (!(SPI1->SR & SPI_SR_RXNE));
/* Read received data */
*pData++ = SPI1->DR;
}
}
/* SPI write and read function */
void SPI_WriteRead(uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
{
while (Size--)
{
/* Wait until TX buffer is empty */
while (!(SPI1->SR & SPI_SR_TXE));
/* Send data */
SPI1->DR = *pTxData++;
/* Wait until RX buffer is not empty */
while (!(SPI1->SR & SPI_SR_RXNE));
/* Read received data */
*pRxData++ = SPI1->DR;
}
}
```
该代码同样实现了SPI1作为主设备,使用PA5、PA6、PA7分别作为SPI的时钟、数据输出和数据输入引脚,并且使用STM32固件库的相关API实现了SPI数据的发送和接收功能。同样只需根据具体的需求修改SPI的配置参数即可。
阅读全文