72 lines
2.2 KiB
C
72 lines
2.2 KiB
C
#include "hcsr04.h"
|
||
#include "tim.h"
|
||
|
||
static uint64_t time_start; // 声明变量,用来计时
|
||
static uint64_t time_end; // 声明变量,存储回波信号时间
|
||
uint8_t sonor_state; // 测距状态变量,0:未测量,1:正在测量,2:已测量
|
||
uint32_t sonor_distance; // 测量出的距离,单位mm
|
||
|
||
void delay_us(uint16_t us);
|
||
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_start;
|
||
}
|
||
}
|
||
|
||
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
|
||
{
|
||
if (GPIO_Pin == Echo_Pin)
|
||
{
|
||
if (HAL_GPIO_ReadPin(Echo_GPIO_Port, Echo_Pin))
|
||
{
|
||
time_start = 0;
|
||
HAL_TIM_Base_Start_IT(&htim2);
|
||
}
|
||
else
|
||
{
|
||
time_end = time_start;
|
||
HAL_TIM_Base_Stop_IT(&htim2);
|
||
sonor_state = 2;
|
||
Sonar_CP_Callback();
|
||
}
|
||
}
|
||
}
|
||
|
||
// 测距完毕回调,执行完自定义任务后将sonor_state置0
|
||
__attribute__((weak)) void Sonar_CP_Callback()
|
||
{
|
||
printf("distance = %d (mm)\n", sonor_distance);
|
||
sonor_state = 0;
|
||
}
|