wch-code/ch32v103_hallarray_controller/src/user/bsp_uart1.c

66 lines
3.0 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "bsp_uart1.h"
#include <stdio.h>
void bsp_uart1_init(uint32_t baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //USART1_TX=PA9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //USART1_TX=PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
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_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE); //使能UART1的DMA发送
DMA_InitTypeDef DMA_InitStructure;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART1->DATAR; //USART1数据寄存器地址
DMA_InitStructure.DMA_MemoryBaseAddr = 0; //数据缓冲区地址
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST; //外设->内存方向
DMA_InitStructure.DMA_BufferSize = 0; //缓冲区大小
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_Medium; //中优先级
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; //非内存到内存传输
DMA_Init(DMA1_Channel4, &DMA_InitStructure);
}
void bsp_uart1_send(uint8_t *buffer, uint16_t size)
{
static uint8_t skip_first_wait = 1;
while (DMA_GetFlagStatus(DMA1_FLAG_TC4) == RESET) { //等待传输完成
if (skip_first_wait != 0) {
skip_first_wait = 0;
break;
}
}
DMA_ClearFlag(DMA1_FLAG_TC4); //清除传输完成标志
DMA_Cmd(DMA1_Channel4, DISABLE); //禁用DMA通道4
DMA1_Channel4->MADDR = (uint32_t)buffer; //设置DMA传输的内存地址
DMA1_Channel4->CNTR = size; //设置DMA传输数据长度
DMA_Cmd(DMA1_Channel4, ENABLE); //使能DMA通道4开始发送
}