串口DMA空闲(IDLE)中断接收
写在前面
- 使用本章教程前需要在111、STM32CubeMX使用printf打印单片机占用率或 110、STM32CubeMX串口DMA发送重定义的基础上进行
- 实现串口不定长DMA接收,减少中断或应用层代码
- stm32历史文章:https://blog.csdn.net/JiaLu0216/article/details/115471382
CubeMx FreeRTOS配置
- 打开CubeMX工程后选择Middleware->FREERTOS选项
- 在Configuration对话框中选择Timers and Semaphores页,在Binary Semaphores任务框中点击添加按钮进行添加任务
1、Semaphore Name :信号量名字
2、Allocation :是否采用外部内存分配堆栈,一般采用系统内部总堆进行分配
CubeMX USART配置
- 根据自己板子选择对应串口,本例程采用串口2,选择Connectivityt->USART2选项
- DMA配置,在Configuration选择框中选择DMA Settings页,选择添加按钮,上方会添加一个对话框,在对话框中选择USART2_TX
- DMA模式选择正常模式Mode :Normal,地址子增选择内存Increment Address :Memory
- 传输数据大小选择字节,Data Width :Byte
5. 在Configuration选择框中选择GPIO Settings页,检测配置的外部GPIO口是否正确,否则在右侧芯片图进行重新选择引脚
6. 中断配置,在Configuration选择框中选择NVIC Settings页,中断接面选择DMA中断,串口中断打开
BSP文件编写
- bsp_uart.h
#ifndef __BSP_UART_H
#define __BSP_UART_H
#include "main.h"
#define UART2_RX_MAX_FPS 2 //接收缓存帧数,
#define UART2_RX_MAX_LEN 400 //接收总缓存会*UART2_RX_MAX_FPS
#define UART2_TX_MAX_LEN 400 //发送最大长度
typedef struct
{
uint8_t rx_data_fps; //当前正在接收缓存帧
uint16_t rx_data_len; //接收数据长度
uint8_t *rx_data; //接收缓存区首地址
uint8_t *tx_data; //发送缓存区首地址
uint32_t rx_time_difference; //于上次接收数据时间差
uint32_t rx_last_time; //当前接收时间
}UartHead;
typedef struct
{
uint16_t rx_data_len; //接收数据长度
uint8_t *rx_data; //接收缓存区首地址
uint32_t rx_time_difference; //于上次接收数据时间差
uint32_t rx_last_time; //当前接收时间
}UartRxData;
typedef struct
{
UartHead uart2_head;
}BspUartStr;
uint8_t BspUartInit(void);
void BspUartDeInit(void);
uint8_t BspUart2Init(void);
void BspUart2DeInit(void);
void printf2(char* fmt,...);
void BspUsrtIrqHandler(UART_HandleTypeDef *huart);
uint8_t BspGetUart2RxData(UartRxData *uart_rx);
#endif
- bsp_uart.c
#include "bsp_uart.h"
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
#include "stdarg.h"
#include "stdio.h"
#include "string.h"
#include "usart.h"
#include "semphr.h"
#include <stdarg.h>
extern UART_HandleTypeDef huart2;
extern osSemaphoreId_t uart2TxIdleBinarySemHandle;
extern osSemaphoreId_t uart2RxIdleBinarySemHandle;
BspUartStr* bsp_uart_str = NULL;
/**
* @name:
* @description: 串口初始化,其中包含内存申请
* @msg:
* @param {*}
* @return {*} 0: 初始成功 bit 0 : 1结构体内存申请失败
* bit 1 : 1发送数据缓存内存申请失败
* bit 2 : 1接收数据缓存内存申请失败
*/
uint8_t BspUartInit(void)
{
if(bsp_uart_str != NULL)
BspUartDeInit();
bsp_uart_str = pvPortMalloc(sizeof(BspUartStr));
if(bsp_uart_str == NULL)
return 1;
bsp_uart_str->uart2_head.rx_data = NULL;
return BspUart2Init