HCSR04.c
- #include "stm32f1xx_hal.h"
- #include "HCSR04.h"
- float distant1; //测量距离
- float distant2; //测量距离
- uint32_t measure_Buf1[3] = {0}; //存放定时器计数值的数组
- uint32_t measure_Buf2[3] = {0}; //存放定时器计数值的数组
- uint8_t measure_Cnt1 = 0; //状态标志位
- uint8_t measure_Cnt2 = 0; //状态标志位
- uint32_t high_time1; //超声波模块返回的高电平时间
- uint32_t high_time2; //超声波模块返回的高电平时间
-
- //===============================================读取距离
- void SR04_GetData1(void)
- {
- switch (measure_Cnt1){
- case 0:
- TRIG1_H;
- delay_us(30);
- TRIG1_L;
-
- measure_Cnt1++;
- __HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
- HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1); //启动输入捕获 或者: __HAL_TIM_ENABLE(&htim5);
- break;
- case 3:
- high_time1 = measure_Buf1[1]- measure_Buf1[0]; //高电平时间
- distant1=(high_time1*0.034)/2; //单位cm
- printf("\r\n-超声波1检测距离为-%.2f-cm-\r\n",distant1);
- measure_Cnt1 = 0; //清空标志位
- TIM2->CNT=0; //清空计时器计数
- break;
-
- }
- HAL_Delay(100);
- }
- //===============================================读取距离
- void SR04_GetData2(void)
- {
- switch (measure_Cnt2){
- case 0:
- TRIG2_H;
- delay_us(30);
- TRIG2_L;
-
- measure_Cnt2++;
- __HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
- HAL_TIM_IC_Start_IT(&htim3, TIM_CHANNEL_1); //启动输入捕获 或者: __HAL_TIM_ENABLE(&htim5);
- break;
- case 3:
- high_time2 = measure_Buf2[1]- measure_Buf2[0]; //高电平时间
- distant2=(high_time2*0.034)/2; //单位cm
- printf("\r\n-超声波2检测距离为-%.2f-cm-\r\n",distant2);
- measure_Cnt2 = 0; //清空标志位
- TIM3->CNT=0; //清空计时器计数
- break;
-
- }
- HAL_Delay(100);
- }
-
-
- //===============================================us延时函数
- void delay_us(uint32_t us)//主频72M
- {
- uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * us);
- while (delay--)
- {
- ;
- }
- }
-
由于代码过于多,这里就直接给到大家,将下面的代码添加到HCSR04.h
|