2024-07-11 18:14:13 +08:00
|
|
|
|
#include "hcsr04.h"
|
|
|
|
|
#include "tim.h"
|
|
|
|
|
|
2024-07-12 23:00:46 +08:00
|
|
|
|
// time 的单位是 1μs
|
|
|
|
|
static volatile uint64_t time; // 声明变量,用来计时
|
|
|
|
|
static uint64_t time_end; // 声明变量,存储回波信号时间
|
|
|
|
|
static uint8_t state = 0;
|
2024-07-11 18:14:13 +08:00
|
|
|
|
|
|
|
|
|
// HACK 临时的 delay 解决方法
|
|
|
|
|
void delay_us(uint16_t us);
|
|
|
|
|
|
2024-07-12 23:00:46 +08:00
|
|
|
|
uint16_t sonar(void) // 测距并返回单位为毫米的距离结果
|
2024-07-11 18:14:13 +08:00
|
|
|
|
{
|
2024-07-12 23:00:46 +08:00
|
|
|
|
// 超时则返回5m距离
|
|
|
|
|
uint32_t distance = 5000;
|
2024-07-11 18:14:13 +08:00
|
|
|
|
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); // 输出低电平
|
|
|
|
|
|
2024-07-12 23:00:46 +08:00
|
|
|
|
// HACK 考虑RTOS优化
|
|
|
|
|
HAL_Delay(15);
|
2024-07-11 18:14:13 +08:00
|
|
|
|
|
2024-07-12 23:00:46 +08:00
|
|
|
|
if (state)
|
|
|
|
|
distance = time_end * 346 / 2000; // 计算距离,25°C空气中的音速为346m/s
|
|
|
|
|
return distance;
|
2024-07-11 18:14:13 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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))
|
|
|
|
|
{
|
|
|
|
|
time = 0;
|
2024-07-12 23:00:46 +08:00
|
|
|
|
HAL_TIM_Base_Start_IT(&htim2);
|
2024-07-11 18:14:13 +08:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
time_end = time;
|
|
|
|
|
HAL_TIM_Base_Stop_IT(&htim2);
|
2024-07-12 23:00:46 +08:00
|
|
|
|
state = 1;
|
2024-07-11 18:14:13 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|