完善超声波测距

This commit is contained in:
EN 2024-07-13 15:59:18 +08:00
parent cbe6350ee3
commit 00ee34a664

View File

@ -1,10 +1,11 @@
#include "hcsr04.h" #include "hcsr04.h"
#include "tim.h" #include "tim.h"
// time 的单位是 1μs // time 的单位是 10μs
static volatile uint64_t time; // 声明变量,用来计时 static volatile uint64_t time; // 声明变量,用来计时
static uint64_t time_end; // 声明变量,存储回波信号时间 static uint64_t time_end; // 声明变量,存储回波信号时间
static uint8_t state = 0; static uint8_t state;
static int16_t delay_time = -1; // 用于延时
// HACK 临时的 delay 解决方法 // HACK 临时的 delay 解决方法
void delay_us(uint16_t us); void delay_us(uint16_t us);
@ -21,23 +22,28 @@ uint16_t sonar(void) // 测距并返回单位为毫米的距离结果
HAL_Delay(15); HAL_Delay(15);
if (state) if (state)
distance = time_end * 346 / 2000; // 计算距离25°C空气中的音速为346m/s distance = time_end * 346 / 200; // 计算距离25°C空气中的音速为346m/s
return distance; return distance;
} }
void delay_us(uint16_t us) void delay_us(uint16_t us)
{ {
HAL_TIM_Base_Start_IT(&htim2); delay_time = us;
time = 0; time = 0;
HAL_TIM_Base_Start_IT(&htim2);
while (time < us) while (time < us)
; ;
HAL_TIM_Base_Stop_IT(&htim2); delay_time = -1;
} }
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{ {
if (htim == &htim2) if (htim == &htim2)
{
++time; ++time;
if (delay_us > 0 && time == delay_time)
HAL_TIM_Base_Stop_IT(&htim2);
}
} }
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)