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