stm32hal库spi使用dma
时间: 2023-11-24 14:50:44 浏览: 466
以下是使用STM32 HAL库实现SPI+DMA的步骤:
1. 配置SPI外设和DMA通道
```c
SPI_HandleTypeDef hspi;
DMA_HandleTypeDef hdma_tx;
void MX_SPI_Init(void)
{
/* SPI2 parameter configuration*/
hspi.Instance = SPI2;
hspi.Init.Mode = SPI_MODE_MASTER;
hspi.Init.Direction = SPI_DIRECTION_2LINES;
hspi.Init.DataSize = SPI_DATASIZE_8BIT;
hspi.Init.CLKPolarity = SPI_POLARITY_LOW; hspi.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi.Init.NSS = SPI_NSS_SOFT;
hspi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
hspi.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi.Init.TIMode = SPI_TIMODE_DISABLE;
hspi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi.Init.CRCPolynomial = 7;
if (HAL_SPI_Init(&hspi) != HAL_OK)
{
Error_Handler();
}
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel5_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel5_IRQn);
/* DMA1_Channel5 init */
hdma_tx.Instance = DMA1_Channel5;
hdma_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_tx.Init.Mode = DMA_NORMAL;
hdma_tx.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&hspi, hdmatx, hdma_tx);
}
```
2. 配置DMA传输完成中断
```c
void DMA1_Channel5_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_tx);
}
```
3. 配置SPI发送函数
```c
uint8_t spi_tx_buf[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A};
void spi_send_data_dma(void)
{
HAL_SPI_Transmit_DMA(&hspi, spi_tx_buf, 10);
}
```
4. 在主函数中调用spi_send_data_dma()函数即可实现SPI+DMA传输。
阅读全文