串口配置
串口配置完之后打开串口中断:
不定长字节接受:
uart.h文件中添加“stdio.h”头文件uart.c文件中添加,重写printf
//加入以下代码,支持printf函数,而不需要选择use MicroLIB
//#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#if 1
//#pragma import(__use_no_semihosting)
//标准库需要的支持函数
struct __FILE
{
int handle;
};
FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
void _sys_exit(int x)
{
x = x;
}
//重定义fputc函数
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0x0001);
return ch;
}
#endif
主函数中重写回调函数:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
/* USER CODE BEGIN PV */
uint8_t revdate[6];
uint8_t aRxBuffer; // 接收中断缓冲
uint8_t Uart1_RxBuff[256]; // 接收缓冲
uint8_t Uart1_Rx_Cnt = 0; // 接收缓冲计数
uint8_t cAlmStr[] = "数据溢出(大于256)\r\n";
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
LED_B(!HAL_GPIO_ReadPin(LED_Blue_GPIO_Port, LED_Blue_Pin));
if (huart->Instance == USART1)
{
if (Uart1_Rx_Cnt >= 255) // 溢出判断
{
Uart1_Rx_Cnt = 0;
memset(Uart1_RxBuff, 0x00, sizeof(Uart1_RxBuff));
HAL_UART_Transmit(&huart1, (uint8_t *)&cAlmStr, sizeof(cAlmStr), 0xFFFF);
}
else
{
Uart1_RxBuff[Uart1_Rx_Cnt++] = aRxBuffer; // 接收数据转存
if ((Uart1_RxBuff[Uart1_Rx_Cnt - 1] == 0x0A) && (Uart1_RxBuff[Uart1_Rx_Cnt - 2] == 0x0D)) // 判断结束位
{
HAL_UART_Transmit(&huart1, (uint8_t *)&Uart1_RxBuff, Uart1_Rx_Cnt, 0xFFFF); // 将收到的信息发送出去
Uart1_Rx_Cnt = 0;
memset(Uart1_RxBuff, 0x00, sizeof(Uart1_RxBuff)); // 清空数组
}
}
HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1); // 再开启接收中断
}
}
系统初始化后开启中断:
/* USER CODE BEGIN 2 */
// 启动接收中断
HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1);
/* USER CODE END 2 */
拓展
编写串口计算器程序:通过串口调试助手,输入四则运算的表达式,发给STM32,STM32接收并计算出结果,将结果返回给串口调试助手。
比如:
上位机发送 12+23=?
MCU接收并计算出结果 35,返回给上位机串口调试助手,应收到 12+23=35
1.添加.h和.c功能函数文件
要在工程中添加对应文件,还有头文件路径
头文件
#ifndef __bsp_calculate_
#define __bsp_calculate_
#include "main.h"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int Calculate(char Cal[]);
#endif
源文件
#include <bsp_calculate.h>
int Calculate(char cal[]){
int temp =0;
int result = 0;
char operation;
for(int i =0 ;i<strlen(cal);i++){
if(cal[i]-'0'<=9 && cal[i]-'0'>=0){
temp=temp*10+(cal[i]-'0');
}else if(cal[i]-'='==0){
break;
}else {
operation = cal[i];
result = temp;
temp =0;
}
}
if(operation-'*' == 0){
return result*temp;
}else if(operation-'/' == 0){
return result/temp;
}else if(operation-'-' == 0){
return result-temp;
}else if(operation-'+' == 0){
return result+temp;
}
return -99999;
}
添加路径