SPI是一种高速的,全双工,同步的通讯总线,原理和运用简略,占用引脚资源少,是一种常用的通讯方法。
STM32一般有2~3个SPI接口
依据STM32手册的运用方法:
1. Enable peripheral clock
2. Enable SCK, MOSI, MISO and NSS GPIO clocks
3. Peripherals alternate funcTIon:
? Connect the pin to the desired peripherals‘ Alternate FuncTIon (AF)
? Call GPIO_Init() funcTIon.
4. Program the Polarity, Phase, First Data, Baud Rate Prescaler, Slave Management,Peripheral Mode and CRC Polynomial values using the SPI_Init() funcTIon in SPI mode.
5. Configure the FIFO threshold using SPI_RxFIFOThresholdConfig() to select at which hreshold the RXNE event is generated.
6. Enable the NVIC and the corresponding interrupt using the function SPI_I2S_ITConfig() if you need to use interrupt mode.
7. When using the DMA mode
? Configure the DMA using DMA_Init() function.
? Active the needed channel Request using SPI_I2S_DMACmd() function.
8. Enable the SPI using the SPI_Cmd() function 。
9. Enable the DMA using the DMA_Cmd() function when using DMA mode.
10. To use the CRC Hardware calculation feature refer to the Peripheral CRC hardware Calculation subsection.
根据STM32F3discovery开发板,STM32F303VC
运用SPI1,从机衔接的是L3GD20陀螺仪,引脚衔接:
SPI1_MOSI——PA7
SPI1_SCK——PA5
SPI1_MISO——PA6
NSS——PE3
代码:
void SPI_GPIO_Config(void)
{
//将SPI1_MOSI—PA7,SPI1_SCK—PA5,SPI1_MISO—PA6引脚装备为对应复用功用
//NSS—PE3为从机片选引脚,装备为推挽输出
}
void SPI_Config(void)
{
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_Low; //结合从机挑选
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; //结合从机挑选
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_I2S_DeInit(SPI1);
SPI_Init(SPI1, &SPI_InitStructure);
SPI_RxFIFOThresholdConfig(SPI1, SPI_RxFIFOThreshold_QF);
SPI_Cmd(SPI1,ENABLE);
}
然后就能够用SPI接口进行收发数据,详细收发方法要依据从机设备决议
需求的时分能够装备中止,DMA等功用
发送或接纳数据前,先将相应从机的片选信号置零
SPI是两个设备移位寄存器的数据交换,接纳数据前先向从机发送虚拟字节,收到的数据便是所要读取的数据