蓝桥杯超声波是TX.RX来驱动。
在超声波模块当中,一块为发生端,一块为接收端,当程序执行的时候,发射端发送声波检测到距离,接受端快速返回并在数码管上显示
计算公式
距离L = 声速V × 发出到接收的时间T/2
发射电路:
接收电路:
跳线帽一定要接住
超声波传感器的谐振频率(中心频率)有23kHz、40kHz、75kHz、200kHz、400kHz等,蓝桥杯CT107D使用谐振为40KHZ的超声波。使用超声波模块前需要将跳帽的1-3 , 2-4连接其中发送端N_A1连接单片机的P10引脚,接收端N_B1连接单片机的P11
#include <STC15F2K60S2.H>
sbit TX = P1^0;
sbit RX = P1^1;
unsigned int distance;//距离
unsigned char dis_stat = 0;
unsigned char code SMG_duanma[18] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};
unsigned char flag=0;
void SMG_down();
void Init_Timer()
{
TMOD= 0x00;//13位定时器
}
//超声波信号发射
void Send_40hz_wave()
{
unsigned char i = 8;
//12Mhz的12分频,间隔定时12us
TR0 = 0;
TL0 = 0XF4;
TH0 = 0XFF;
TF0 = 0;
TR0 = 1;
//发射8个Mhz的超声波信号
while(i--)
{
TX = 0;
while(TF0 == 0);
TF0 = 0;
TX = 1;
while(TF0 == 0);
TF0 = 0;
}
}
//距离测量
void Measure_dis()
{
//先发送8个40Mhz的方波,如果碰到障碍物,则原路返回
Send_40hz_wave();
//每次测距的最大时间为0xfff,即8191us
//也就是,超声波最大测距为,0.017*8191 = 139cm
TR0 = 0;
TL0 = 0X00;
TH0 = 0XE0;
TF0 = 0;
TR0 = 1;
//等待超声波返回,或者定时器溢出
while((RX == 1)&&(TF0 == 0));
TR0 = 0;
//如果定时器溢出则显示最大值999
if(TF0 == 1)
{
distance = 0;//之前999
}
//超声波速度取334 m/s
//距离L = (334m/s * t) / 2 = 172m/s * t
//t 取毫秒,即:L = 0.0172m/us*t
else
{
distance = ((TH0 & 0x1f) << 8 | TL0) * 0.0172;
}
}
void Seclect_HC138(unsigned char channl)
{
switch(channl)
{
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
case 8:
P2 = (P2 & 0x1f) | 0x00;
break;
}
}
void Init_SMG(unsigned char date,unsigned char pos)
{
Seclect_HC138(6);
P0 = 0x01 << pos;
Seclect_HC138(7);
P0 = date;
}
void delay_smg(unsigned char i)
{
unsigned char x,y;
for(x = i;x>0;x--)
for(y = 114;y>0;y--);
}
void SMG_display()
{
if(distance > 0)
{
if(distance > 99)
{
Init_SMG( SMG_duanma[distance / 100],5);
delay_smg(10);
}
if(distance > 9)
{
Init_SMG( SMG_duanma[(distance % 100) / 10],6);
delay_smg(10);
}
Init_SMG( SMG_duanma[distance % 10],7);
delay_smg(10);
}
if(distance == 0)
{
Init_SMG(0xff,5);
delay_smg(10);
Init_SMG(0xff,6);
delay_smg(10);
Init_SMG(0xff,7);
delay_smg(10);
}
}
void main()
{
Init_Timer();
while(1)
{
SMG_display();
SMG_display();
Measure_dis();
}
}