HC-SR04 的使用
一、超声波模块介绍
HC-SR04 是一种常用的超声波测距模块。它通过发射超声波并测量这些波反射回来的时间来计算距离。模块的基本结构包括一个超声波发射器和一个接收器。发射器发出高频超声波,当这些波遇到物体后反射回来,接收器接收到这些反射波。根据超声波的传播时间和声速,模块可以计算出到物体的距离。它通常用于测距、避障等应用中。
用的是这两款 第二款功能更多 不贴电阻 和上面这款没差别
二、工作原理介绍
三、接线方式
VCC–5V/3.3v【网上有看到一定得是5v 根据自己使用的模块来】
GND–GND
Trig – 板子上的OUTPUT引脚(用来发射超声波信号)
Echo-- 板子上的INPUT引脚(用来接收返回的超声波信号)
四、驱动方式
方法一
使用普通两个io 接Trig【OUTPUT】和Echo【INPUT】 外用一个定时器计数【开中断】
【不需要开自动重装载吗?】
方法二
使用双超声波
Trig使用普通io【OUTPUT】,Echo 使用定时器输入捕获功能 并开中断
五、程序实现
串口查看数据
头文件:#include “stdio.h”
ps:如果只使用串口功能 不需要开中断
int fputc(int c,FILE* s)
{
HAL_UART_Transmit(&huart1,(const uint8_t*)&c,1,0xFFFF );
return c;
}
方法一
HC_SR04.c
#include "main.h"
#include "HC_SR04.h"
#include "stm32f1xx_hal.h"
#include "stm32f1xx_it.h"
#include "gpio.h"
static float distance_result;
/*
*********************************************************
函数原型:void Delay_us(uint16_t time)
函数输入:无符号整形
函数输出:无
函数功能:利用定时器实现微秒级延时
*********************************************************
*/
void Delay_us(uint16_t time)
{
uint16_t a1=TIM2->CNT;
while(TIM2->CNT-a1<time);
}
/*
*********************************************************
函数原型:void HC_SR04_startrange(void)
函数输入:无
函数输出:无
函数功能:从trig引脚生成一个不小于10us的高电平触发测距,触发后模块自动产生8个40kHz方波,自动检测是否有信号返回
*********************************************************
*/
void HC_SR04_startrange(void)
{
HAL_GPIO_WritePin(HC_SR04_Trig_Pin_GPIO_Port,HC_SR04_Trig_Pin_Pin,GPIO_PIN_SET);
//HAL_Delay(5);
Delay_us(10);
HAL_GPIO_WritePin(HC_SR04_Trig_Pin_GPIO_Port,HC_SR04_Trig_Pin_Pin,GPIO_PIN_RESET);
}
/*
*********************************************************
函数原型:uint16_t HC_SR04_gettime(void)
函数输入:无
函数输出:无符号整型
函数功能:通过定时器获取当前时间
*********************************************************
*/
uint16_t HC_SR04_gettime(void)
{
uint32_t a;
a=TIM2->CNT;
return a;
}
/*
*********************************************************
函数原型:float HC_SR04_getdistance(void)
函数输入:无
函数输出:浮点型
函数功能:获取与目标之间的距离
*********************************************************
*/
float HC_SR04_getdistance(void)
{
uint16_t time_node1;
uint16_t time_node2;
uint16_t measure;
HC_SR04_startrange();
TIM2->CNT = 0;
//有信号返回则通过IO口Echo输出高电平,高电平持续时间即为超声波从发射到返回的时间,测试距离=( 高电平时间*声速(340m/s) )/ 2
while(HAL_GPIO_ReadPin(HC_SR04_Echo_Pin_GPIO_Port,HC_SR04_Echo_Pin_Pin)==RESET);
time_node1=HC_SR04_gettime();
while(HAL_GPIO_ReadPin(HC_SR04_Echo_Pin_GPIO_Port,HC_SR04_Echo_Pin_Pin)==SET);
time_node2=HC_SR04_gettime();
measure=time_node2-time_node1;
distance_result = measure * 17.0/1000;//距离=计数差值(us) / 1000000 * 340(m/s) * 100 / 2 = measure * 17/1000
return distance_result;
}
HC_SR04.h
#ifndef _HC_SR04_H_
#define _HC_SR04_H_
#include "main.h"
void Delay_us(uint16_t time);
void HC_SR04_startrange(void);
float HC_SR04_getdistance(void);
uint16_t HC_SR04_gettime(void);
#endif
main.c
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "HC_SR04.h"
#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 */
int fputc(int c,FILE* s)
{
HAL_UART_Transmit(&huart1,(const uint8_t*)&c,1,0xFFFF );
return c;
}
/* 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 */
/**************************************************************************/
//平滑数据处理
//使用平滑算法(如移动平均)来减少数据的波动。这样可以让测得的距离值更稳定。
/**************************************************************************/
#define SMOOTHING_FACTOR 7 // 平滑的历史值数量
float smooth_dist(int current_dist) {
static float history[SMOOTHING_FACTOR] = {0};
static int index = 0;
static int count = 0;
float sum = 0;
history[index] = current_dist;
index = (index + 1) % SMOOTHING_FACTOR;
if (count < SMOOTHING_FACTOR) count++;
for (int i = 0; i < count; i++) {
sum += history[i];
}
return sum / count;
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
float HC_SR04_distance = 0 ;
/* 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_USART1_UART_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start_IT(&htim2);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HC_SR04_distance=HC_SR04_getdistance();
HC_SR04_distance= smooth_dist(HC_SR04_distance);
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET);//开灯
printf("有人,目前距离为:%.2f cm\r\n",HC_SR04_distance);
HAL_Delay(100);
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
main.h
#define LED_Pin GPIO_PIN_13
#define LED_GPIO_Port GPIOC
#define HC_SR04_Trig_Pin_Pin GPIO_PIN_4
#define HC_SR04_Trig_Pin_GPIO_Port GPIOB
#define HC_SR04_Echo_Pin_Pin GPIO_PIN_5
#define HC_SR04_Echo_Pin_GPIO_Port GPIOB
串口数据显示
方法二
main.c
/* 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"
#include "string.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t TIM2CH1_CAPTURE_STA; //输入捕获状态
uint16_t TIM2CH1_CAPTURE_VAL; //输入捕获值
uint8_t TIM3CH1_CAPTURE_STA; //输入捕获状态
uint16_t TIM3CH1_CAPTURE_VAL; //输入捕获值
/* 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 */
int fputc(int c,FILE* s)
{
HAL_UART_Transmit(&huart1,(const uint8_t*)&c,1,0xFFFF );
return c;
}
/* 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
*/
int main(void)
{
/* USER CODE BEGIN 1 */
float len=0;
uint16_t dis = 0;
uint32_t time=0;
float len3=0;
uint16_t dis3 = 0;
uint32_t time3=0;
/* 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_TIM3_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_1); //开启TIM2的捕获通道1,并且开启捕获中断
HAL_TIM_IC_Start_IT(&htim3,TIM_CHANNEL_1); //开启TIM3的捕获通道1,并且开启捕获中断
__HAL_TIM_ENABLE_IT(&htim2,TIM_IT_UPDATE); //使能更新中断
__HAL_TIM_ENABLE_IT(&htim3,TIM_IT_UPDATE); //使能更新中断
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
//printf("123\r\n");
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
ch1_capture();
ch3_capture();
//printf("TIM2 Capture STA: %02X\n", TIM2CH1_CAPTURE_STA);
if(TIM2CH1_CAPTURE_STA&0X80) //成功捕获到了一次高电平
{
time=TIM2CH1_CAPTURE_STA&0X3F;
time*=65536; //溢出时间总和
time+=TIM2CH1_CAPTURE_VAL; //得到总的高电平时间
len=time*0.17;
dis = (uint16_t)len;
printf("v1=%d\r\n",dis);
// while(HAL_OK != HAL_UART_Transmit(&huart1, (uint8_t *)str, strlen(str), 5000));
TIM2CH1_CAPTURE_STA=0; //开启下一次捕获
}
if(TIM3CH1_CAPTURE_STA&0X80) //成功捕获到了一次高电平
{
time3=TIM3CH1_CAPTURE_STA&0X3F;
time3*=65536; //溢出时间总和
time3+=TIM3CH1_CAPTURE_VAL; //得到总的高电平时间
len3=time3*0.17;
dis3 = (uint16_t)len3;
printf("v2=%d\r\n",dis3);
// sprintf(str3,"v2=%d\r\n",dis3);
// while(HAL_OK != HAL_UART_Transmit(&huart1, (uint8_t *)str3, strlen(str3), 5000));
TIM3CH1_CAPTURE_STA=0; //开启下一次捕获
}
HAL_Delay(100);
}
/* 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 */
void ch1_capture(void)
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);
delay_us(20);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
}
void ch3_capture(void)
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_SET);
delay_us(20);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_RESET);
}
void delay_us(uint32_t us)
{
// 预计算循环次数,根据你的处理器频率调整
volatile uint32_t count;
while (us-- > 0)
{
count = 8; // 根据处理器频率和指令执行时间调整
while (count-- > 0);
}
}
//定时器更新中断(计数溢出)中断处理回调函数, 该函数在HAL_TIM_IRQHandler中会被调用
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)//更新中断(溢出)发生时执行
{
if(htim->Instance == htim2.Instance)
{
if((TIM2CH1_CAPTURE_STA&0X80)==0) //还未成功捕获上升沿
{
if(TIM2CH1_CAPTURE_STA&0X40) //已经捕获到高电平了
{
if((TIM2CH1_CAPTURE_STA&0X3F)==0X3F) //高电平太长了
{
TIM2CH1_CAPTURE_STA|=0X80; //标记成功捕获了一次
TIM2CH1_CAPTURE_VAL=0XFFFF;
}else TIM2CH1_CAPTURE_STA++;
}
}
}
if(htim->Instance == htim3.Instance)
{
if((TIM3CH1_CAPTURE_STA&0X80)==0) //还未成功捕获上升沿
{
if(TIM3CH1_CAPTURE_STA&0X40) //已经捕获到高电平了
{
if((TIM3CH1_CAPTURE_STA&0X3F)==0X3F) //高电平太长了
{
TIM3CH1_CAPTURE_STA|=0X80; //标记成功捕获了一次
TIM3CH1_CAPTURE_VAL=0XFFFF;
}else TIM3CH1_CAPTURE_STA++;
}
}
}
}
//定时器输入捕获中断处理回调函数,该函数在HAL_TIM_IRQHandler中会被调用
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)//捕获中断发生时执行
{
if(htim->Instance == TIM2)
{
if((TIM2CH1_CAPTURE_STA&0X80)==0) //还未成功捕获
{
if(TIM2CH1_CAPTURE_STA&0X40) //捕获到一个下降沿
{
TIM2CH1_CAPTURE_STA|=0X80; //标记成功捕获到一次高电平脉宽
TIM2CH1_CAPTURE_VAL=HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_1);//获取当前的捕获值.
TIM_RESET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1); //一定要先清除原来的设置!!
TIM_SET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1,TIM_ICPOLARITY_RISING);//配置TIM2通道1上升沿捕获
}else //还未开始,第一次捕获上升沿
{
TIM2CH1_CAPTURE_STA=0; //清空
TIM2CH1_CAPTURE_VAL=0;
TIM2CH1_CAPTURE_STA|=0X40; //标记捕获到了上升沿
__HAL_TIM_DISABLE(&htim2); //关闭定时器2
__HAL_TIM_SET_COUNTER(&htim2,0);
TIM_RESET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1); //一定要先清除原来的设置!!
TIM_SET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1,TIM_ICPOLARITY_FALLING);//定时器2通道1设置为下降沿捕获
__HAL_TIM_ENABLE(&htim2); //使能定时器2
}
// printf("TIM2 Capture STA: %02X\n", TIM2CH1_CAPTURE_STA);
}
}
if(htim->Instance == htim3.Instance)
{
if((TIM3CH1_CAPTURE_STA&0X80)==0) //还未成功捕获
{
if(TIM3CH1_CAPTURE_STA&0X40) //捕获到一个下降沿
{
TIM3CH1_CAPTURE_STA|=0X80; //标记成功捕获到一次高电平脉宽
TIM3CH1_CAPTURE_VAL=HAL_TIM_ReadCapturedValue(&htim3,TIM_CHANNEL_1);//获取当前的捕获值.
TIM_RESET_CAPTUREPOLARITY(&htim3,TIM_CHANNEL_1); //一定要先清除原来的设置!!
TIM_SET_CAPTUREPOLARITY(&htim3,TIM_CHANNEL_1,TIM_ICPOLARITY_RISING);//配置TIM2通道1上升沿捕获
}else //还未开始,第一次捕获上升沿
{
TIM3CH1_CAPTURE_STA=0; //清空
TIM3CH1_CAPTURE_VAL=0;
TIM3CH1_CAPTURE_STA|=0X40; //标记捕获到了上升沿
__HAL_TIM_DISABLE(&htim3); //关闭定时器2
__HAL_TIM_SET_COUNTER(&htim3,0);
TIM_RESET_CAPTUREPOLARITY(&htim3,TIM_CHANNEL_1); //一定要先清除原来的设置!!
TIM_SET_CAPTUREPOLARITY(&htim3,TIM_CHANNEL_1,TIM_ICPOLARITY_FALLING);//定时器2通道1设置为下降沿捕获
__HAL_TIM_ENABLE(&htim3); //使能定时器2
}
}
}
}
/* 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 */
main.h
#define Echo1_Pin GPIO_PIN_0
#define Echo1_GPIO_Port GPIOA
#define Trig1_Pin GPIO_PIN_1
#define Trig1_GPIO_Port GPIOA
#define Trig2_Pin GPIO_PIN_3
#define Trig2_GPIO_Port GPIOA
#define Echo2_Pin GPIO_PIN_6
#define Echo2_GPIO_Port GPIOA
六、 数据处理
数据处理还存在问题 后续找到更好的更新
/**************************************************************************/
//平滑数据处理
//使用平滑算法(如移动平均)来减少数据的波动。这样可以让测得的距离值更稳定。
/**************************************************************************/
#define SMOOTHING_FACTOR 5 // 平滑的历史值数量
float smooth_dist(int current_dist) {
static float history[SMOOTHING_FACTOR] = {0};
static int index = 0;
static int count = 0;
float sum = 0;
history[index] = current_dist;
index = (index + 1) % SMOOTHING_FACTOR;
if (count < SMOOTHING_FACTOR) count++;
for (int i = 0; i < count; i++) {
sum += history[i];
}
return sum / count;
}
标签:CAPTURE,SR04,HAL,TIM,CODE,USER,CubeMx,STM32F103C8T6,GPIO
From: https://blog.csdn.net/makabaka2020/article/details/142130583