STM32外设使用之超声波(一),基于Cubemx,输入捕获法

前言

在学习stm32的外设-超声波模块(HC-SR04),遇到了一些困难,因为cubemx无法直接使用超声波的模板(需要自己改动),故写下此篇文章,提醒自己的同时也想去给小白一下建议

准备工作

外设的连接

超声波模块有四个引脚
GND–GND
TRIG–PB11
ECHO–PB10(需打开此引脚对应的定时器通道)
VCC–5V的电压(若为最小开发版需要链接stlink的5V!!!!

1.我们需要看清楚连接的引脚这是最重要的一步
2.需要确保超声波模块连接的是5V电压
3.注意要给PB10引脚下拉电阻

cubemx的配置

这里就不详细展开了,我们只需要打开定时器的中断,并且配置其中的一个通道为输入捕获通道即可
(ECHO所连接的引脚),用到的知识点是输入捕获故不懂的小白可以先去学习这部分的知识

工作原理

我们给TRIG引脚一个10us的高电平即可触发超声波模块发射8个40khz的声波,然后ECHO端便会收到返回来的声波,这个时间就是声波来回的时间,根据这个我们便可以大概算出来这个距离,然后在发给串口即可

需要用到的相关函数

//关于定时器捕获的

HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_3); /开启定时器的捕获中断
HAL_TIM_IC_Stop_IT(&htim2, TIM_CHANNEL_3);  /关闭定时器的捕获中断

HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_3);/获取当前的捕获值

__HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_RISING);/修改为上升沿捕获
__HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_FALLING);/修改为下降沿捕获

__HAL_TIM_SET_COUNTER(&htim2,0);   //设置计数寄存器的值变为0

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)/重写中断回调函数




//关于串口输出的
先重写printf函数
//支持printf函数,而不需要选择use MicroLIB	  
#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)
{      
	while((USART1->SR&0X40)==0);//循环发送,直到发送完毕   
    USART1->DR = (uint8_t) ch;      
	return ch;
}
#endif 
/直接写到uart.c就好(记得引入<stdio.h>)

spritnf()用于将数据转化为字符串形式用,printf输出信息

代码的编写

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 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 "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include<stdio.h>
/* 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 BEGIN 0 */
uint32_t capture_Buf[2] = {0};   //存放计数值
uint8_t capture_Cnt = 0;    //状态标志位
uint32_t high_time;   //高电平时间
/* USER CODE END 0 */
/* 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 */
void Supersonic_Start()
{
  HAL_GPIO_WritePin(TRIG_GPIO_Port,TRIG_Pin,GPIO_PIN_SET);
  HAL_Delay(5);
  HAL_GPIO_WritePin(TRIG_GPIO_Port,TRIG_Pin,GPIO_PIN_RESET);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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_TIM2_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  HAL_GPIO_TogglePin(LED_G_GPIO_Port,LED_G_Pin);
  switch (capture_Cnt){
	case 0:
  //printf("1");
		capture_Cnt++;
		__HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_RISING);

		HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_3);	//启动输入捕获       或者: __HAL_TIM_ENABLE(&htim2);
        Supersonic_Start();

		break;
	case 3:
  //printf("4");
    high_time = capture_Buf[1]- capture_Buf[0];    //高电平时间
		//HAL_UART_Transmit(&huart2, (uint8_t *)high_time, 1, 0xffff);   //发送高电平时间
				
		float data = high_time*0.017;
    char buf[20];
    sprintf(buf,"%2.2f",data);		
    printf("距离是:%s cm
",buf);

		HAL_Delay(1000);   //延时1S
    //__HAL_TIM_SET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_3,0);
		capture_Cnt = 0;  //清空标志
    break;
  }
  }
  /* 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 BEGIN 4 */
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	
	if(TIM2 == htim->Instance)
	{
		switch(capture_Cnt){
			case 1:
        capture_Buf[0] = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_3);//获取当前的捕获值.
        __HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_FALLING);
        capture_Cnt++; 
      break;
		  case 2:
        //HAL_GPIO_WritePin(LED_R_GPIO_Port,LED_R_Pin,GPIO_PIN_RESET);
        capture_Buf[1] = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_3);//获取当前的捕获值.
        HAL_TIM_IC_Stop_IT(&htim2,TIM_CHANNEL_3); //停止捕获   或者: __HAL_TIM_DISABLE(&htim2);
        __HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_RISING);
        capture_Cnt++;    
      break;
		}
	
	}
	
}
/* 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
", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

这段代码是有借鉴别的博主,我觉得这个定时器捕获的思路非常好,同时记得中断回调函数的重写
以及数据的清零

代码思路

首先定义状态标志量以及用于储存数据的数组,随后在主循环里我们要做两件事
第一件是启动定时器捕获,并且驱动超声波模块
第二件则是对数据清零以及处理捕获到的数据

在中断回调函数中我们需要处理的则是捕获上升沿和下降沿的数据(中间更改捕获的极性)

总结

我们在驱动外设前需要先理解该原理,否则无法成为一个合格的cv工程师,我们需要看的懂别人的代码也需要会修改别人的代码,通过这次学习我学会了如何去调试程序,如果去一个一个地方的排除错误。希望大家能够通过学习外设的同时学会如何调试如何移植别人的代码