73 lines
2.0 KiB
C
73 lines
2.0 KiB
C
#include "hcsr04.h"
|
||
|
||
#include "syscalls.h"
|
||
#include "delay.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 = INT32_MAX; // 测量出的距离,单位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);
|
||
|
||
sonor_distance = INT32_MAX;
|
||
}
|
||
|
||
// 启动测距,单位: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); // 输出低电平
|
||
|
||
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;
|
||
sonor_distance = (time_end / 100 < 38) ? (time_end * 346) / 200 : INT32_MAX;
|
||
Sonar_CP_Callback();
|
||
sonor_state = 0;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 测距完毕回调,执行完自定义任务后会将sonor_state置0
|
||
__attribute__((weak)) void Sonar_CP_Callback()
|
||
{
|
||
my_printf(HUART2, "distance = %d (mm)\n", sonor_distance);
|
||
}
|