1.给超声波模块接入电源和地。
2.给trig输入一个长为20us的高电平方波
3.输入方波后,模块会自动发射8个40KHz的声波,echo的电平会由0变为1
4.当超声波返回被模块接收到时,回波引 脚端的电平会由1变为0。定时器记下的这个时间即为超声波由发射到返回的总时长。
5.根据声波在空气中的速度为344米/秒,即可计算出所测的距离。
以下为程序:
#include "stm32f4xx.h"
#include "usart.h"
#include "delay.h"
void GPIO_Configuration()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
/*echo*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_Init(GPIOF, &GPIO_InitStructure);
/*trig*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_Init(GPIOF, &GPIO_InitStructure);
}
void TIM2_Configuration(u16 arr, u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructrue;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_DeInit(TIM2);
TIM_TimeBaseStructrue.TIM_Period = arr;
TIM_TimeBaseStructrue.TIM_Prescaler = psc;
TIM_TimeBaseStructrue.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructrue.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructrue);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel=TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2, DISABLE);
}
u16 TIM2_Flag;
u16 get_Diatance()
{
int distance = 0;
u16 TIM = 0;
TIM_Cmd(TIM2, ENABLE);
GPIO_SetBits(GPIOF, GPIO_Pin_6);
delay_us(30);
GPIO_ResetBits(GPIOF, GPIO_Pin_6);
while((!GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_5))&&TIM2_Flag==0);
TIM2->CNT = 0;
while(GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_5)&&TIM2_Flag==0);
TIM_Cmd(TIM2, DISABLE);
if(TIM2_Flag==1)
TIM2_Flag = 0;
TIM = TIM_GetCounter(TIM2);
distance = TIM*0.85;
return distance;
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
TIM2_Flag=1;
}
}
#ifndef __CS_H
#define __CS_H
#include "sys.h"
void GPIO_Configuration();
void TIM2_Configuration(u16 arr,u16 psc);
u16 get_Diatance(void);
void TIM2_IRQHandler(void);
void LED_Init(void);
#endif
#include "stm32f4xx.h"
#include "usart.h"
#include "delay.h"
#include "lcd.h"
#include "cs.h"
extern u16 TIM2_Flag;
int main(void)
{
u16 diatance_Data;
u16 q;
u16 b;
u16 s;
u16 g;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
delay_init(168);
uart_init(115200);
GPIO_Configuration();
TIM2_Configuration(5000,419);
POINT_COLOR=RED;
while (1)
{
diatance_Data = get_Diatance();
q = diatance_Data/1000;
b = diatance_Data/100%10;
s = diatance_Data/10%10;
g = diatance_Data%10;
diatance_Data = q*1000+b*100+s*10+g;
POINT_COLOR=BLUE;
printf("%d\n",diatance_Data);
delay_ms(1000);
}
}
如若有不懂的可以下载代码进行查看学习:stm32f407使用超声波HC_SR04-C/C++文档类资源-CSDN下载
本人联系方式,欢迎打扰: