Car/Peripheral/Src/hcsr04.c

73 lines
2.0 KiB
C
Raw Normal View History

2024-07-11 18:14:13 +08:00
#include "hcsr04.h"
2024-07-20 10:44:59 +08:00
2024-07-15 20:10:12 +08:00
#include "syscalls.h"
2024-07-20 10:44:59 +08:00
#include "delay.h"
#include "tim.h"
2024-07-11 18:14:13 +08:00
2024-07-20 10:44:59 +08:00
static uint64_t time_start; // 声明变量,用来计时
static uint64_t time_end; // 声明变量,存储回波信号时间
uint8_t sonor_state; // 测距状态变量0未测量1正在测量2已测量
uint32_t sonor_distance = INT32_MAX; // 测量出的距离单位mm
2024-07-11 18:14:13 +08:00
2024-07-15 20:10:12 +08:00
void HCSR04_HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
2024-07-11 18:14:13 +08:00
2024-07-13 15:22:46 +08:00
// 初始化超声波测距
void HC_SR04_Init(void)
{
2024-07-13 15:22:46 +08:00
// 禁用JTAG
__HAL_RCC_AFIO_CLK_ENABLE();
__HAL_AFIO_REMAP_SWJ_NOJTAG();
2024-07-11 18:14:13 +08:00
2024-07-13 15:22:46 +08:00
// 注册定时器中断溢出回调
HAL_TIM_RegisterCallback(&htim2, HAL_TIM_PERIOD_ELAPSED_CB_ID, HCSR04_HAL_TIM_PeriodElapsedCallback);
2024-07-20 10:44:59 +08:00
sonor_distance = INT32_MAX;
2024-07-11 18:14:13 +08:00
}
2024-07-13 15:22:46 +08:00
// 启动测距单位mm
uint32_t sonar_mm(void)
{
2024-07-13 15:22:46 +08:00
sonor_state = 1;
2024-07-16 22:39:49 +08:00
HAL_GPIO_WritePin(TRIG_GPIO_Port, TRIG_Pin, GPIO_PIN_SET); // 输出高电平
2024-07-13 15:22:46 +08:00
delay_us(15); // 延时15微秒
2024-07-16 22:39:49 +08:00
HAL_GPIO_WritePin(TRIG_GPIO_Port, TRIG_Pin, GPIO_PIN_RESET); // 输出低电平
2024-07-20 10:44:59 +08:00
2024-07-13 15:22:46 +08:00
return sonor_distance;
2024-07-11 18:14:13 +08:00
}
2024-07-15 20:10:12 +08:00
void HCSR04_HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim == &htim2)
2024-07-15 20:10:12 +08:00
{
// 每10us自增一
++time_start;
2024-07-13 15:59:18 +08:00
}
2024-07-11 18:14:13 +08:00
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
2024-07-16 22:39:49 +08:00
if (GPIO_Pin == ECHO_Pin)
{
2024-07-16 22:39:49 +08:00
if (HAL_GPIO_ReadPin(ECHO_GPIO_Port, ECHO_Pin))
{
2024-07-15 20:10:12 +08:00
time_start = 0;
HAL_TIM_Base_Start_IT(&htim2);
}
else
{
2024-07-15 20:10:12 +08:00
time_end = time_start;
2024-07-11 18:14:13 +08:00
HAL_TIM_Base_Stop_IT(&htim2);
2024-07-13 15:22:46 +08:00
sonor_state = 2;
2024-07-20 10:44:59 +08:00
sonor_distance = (time_end / 100 < 38) ? (time_end * 346) / 200 : INT32_MAX;
2024-07-13 15:22:46 +08:00
Sonar_CP_Callback();
2024-07-20 10:44:59 +08:00
sonor_state = 0;
2024-07-11 18:14:13 +08:00
}
}
}
2024-07-13 15:22:46 +08:00
2024-07-20 10:44:59 +08:00
// 测距完毕回调执行完自定义任务后会将sonor_state置0
2024-07-15 20:10:12 +08:00
__attribute__((weak)) void Sonar_CP_Callback()
{
2024-07-20 10:44:59 +08:00
my_printf(HUART2, "distance = %d (mm)\n", sonor_distance);
2024-07-13 15:22:46 +08:00
}