stm32 DMA + 串口发送不定长数据 标准库函数代码
时间: 2023-09-10 07:08:00 浏览: 147
以下是一个基于STM32的DMA+串口发送不定长数据的示例代码,使用了标准库函数。
首先需要初始化串口和DMA:
```c
#include "stm32fxxx.h"
#include <string.h>
#define BUFFER_SIZE 256
uint8_t buffer[BUFFER_SIZE];
uint16_t buffer_length = 0;
void init_USART1(uint32_t baudrate)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = baudrate;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE);
USART_Cmd(USART1, ENABLE);
}
void init_DMA1(uint8_t* buffer, uint16_t length)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t) & (USART1->DR);
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t) buffer;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = length;
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_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel4, &DMA_InitStructure);
}
```
然后,可以编写一个函数来发送数据。该函数将数据添加到缓冲区中,并启动DMA传输:
```c
void send_data(uint8_t* data, uint16_t length)
{
if (length > BUFFER_SIZE) {
length = BUFFER_SIZE;
}
if (buffer_length + length > BUFFER_SIZE) {
length = BUFFER_SIZE - buffer_length;
}
memcpy(buffer + buffer_length, data, length);
buffer_length += length;
if (DMA_GetFlagStatus(DMA1_FLAG_TC4) == SET) {
DMA_Cmd(DMA1_Channel4, DISABLE);
DMA_SetCurrDataCounter(DMA1_Channel4, buffer_length);
DMA_Cmd(DMA1_Channel4, ENABLE);
buffer_length = 0;
}
}
```
在主函数中,可以使用此函数来发送数据:
```c
int main()
{
init_USART1(9600);
init_DMA1(buffer, 0);
uint8_t data[] = "Hello World!";
send_data(data, strlen(data));
while (1);
}
```
当缓冲区满时,DMA传输将启动。每次DMA传输完成时,都会重新启动DMA传输。
阅读全文