定时器配置:
引脚定义:
SR04.c
#include "SR04.h"
float distant; //测量距离
float Distance_Data;//距离数据存储
uint32_t measure_Buf[3] = {0}; //存放定时器计数值的数组
uint8_t measure_F_Cnt = 0; //状态标志位
uint32_t high_time; //超声波模块返回的高电平时间
//===============================================读取距离
void SR04_GetData(void)
{
switch (measure_F_Cnt)
{
case 0:
TRIG_H;
delay_us(30);
TRIG_L;
measure_F_Cnt++;
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_3, TIM_INPUTCHANNELPOLARITY_RISING);
HAL_TIM_IC_Start_IT(&htim3, TIM_CHANNEL_3); //启动输入捕获
break;
case 3:
high_time = measure_Buf[1]- measure_Buf[0]; //高电平时间
//printf("\r\n----高电平时间-%d-us----\r\n",high_time); //串口显示
distant=(high_time*0.034)/2; //单位cm
//printf("\r\n-检测距离为-%.2f-cm-\r\n",distant); //串口显示
Distance_Data = distant;
measure_F_Cnt = 0; //清空标志位
TIM3->CNT=0; //清空计时器计数
break;
}
}
//===============================================us延时函数
void delay_us(uint32_t us)//主频72M
{
uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * us);
while (delay--)
{
;
}
}
//===============================================中断回调函数
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)//
{
if(TIM3 == htim->Instance)// 判断触发的中断的定时器为TIM3
{
switch(measure_F_Cnt){
case 1:
//获取当前的捕获值.
measure_Buf[0] = HAL_TIM_ReadCapturedValue(&htim3,TIM_CHANNEL_3);
//设置为下降沿捕获
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3,TIM_CHANNEL_3,TIM_ICPOLARITY_FALLING);
measure_F_Cnt++;
break;
case 2:
//获取当前的捕获值.
measure_Buf[1] = HAL_TIM_ReadCapturedValue(&htim3,TIM_CHANNEL_3);
//停止捕获 或者: __HAL_TIM_DISABLE(&htim5);
HAL_TIM_IC_Stop_IT(&htim3,TIM_CHANNEL_3);
measure_F_Cnt++;
}
}
}
SR04.h
#ifndef __SR04_H
#define __SR04_H
#include "main.h"
#include "tim.h"
#include "stdio.h"
#define TRIG_H HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET)
#define TRIG_L HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET)
extern float Distance_Data;
void delay_us(uint32_t us);
void SR04_GetData(void);
#endif
main.c
void csb_SR04_mainloop(void)//超声波
{
if(!f_1500ms)return;
f_1500ms = 0;
SR04_GetData();
}