目录
实验准备
传感器-超声波模块
特点
超声波测距模块可提供 2cm-450cm 的非接触式距离感测功能,测距精度可达高 到 3mm;模块包括超声波发射器、接收器与控制电路。
基本工作原理
(1)采用 IO 口 TRIG 触发测距,给最少 10us 的高电平信呈。
(2)模块自动发送 8 个 40khz 的方波,自动检测是否有信号返回;
(3)有信号返回,通过 IO 口 ECHO 输出一个高电平,高电平持续的时间就是超声 波从发射到返回的时间。测试距离=(高电平时间*声速(340M/S))/2;
实物图
电气参数
引脚使用
传感器Trig接口是接收端,我们需要用输出引脚给它传参数
传感器Echo接口是发送端,我们需要用输入引脚接收参数
流程图
实验步骤
- 时钟使能
- GPIO参数配置
- 发送信号
- 接收信号
- 计算时间
- 转换时间为距离
- 结果打印
代码
Hysrf.c
#include "stm32f4xx.h" // Device header
#include "BitBand.h"
#include "delay.h"
//#include "beep.h"
#include<stdio.h>
void Hysrf05_Init()
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
//PF12输出引脚-->Trig
GPIO_InitTypeDef GPIO_Initstruct;
GPIO_Initstruct.GPIO_Mode=GPIO_Mode_OUT;
GPIO_Initstruct.GPIO_OType=GPIO_OType_PP;
GPIO_Initstruct.GPIO_Pin=GPIO_Pin_12;
GPIO_Initstruct.GPIO_PuPd=GPIO_PuPd_NOPULL;
GPIO_Initstruct.GPIO_Speed=GPIO_High_Speed;
GPIO_Init(GPIOF,&GPIO_Initstruct);
//PF11输入引脚-->Echo
GPIO_Initstruct.GPIO_Mode=GPIO_Mode_IN;
GPIO_Initstruct.GPIO_OType=GPIO_OType_OD;
GPIO_Initstruct.GPIO_Pin=GPIO_Pin_11;
GPIO_Initstruct.GPIO_PuPd=GPIO_PuPd_DOWN;
GPIO_Initstruct.GPIO_Speed=GPIO_High_Speed;
GPIO_Init(GPIOF,&GPIO_Initstruct);
}
uint32_t Get_S_Hysrf05()
{
uint32_t time=0;
while(1)
{
//给予10us的高电压,完成触发动作
PFout(12)=1;
delay_us(10);
//获得信号
PFout(12)=0;
while(PFin(11)==0)
{
time++;
delay_us(10);
if(time>=2000)
{
printf("time out\n");
break;
}
}
//等待PF11(Echo)为高电压,统计时间
time=0;
while(PFin(11)==1)
{
//用time的值计算高电平维持了几微秒
time++;
delay_us(8);
}
// delay_ms(1000);
// printf("time=%d\n",time);
int s=time*17;
s = s/10;
printf("距离为%d mm\n",s);
time=0;
return s;
}
}
Hysrf.h
声明.c文件中的函数
#include "stm32f4xx.h" // Device header
#include<stdio.h>
void Hysrf05_Init(void);
uint32_t Get_S_Hysrf05(void);
main.c
模拟倒车时绿灯、黄灯、红灯
距离越近蜂鸣器声音越急促
灯颜色变化闪烁变快
#include "stm32f4xx.h" // Device header
#include "led.h"
#include "key.h"
#include "BitBand.h"
#include "pir.h"
#include "delay.h"
#include <stdio.h>
#include "usart.h"
#include "Hysrf.h"
#include "Beep.h"
int main()
{
uint32_t time=0;
uint32_t i = 0;
Led_Init();
Pir_Init();
Usart_Init();
Hysrf05_Init();
Beep_Init();
int s=0;
while(1)
{
s=Get_S_Hysrf05();
//模拟倒车时绿灯、黄灯、红灯
//距离越近蜂鸣器声音越急促
//灯颜色变化闪烁变快
if(s > 200)//20cm
{
PFout(13)=1;
Beep_Once(1000,8000);
delay_ms(500);
PFout(13)=0;
}
else if (s > 100)//10cm
{
PFout(2)=1;
Beep_Once(1000,8000);
delay_ms(250);
PFout(2)=0;
}
else if(s > 50)//5cm
{
PFout(15)=1;
Beep_Once(1000,8000);
delay_ms(100);
PFout(15)=0;
}
else
{
PFout(13)=1;
PFout(2)=1;
PFout(15)=1;
Beep_Once(1000,8000);
delay_ms(50);
}
PFout(13)=0;
PFout(2)=0;
PFout(15)=0;
}
return 0;
}
实验结果
串口接收器显示
距离不同,打印数据不同