Car/User/Src/hcsr04.c

72 lines
2.2 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "hcsr04.h"
#include "stm32f1xx_hal_tim.h"
#include "tim.h"
uint64_t time; // 声明变量,用来计时
uint64_t time_end; // 声明变量,存储回波信号时间
uint8_t sonor_state = 1; // 测距状态变量0未测量1正在测量2已测量
uint32_t sonor_distance; // 测量出的距离单位mm
void HCSR04_HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim);
// 初始化超声波测距
void HC_SR04_Init(void)
{
// 禁用JTAG
__HAL_RCC_AFIO_CLK_ENABLE();
__HAL_AFIO_REMAP_SWJ_NOJTAG();
// 注册定时器中断溢出回调
HAL_TIM_RegisterCallback(&htim2, HAL_TIM_PERIOD_ELAPSED_CB_ID, HCSR04_HAL_TIM_PeriodElapsedCallback);
}
// 启动测距单位mm
uint32_t sonar_mm(void)
{
sonor_state = 1;
HAL_GPIO_WritePin(Trig_GPIO_Port, Trig_Pin, GPIO_PIN_SET); // 输出高电平
delay_us(15); // 延时15微秒
HAL_GPIO_WritePin(Trig_GPIO_Port, Trig_Pin, GPIO_PIN_RESET); // 输出低电平
if (time_end / 100 < 38)
{ // 判断是否小于38毫秒大于38毫秒的就是超时直接调到下面返回0
sonor_distance = (time_end * 346) / 2; // 计算距离25°C空气中的音速为346m/s
sonor_distance = sonor_distance / 100; // 因为上面的time_end的单位是10微秒所以要得出单位为毫米的距离结果还得除以100
}
return sonor_distance;
}
void HCSR04_HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim)
{
if (htim == &htim2)
{ // 每10us自增一
time++;
}
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if (GPIO_Pin == Echo_Pin)
{
if (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin))
{
HAL_TIM_Base_Start_IT(&htim2);
time = 0;
}
else
{
time_end = time;
HAL_TIM_Base_Stop_IT(&htim2);
sonor_state = 2;
Sonar_CP_Callback();
sonor_state = 0;
}
}
}
// 测距完毕回调执行完自定义任务后将sonor_state置0void
__attribute__((weak)) void Sonar_CP_Callback(void)
{
printf("distance = %d (mm)\n", sonor_distance);
}