From f9d3b94f6317d9d7d6f26550aed29f35eea2bd07 Mon Sep 17 00:00:00 2001 From: EN Date: Thu, 11 Jul 2024 18:14:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B6=85=E5=A3=B0=E6=B3=A2?= =?UTF-8?q?=EF=BC=8C=E7=AE=97=E6=B3=95=E9=9C=80=E8=A6=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Core/Inc/hcsr04.h | 9 +++++ Core/Src/hcsr04.c | 85 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 Core/Inc/hcsr04.h create mode 100644 Core/Src/hcsr04.c diff --git a/Core/Inc/hcsr04.h b/Core/Inc/hcsr04.h new file mode 100644 index 0000000..9c00c39 --- /dev/null +++ b/Core/Inc/hcsr04.h @@ -0,0 +1,9 @@ +#ifndef __HCSR04_H +#define __HCSR04_H + +#include "main.h" + +int16_t sonar_mm(void); +float sonar(void); + +#endif diff --git a/Core/Src/hcsr04.c b/Core/Src/hcsr04.c new file mode 100644 index 0000000..aa57595 --- /dev/null +++ b/Core/Src/hcsr04.c @@ -0,0 +1,85 @@ +#include "hcsr04.h" +#include "tim.h" + +// time 的单位是 μs +uint64_t time; // 声明变量,用来计时 +uint64_t time_end; // 声明变量,存储回波信号时间 +uint8_t state = 1; + +// HACK 临时的 delay 解决方法 +void delay_us(uint16_t us); + +int16_t sonar_mm(void) // 测距并返回单位为毫米的距离结果 +{ + uint32_t distance, distance_mm = 0; + HAL_GPIO_WritePin(SCL_C_GPIO_Port, SCL_C_Pin, GPIO_PIN_SET); // 输出高电平 + delay_us(15); // 延时15微秒 + HAL_GPIO_WritePin(SCL_C_GPIO_Port, SCL_C_Pin, GPIO_PIN_RESET); // 输出低电平 + + while (state) + ; + state = 1; + + // BUG 现在 time 的单位是 1μs + if (time_end / 100 < 38) // 判断是否小于38毫秒,大于38毫秒的就是超时,直接调到下面返回0 + { + distance = (time_end * 346) / 2; // 计算距离,25°C空气中的音速为346m/s + distance_mm = distance / 100; // 因为上面的time_end的单位是10微秒,所以要得出单位为毫米的距离结果,还得除以100 + } + return distance_mm; // 返回测距结果 +} + +float sonar(void) // 测距并返回单位为米的距离结果 +{ + uint32_t distance, distance_mm = 0; + float distance_m = 0; + HAL_GPIO_WritePin(SCL_C_GPIO_Port, SCL_C_Pin, GPIO_PIN_SET); // 输出高电平 + delay_us(15); // 延时15微秒 + HAL_GPIO_WritePin(SCL_C_GPIO_Port, SCL_C_Pin, GPIO_PIN_RESET); // 输出低电平 + + while (state) + ; + state = 1; + + // BUG 现在 time 的单位是 1μs + if (time_end / 100 < 38) + { + distance = (time_end * 346) / 2; + distance_mm = distance / 100; + distance_m = distance_mm / 1000; + } + return distance_m; +} + +void delay_us(uint16_t us) +{ + HAL_TIM_Base_Start_IT(&htim2); + time = 0; + while (time < us) + ; + HAL_TIM_Base_Stop_IT(&htim2); +} + +void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) +{ + if (htim == &htim2) + ++time; +} + +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + if (GPIO_Pin == SDA_C_EXTI12_Pin) + { + if (HAL_GPIO_ReadPin(SDA_C_EXTI12_GPIO_Port, SDA_C_EXTI12_Pin)) + { + HAL_TIM_Base_Start_IT(&htim2); + time = 0; + } + else + { + time_end = time; + HAL_TIM_Base_Stop_IT(&htim2); + state = 0; + } + } +}