STM32CubeMx 串口通信(下)串口接收

工作環(huán)境:
STM32CubeMXv6
Keil5
串口調(diào)試助手
????串口接收相對串口發(fā)送而言比較復(fù)雜,HAL_UART_Receive是阻塞式的發(fā)送,但是我們不可能讓一塊單片機(jī)一直進(jìn)行監(jiān)聽,通常而言我們都會采用終端的方法完成串口接收。
????Cube的基本配置和串口發(fā)送是一致的,但最后要添加終端的勾選。
????首先打開左側(cè)的下拉框Connectivity,點(diǎn)擊USART1選項(xiàng);

????在打開的選單中點(diǎn)擊Mode的下拉框,選中Asynchronous;
????

? ?在下方的配置框中選中Parameter Settings進(jìn)行配置:
????Baud Rate:波特率
????Word Length:字長
????Parity:?奇偶校驗(yàn)
????Stop Bits:停止位
????Data Directon:數(shù)據(jù)方向
????Over Sampling:超采樣
????Auto Baudrate:?自動波特率
????TX Pin Active Level Inversion:輸出引腳有效電平反轉(zhuǎn)
????RX Pin Active Level Inversion:輸入引腳有效電平反轉(zhuǎn)
????Data Inversion:數(shù)據(jù)反轉(zhuǎn)
????TX and RX Pin Swapping:輸出和輸入引腳交換
????DMA on RX Error:DMA接收錯誤
????MSB?First:MSB優(yōu)先(大端優(yōu)先)

????再打開左側(cè)的下拉框System,點(diǎn)擊NVIC選項(xiàng);

????可以在Priority Group中選擇中斷優(yōu)先級組

勾選USART1 global? interrupt開啟中斷

設(shè)置完成后
點(diǎn)擊Project Manager頁面,輸入工程名和工程位置,選擇工具鏈和IDE為MDK-ARM,版本為5.27;

打開左側(cè)Code Generater菜單勾選Generate peripheral initialization as a pair of'.c/.h'file per peripheral;?

最后點(diǎn)擊右上角的GENERATE CODE按鈕后生成代碼。
生成代碼后打開工程文件夾,用Keil5打開工程。

為了使得我們的代碼盡可能解耦合,所以我們在工程文件夾中新建一個user_uart.c和對應(yīng)的user_uart.h文件,在這個.c文件中我們寫入以下函數(shù)
/* Includes ------------------------------------------------------------------*/
#include "user_uart.h"
unsigned char UART1_Rx_Buf[Max_Rec_Long] = {0}; // 串口1存儲接收數(shù)據(jù)
unsigned char UART1_Rx_flg = 0; // 串口1接收完成標(biāo)志
unsigned int ?UART1_Rx_cnt = 0; // 串口1接受數(shù)據(jù)計(jì)數(shù)器
unsigned char UART1_temp[Rec_Long] = {0}; // 串口1接收數(shù)據(jù)緩存
/**
?* 函數(shù)名稱:串口中斷回調(diào)函數(shù)
?* 函數(shù)功能:調(diào)用回調(diào)函數(shù)的串口
?* 形 ? 參:串口名
?* 返回值 :無
?*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
? ?if(huart->Instance==USART1)
? ?{
? ? ? ?UART1_Rx_Buf[UART1_Rx_cnt] = UART1_temp[0];
? ? ? ?UART1_Rx_cnt++;
? ? ? ?if(0x0a == UART1_temp[0])
? ? ? ?{
? ? ? ? ? ?UART1_Rx_flg = 1;
? ? ? ?}
? ? ? ?HAL_UART_Receive_IT(&huart1,(uint8_t *)UART1_temp,Rec_Long); // 重新開啟串口接收中斷
? ?}
}
在對應(yīng)頭函數(shù)user_uart.h中寫入以下函數(shù)
#ifndef __USER_UART_H
#define __USER_UART_H
#ifdef __cplusplus
extern "C" {
#endif
#define Rec_Long ?1
#define Max_Rec_Long ?64
extern unsigned char UART1_Rx_Buf[Max_Rec_Long];
extern unsigned char UART1_Rx_flg ;
extern unsigned int ?UART1_Rx_cnt ;
extern unsigned char UART1_temp[Rec_Long];
#ifdef __cplusplus
}
#endif
#endif
在主函數(shù)的include中加入include
#include "user_uart.h"
再在主循環(huán)的初始化階段加入中斷初始化
HAL_UART_Receive_IT(&huart1,(uint8_t *)UART1_temp,REC_LENGTH);
然后再在主循環(huán)里加入中斷標(biāo)志位檢測
if(UART1_Rx_flg)
{
// 業(yè)務(wù)代碼開始
?
?
? // 業(yè)務(wù)代碼結(jié)束
? for(int i = 0; i < UART1_Rx_cnt; i++) // 清空接收數(shù)組
{
UART1_Rx_Buf[i] = 0;
}
? UART1_Rx_cnt = 0; // 清空接收計(jì)數(shù)器
? UART1_Rx_flg = 0; // 清空接收完成標(biāo)志位
}
好了,現(xiàn)在我們就可以在main里調(diào)用接收到的數(shù)組了
參考資料:
STM32F7開發(fā)指南-HAL庫版本_V1.1
HAL庫教程6:串口數(shù)據(jù)接收? ? https://blog.csdn.net/geek_monkey/article/details/89165040