stm32f401 hal 超声波测距
时间: 2024-12-25 08:20:11 浏览: 69
### STM32F401 使用 HAL 库进行超声波测距
对于 STM32F401 来说,利用 HAL 库可以简化硬件抽象层的操作,使得开发者能够更专注于应用逻辑而非底层驱动细节。当涉及到超声波传感器的应用时,主要的工作原理是通过测量发射脉冲与接收回波之间的时间差来计算距离。
#### 初始化配置
为了使能外设功能并初始化 GPIO 和定时器资源,在 `main.c` 文件中的 `MX_GPIO_Init()` 函数里完成必要的引脚设置以及调用 `HAL_TIM_Encoder_MspInit(&htim)` 方法来进行编码器模式下的 TIM 配置[^1]。
```c
static void MX_GPIO_Init(void)
{
__HAL_RCC_GPIOA_CLK_ENABLE();
/* Configure the trigger pin as output */
GPIO_InitStruct.Pin = TRIG_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(TRIG_GPIO_Port, &GPIO_InitStruct);
/* Configure the echo pin as input with pull-up resistor */
GPIO_InitStruct.Pin = ECHO_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(ECHO_GPIO_Port, &GPIO_InitStruct);
}
```
#### 超声波触发信号生成
在实际操作过程中,向 HC-SR04 的 Trig 引脚施加至少 10us 的高电平脉冲即可启动一次测距请求;随后等待 Echo 引脚变为低电平时记录下时刻 t1 ,再次等到其变回高电平则记作 t2 。两者之差即代表了往返飞行时间 Tflight=(t2-t1),再乘以空气中的声速 v (约为 340m/s ) 并除以二便得到目标物体到探头间的直线距离 D=v*Tflight/2.
```c
void sendTriggerPulse()
{
// Set Trigger Pin High for at least 10 microseconds.
HAL_GPIO_WritePin(GPIOA, TRIG_PIN, GPIO_PIN_SET);
HAL_Delay(1); // Wait for a short period to ensure pulse width is sufficient
// Reset Trigger Pin Low after sending out the pulse.
HAL_GPIO_WritePin(GPIOA, TRIG_PIN, GPIO_PIN_RESET);
}
float getDistance_cm(TIM_HandleTypeDef *htim)
{
uint32_t start_time_us = 0;
uint32_t end_time_us = 0;
while(HAL_GPIO_ReadPin(GPIOA,ECHO_PIN)==RESET){}; // wait until ECHO goes HIGH
start_time_us=__HAL_TIM_GET_COUNTER(htim);
while(HAL_GPIO_ReadPin(GPIOA,ECHO_PIN)){};
end_time_us=__HAL_TIM_GET_COUNTER(htim);
float duration_s=((end_time_us-start_time_us)/((float)SystemCoreClock))*1e6; // Calculate time difference between two edges in seconds.
const float sound_speed_m_per_s=343.2f; // Speed of Sound @ Sea Level and Room Temperature
return ((duration_s*sound_speed_m_per_s)*100.f)/2.f ;// Convert Time Difference into Distance(in cm).
}
```
阅读全文
相关推荐


















