STM32CubeMX USART串口DMA,IDLE 空闲中断接收不定长接收详解(stm32f407zg)
1.打开软件如下图;
2.选择单片机,如下图;
3.配置最大时钟,如下图
4.选择usart1,配置异步通讯,并在DMA settings下添加USART1_RX和USART1_TX,DMA模式选择NORMAL就行,如下图;
5.添加usart1中断,如下图;
6.配置路径,.c.h 后再点击GENERATE CODE
7.生成工程代码后,while上面初始化;
if (HAL_UART_Receive_DMA(&huart1, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}
__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);
//添加 #define RXBUFFERSIZE 50
//添加 uint8_t aRxBuffer[RXBUFFERSIZE];
/***************************下面添加printf第一段***************/
#ifdef __GNUC__
/* With GCC, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/***************************下面添加printf第二段***************/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
8.编写,声明,定义,调用 void HAL_UART_IdleCallback(UART_HandleTypeDef*huart);
/***************************下面main.h内添加函数声明***************/
void HAL_UART_IdleCallback(UART_HandleTypeDef*huart);
/***************************下面main.c内添加库函数***************/
#include "string.h"
#include "stdio.h"
/***************************下面main.c内添加编写的回调函数***************/
void HAL_UART_IdleCallback(UART_HandleTypeDef*huart)
{
//清除标志位
__HAL_UART_CLEAR_IDLEFLAG(huart);
//停止DMA接收
HAL_UART_DMAStop(huart);
//返回发送回的数据
printf("%s",aRxBuffer);
printf("Helloorld!\n");
//清除缓存区
memset(aRxBuffer,0x00,50);
//开始DMA接收
if(HAL_UART_Receive_DMA(huart,(uint8_t*)aRxBuffer,RXBUFFERSIZE)!=HAL_OK)
{
Error_Handler();
}
}
/***********下面stm32f4xx_it.c内void USART1_IRQHandler(void)中添加编写的回调函数***************/
if(__HAL_UART_GET_FLAG(&huart1,UART_FLAG_IDLE)!=RESET)
{
// HAL_UART_IdleCallback(&huart1);
HAL_UART_IdleCallback(&huart1); // HAL_IdleCallback(UART_HandleTypeDef*huart);
}
9.结束。 例:发送123。返回123 ; 发送5909.返回5909;
10. 添加DMA发送
10.1
添加:#define TXBUFFERSIZE 50
添加:uint8_t aTxBuffer[TXBUFFERSIZE];
开启发送中断:
HAL_UART_Transmit_DMA(&huart1, (uint8_t *)aTxBuffer, lslong);
__HAL_UART_ENABLE_IT(&huart1,UART_IT_TC);
添加 发送回调函数:
//发送结束回调函数,使能485接收;
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
//开始DMA接收
if(HAL_UART_Receive_DMA(huart,(uint8_t*)aRxBuffer,RXBUFFERSIZE)!=HAL_OK)
{
Error_Handler();
}
}