赞
踩
欢迎入群共同学习交流
时间记录:2024/5/23
(1)引脚介绍
VCC:电源引脚,接单片机3.3/5V
GND:电源地
Trig:超声信号触发引脚
Echo:超声信号接收引脚
(2)时序图
介绍:通过Trig触发引脚设置一个大于10us的TTL高电平,触发内部循环发送8个40KHZ的超声波,然后通过接收引脚判断接收信号高电平的持续时间,通过声速进行计算来回的距离,如果超过38ms仍未接收到回波也会触发高电平,此时电平持续时间最长
(1)头文件
#ifndef __HCSR04_H__
#define __HCSR04_H__
#include "stm32f10x.h"
/**HC-SR04超声模块初始化*/
void Hcsr04_Init(void);
/**获取距离,单位CM*/
void vGetDistance(float *dis,float temp);
#endif
(2)源文件
#include "hc_sr04.h" #include "delay.h" //端口宏定义 #define Tring_GPIO GPIOB #define Tring_PIN GPIO_Pin_5 #define Echo_GPIO GPIOB #define Echo_PIN GPIO_Pin_6 void Hcsr04_Init(void) { //使能时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); /**初始化GPIO端口*/ GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Pin = Tring_PIN; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(Tring_GPIO,&GPIO_InitStruct); GPIO_InitStruct.GPIO_Pin = Echo_PIN; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPD; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(Echo_GPIO,&GPIO_InitStruct); /**初始化TIM2,进行计时*/ TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStruct.TIM_Period=0xFFFF; TIM_TimeBaseInitStruct.TIM_Prescaler=72-1; //1us计数一次 TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct); TIM_Cmd(TIM2,ENABLE);//使能/开启定时器 } void vGetDistance(float *dis,float temp) { u16 time = 0; /**Tring引脚拉高10us的TTL电平,使模块发送超声波*/ GPIO_SetBits(Tring_GPIO,Tring_PIN); vDelayUs(10); GPIO_ResetBits(Tring_GPIO,Tring_PIN); /*获取回波时间,高电平持续时间38ms为无回波时返回时间*/ while(GPIO_ReadInputDataBit(Echo_GPIO,Echo_PIN) == 0); TIM_SetCounter(TIM2,0); while(GPIO_ReadInputDataBit(Echo_GPIO,Echo_PIN) == 1); time = TIM_GetCounter(TIM2); //计算距离 *dis = time*(334.1+0.6*temp) / 20000; vDelayMs(5); //等待下一次开始,官方建议60ms采样周期,自己根据情况修改 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。