STM32的SPI3使用DMA的程序
时间: 2024-03-25 22:35:54 浏览: 94
以下是一个使用STM32的SPI3和DMA控制器进行数据传输的程序:
```c
#include "stm32f4xx.h"
#define BUFFER_SIZE 100
uint8_t txBuffer[BUFFER_SIZE];
uint8_t rxBuffer[BUFFER_SIZE];
void SPI3_DMA_Init(void)
{
// 使能SPI3和DMA2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI3, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
// 配置SPI3的GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置SPI3的工作模式
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_256;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI3, &SPI_InitStructure);
// 配置DMA2_Stream2
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_Channel = DMA_Channel_0;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&SPI3->DR;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)rxBuffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream2, &DMA_InitStructure);
// 使能DMA2_Stream2和SPI3的DMA接收
DMA_Cmd(DMA2_Stream2, ENABLE);
SPI_I2S_DMACmd(SPI3, SPI_I2S_DMAReq_Rx, ENABLE);
// 使能SPI3
SPI_Cmd(SPI3, ENABLE);
}
int main(void)
{
// 初始化SPI3和DMA2
SPI3_DMA_Init();
// 初始化发送缓冲区
for (int i = 0; i < BUFFER_SIZE; i++) {
txBuffer[i] = i;
}
// 发送数据
while (1) {
SPI_I2S_DMACmd(SPI3, SPI_I2S_DMAReq_Tx, ENABLE);
DMA_Cmd(DMA2_Stream2, DISABLE);
DMA_SetCurrDataCounter(DMA2_Stream2, BUFFER_SIZE);
DMA_Cmd(DMA2_Stream2, ENABLE);
// 等待传输完成
while (DMA_GetFlagStatus(DMA2_Stream2, DMA_FLAG_TCIF2) == RESET) {}
// 清除传输完成标志位
DMA_ClearFlag(DMA2_Stream2, DMA_FLAG_TCIF2);
}
}
```
在该程序中,首先通过SPI3和DMA2初始化函数进行初始化,然后通过循环向SPI3发送数据,发送数据的过程中,先使能SPI3的DMA发送请求,然后等待传输完成。在传输完成时,需要清除DMA传输完成标志位,以便下一次传输。
阅读全文