在使用超声波,必须将蓝桥杯板子上的J2的1和3,2和4脚用跳线帽连在一起。
原理图:
我们通过P10和P11来分别发送和接收,利用声音在空气中的传播速度为340m/s,来计算出板子到阻挡物之间的距离
重点代码:1.位定义
sbit TX = P1^0; sbit RX = P1^1;
2.定时器初始化及发送接收函数
void Time0Init()
{
AUXR &= 0x7f;
TMOD &= 0xf0;
TL0 = 0xF4;
TH0 = 0xFF;
TF0 = 0;
TR0 = 0;
}
unsigned char Ware_Recv()
{
unsigned char ucDist, ucNum = 10;
TX = 0;
TL0 = 0xf4;
TH0 = 0xff;
TR0 = 1;
while(ucNum--)
{
while(!TF0);
TX ^= 1;
TF0 = 0;
}
TR0 = 0;
TL0 = 0;
TH0 = 0;
TR0 = 1;
while(RX && !TF0);
TR0 = 0;
if(TF0)
{
TF0 = 0;
ucDist = 255;
}
else
{
ucDist = ((TH0<<8)+TL0)*0.017;
}
return ucDist;
}
实战源码:
#include#include "intrins.h" sfr AUXR = 0x8e; sbit TX = P1^0; sbit RX = P1^1; typedef unsigned char u8; typedef unsigned int u16; u8 yi,er,san,si,wu,liu,qi,ba; u16 dds; unsigned char code smg_duanma[]={ 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8, 0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e, 0xbf,0x7f }; void SelectHC573(u8 channel) { switch(channel) { case 0: P2=P2&0x1f|0x00; break; 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; } } void Display_bit(u8 pos,u8 vlaue) { SelectHC573(6);P0=0x01< 这个代码雏形出自于官方,和一般的使用12ms延时具有一定的不闪屏的优点。



