时钟配置HSI主频配置64M
配置好串口,选择异步模式
配置DMA TX,RX,选择循环模式。
NVIC中勾选使能中断
勾选生成独立的.c和h文件
配置好需要的开发环境并获取代码
串口重定向勾选Use Micro LIB
main.c文件修改
增加头文件和串口重定向
#include <string.h>
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
main函数修改
printf("hello world\r\n");
while (1)
{
if(USART1_RECV_FLAG == 1)
{
printf("rx_len = %d \r\n",USART1_RX_LEN);
HAL_UART_Transmit(&huart1,USART1_RX_BUF, USART1_RX_LEN,200);
memset(USART1_RX_BUF,0,USART1_RX_BUF_SIZE);
USART1_RX_LEN = 0;
USART1_RECV_FLAG = 0;
}
HAL_UART_Receive_DMA(&huart1,USART1_RX_BUF,USART1_RX_BUF_SIZE);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
usart.c文件修改
增加定义
uint8_t USART1_RX_LEN = 0;
uint8_t USART1_RECV_FLAG = 0;
uint8_t USART1_RX_BUF[USART1_RX_BUF_SIZE]={0};
修改void MX_USART1_UART_Init(void)函数
void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);
HAL_UART_Receive_DMA(&huart1,USART1_RX_BUF,USART1_RX_BUF_SIZE);
}
usart.h文件修改
增加头文件和定义声明
#include "stdio.h"
#define USART1_RX_BUF_SIZE 512
extern uint8_t USART1_RX_LEN;
extern uint8_t USART1_RECV_FLAG;
extern uint8_t USART1_RX_BUF[USART1_RX_BUF_SIZE];
stm32g0xx_it.c文件修改
增加头文件
#include "usart.h"
修改void USART1_IRQHandler(void)函数
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
uint32_t temp;
if((__HAL_UART_GET_FLAG(&huart1,UART_FLAG_IDLE) != RESET))
{
__HAL_UART_CLEAR_IDLEFLAG(&huart1);
HAL_UART_DMAStop(&huart1);
temp = __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
USART1_RX_LEN = USART1_RX_BUF_SIZE - temp;
USART1_RECV_FLAG = USART1_RX_LEN ? 1 : 0;
HAL_UART_Receive_DMA(&huart1,USART1_RX_BUF,USART1_RX_BUF_SIZE);
}
/* USER CODE END USART1_IRQn 1 */
}
编译后连上串口工具调试