STM32 —— 串口通信2 、中断2 STM32 中断方式串口通信(不定长已知内容或定长字符串)

STM32 —— 串口通信2 、中断2 STM32 中断方式串口通信(不定长已知内容或定长字符串)

实验目的

采用串口中断方式重做上周的串口通信作业,分别实现:

当 stm32 接收到字符 “s” 时,停止持续发送 “hello windows!” ; 当接收到字符“t”时,持续发送 “hello windows!”(提示:采用一个全局标量做信号灯)

当stm32接收到字符“stop stm32!”时,停止持续发送“hello windows!”

当接收到字符“go stm32!”时,持续发送“hello windows!”

提示:要将接收到的连续字符保存到一个字符数组里,进行判别匹配。写一个接收字符串的函数

实验原理

实验原理在我的另一篇博客中有详细的介绍:STM32 —— 串口定长数据接收

HAL 库方法

CubeMX 项目配置

设置 RCC

配置如图:

image

设置好外部晶振之后,需要设置时钟周期为 72 MHz

image

设置 SYS

用于设置并控制板载灯泡

image

设置 USART

将串口 USART1 设置为异步通信模式

image

设置 NVIC

将串口 USART1 设置为默认全局中断

image

代码设计

定长字符串接收

首先,我们需要一个布尔类型变量用来判断串口是否中断,并且在输入是要向上位机发送对应的回复,所以,数据定义如下:

bool flag = false;
char c;	// 输入的数据,t 是开始持续发送,s 是中断发送
uint8_t str[] = "Hello ppqppl !\r\n";	// 输出数据
uint8_t tips[] = "input error !\r\n";	// 输入错误
uint8_t stop[] = "STOP !\r\n";	// 中断发送
uint8_t start[] = "START !\r\n";	// 开始发送

注意:默认引入 bool 变量时会报错,所以,如果需要使用 bool 变量类型,需要引入头文件 stdbool.h

然后我们需要接收数据,HAL 库中已经有接收固定长度数据的函数,我们只需要直接调用即可,这里我们把串口接收函数写在主函数中的循环之前:

HAL_UART_Receive_IT(&huart1,(uint8_t *)&c,1);
// 函数的三个参数分别是:接收的串口,接收的数据,数据的长度

我们成功接收数据后,需要思考我们如何使串口产生中断,在 stm32f1xx_it.c 中我们可以找到使串口产生中断的函数:

void USART1_IRQHandler(void)

而这个函数主要是通过这个函数来执行中断事件:

void HAL_UART_IRQHandler(&huart1);

如果没有明白为什么要使用这个函数,请看我的另一篇博客:STM32 —— 串口定长数据接收

我们只需要重写这个函数即可:

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
	switch(c){
		case 's':{
			flag = false;
			HAL_UART_Transmit(huart,(uint8_t *)stop,COUNTOF(stop),0xFFFF);
			break;
		}
		case 't':{
			flag = true;
			HAL_UART_Transmit(huart,(uint8_t *)start,COUNTOF(start),0xFFFF);
			break;
		}
		default:{
			flag = false;
			HAL_UART_Transmit(huart,(uint8_t *)tips,COUNTOF(tips),0xFFFF);
			break;
		}
	}
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&c, 1);	// 由于我们是根据输入来判断中断,而且要求程序可以多次输入,所以这里每次中断判断后都要重新获取 c 的值
	
}

最后,我们只需要在主函数的循环中加上判断即可:

if(flag)
{
	HAL_UART_Transmit(&huart1,(uint8_t *)str,COUNTOF(str),0xFFFF);
	HAL_Delay(500);
}

完整的 main.c 代码如下:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"
#include <stdbool.h>

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
	
#define COUNTOF(a) (sizeof(a)/sizeof(*(a)))
bool flag = false;
char c;
uint8_t str[] = "Hello ppqppl !\r\n";
uint8_t tips[] = "input error !\r\n";
uint8_t stop[] = "STOP !\r\n";
uint8_t start[] = "START !\r\n";

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
	switch(c){
		case 's':{
			flag = false;
			HAL_UART_Transmit(huart,(uint8_t *)stop,COUNTOF(stop),0xFFFF);
			break;
		}
		case 't':{
			flag = true;
			HAL_UART_Transmit(huart,(uint8_t *)start,COUNTOF(start),0xFFFF);
			break;
		}
		default:{
			flag = false;
			HAL_UART_Transmit(huart,(uint8_t *)tips,COUNTOF(tips),0xFFFF);
			break;
		}
	}
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&c, 1);
	
}
	
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	HAL_UART_Receive_IT(&huart1,(uint8_t *)&c,1);
  while (1)
  {
		
		if(flag){
			HAL_UART_Transmit(&huart1,(uint8_t *)str,COUNTOF(str),0xFFFF);
			HAL_Delay(500);
		}
		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

不定长已知内容字符串接收

原理与上面类似,知识每次接收一个字符,然后讲字符存储到字符串中,每次中断都进行比对,当比对成功,通过判断改变 bool 变量的值,从而影响输出

主要代码如下

#define COUNTOF(a)(sizeof(a)/sizeof(*(a)))
char getBuffer[100];
char value;
char str1[] = "go ppqppl!"; 
char str2[] = "stop ppqppl!"; 
uint8_t out1[] = "start!\r\n";
uint8_t out2[] = "stop!\r\n";
uint8_t str[] = "Hello ppqppl!\r\n";
bool flag = false;
int countofGetBuffer = 0;

void USART1_IRQHandler(void)
{
	HAL_UART_IRQHandler(&huart1); //该函数会清空中断标志,取消中断使能,并间接调用回调函数
	getBuffer[countofGetBuffer++] = value;
	if(strcmp(str1,getBuffer) == 0)	// 这里把判断长度改为判断内容
	{
		HAL_UART_Transmit(&huart1,(uint8_t *)out1,COUNTOF(out1),0xFFFF);
		flag = true;
		countofGetBuffer = 0;
		memset(getBuffer,0,COUNTOF(getBuffer));
	}
	else if(strcmp(str2,getBuffer) == 0)
	{
		flag = false;
		HAL_UART_Transmit(&huart1,(uint8_t *)out2,COUNTOF(out2),0xFFFF);
		HAL_Delay(500);
		countofGetBuffer = 0;
		memset(getBuffer,0,COUNTOF(getBuffer));
	}
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&value,1);  //由于接收中断是每接收一个字符便进入一次,所以这一行代码必须添加,否则只能接收一个字符,而无法接收整个字符串
}

注意:这里再重写函数是需要将 stm32f1xx_it.c 中的函数删掉,否则会出现重定义的报错

完整的 main.c 代码如下:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"
#include <stdbool.h>
#include <string.h>

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
#define COUNTOF(a)(sizeof(a)/sizeof(*(a)))
char getBuffer[100];
char value;
char str1[] = "go ppqppl!"; 
char str2[] = "stop ppqppl!"; 
uint8_t out1[] = "start!\r\n";
uint8_t out2[] = "stop!\r\n";
uint8_t str[] = "Hello ppqppl!\r\n";
bool flag = false;
int countofGetBuffer = 0;

void USART1_IRQHandler(void)
{
	HAL_UART_IRQHandler(&huart1); //该函数会清空中断标志,取消中断使能,并间接调用回调函数
	getBuffer[countofGetBuffer++] = value;
	if(strcmp(str1,getBuffer) == 0)	// 这里把判断长度改为判断内容
	{
		HAL_UART_Transmit(&huart1,(uint8_t *)out1,COUNTOF(out1),0xFFFF);
		flag = true;
		countofGetBuffer = 0;
		memset(getBuffer,0,COUNTOF(getBuffer));
	}
	else if(strcmp(str2,getBuffer) == 0)
	{
		flag = false;
		HAL_UART_Transmit(&huart1,(uint8_t *)out2,COUNTOF(out2),0xFFFF);
		HAL_Delay(500);
		countofGetBuffer = 0;
		memset(getBuffer,0,COUNTOF(getBuffer));
	}
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&value,1);  //由于接收中断是每接收一个字符便进入一次,所以这一行代码必须添加,否则只能接收一个字符,而无法接收整个字符串
}
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  HAL_UART_Receive_IT(&huart1,(uint8_t *)&value,1);
  while (1)
  {
	  if(flag){
			HAL_UART_Transmit(&huart1,(uint8_t *)str,COUNTOF(str),0xFFFF);  
			HAL_Delay(500);
	  }
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

标准库方法

若有需要,后续会更新标准库写法

寄存器方法

若有需要,后续会更新寄存器写法

运行测试

虚拟串口调试

由于在调试程序时,每次修改代码后重新编译生成 hex 文件并多次烧录比较麻烦,所以这里采用仿真运行,并在 keil 中使用虚拟串口调试

调试工具下载连接:虚拟串口驱动程序_Virtual Serial Port Driver(中文和谐版)

安装好之后,我们将两个空闲串口进行绑定,这里采用将 COM3 与 COM2 进行绑定使用:

image

在选择好目标端口后,点击添加端口即可

如果左边已经出现了虚拟端口,就说明端口绑定成功:

image

然后我们在 keil 中启动仿真运行,在左下角命令窗口输入如下命令即可绑定串口:

MODE COM2 15200,n,8,1

函数源码如下:

MODE COMx baudrate, parity, databits, stopbits
/*
COMx 表示计算机的串口
baudrate 表示串口的波特率
parity 表示校验方式,即 n 表示无校验位,0 表示偶校验,1 表示奇校验
stopbits 表示停止位长度
*/

绑定串口后,需要将计算机的串口绑定到单片机上:

ASSIGN COM2 < S3IN > S3OUT

函数源码如下:

ASSIGN COMx < SIN > SOUT
/*
COMx 表示计算机的串口
SIN 和 SOUT 表示绑定的单片机的输入和输出串口
*/

绑定如下:

image

绑定完全成功后,就可以使用串口调试工具进行仿真串口调试了

虚拟串口测试结果

接收单字符:

image

接收不定长已知内容字符串:

image

测试接收不定长已知内容字符串的时候忘记加延时了,导致上位机端接收有点小问题,加上延时之后就没问题了

接线示例

image

image

image

运行结果

image

image

波形检测

我们通过仿真虚拟串口调试的方式进行波形检测

image

与串口发送 Hello Windows 波形相同,产生原因也不尽相同

错误解决方法

目前尚未发现报错,如有报错会及时更新修改方法

参考文档

  1. HAL库中断方式进行串口通信

  2. keil MDK 中使用虚拟串口调试串口

posted @ 2022-10-23 19:33  ppqppl  阅读(327)  评论(0编辑  收藏  举报