51单片机超声波模块测距代码
TX,Rx分别是发射和接受,需要注意的是管脚号别用P2和P0口,那是数码显示
#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
bit succeed_flag;
uint time;
uchar time_H,time_L;
sbit TX=P1^0;
sbit RX=P1^1;
sbit wei1=P2^4;
sbit wei2=P2^5;
sbit wei3=P2^6;
sbit wei4=P2^7;
unsigned char ge,shi,bai;
unsigned int time=0;
unsigned int timer=0;
unsigned char posit=0;
unsigned long S=0;
bit flag =0;
unsigned char table[] ={ 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void delay_10us(void)
{
unsigned char a,b;
for(b=1;b>0;b--)
for(a=52;a>0;a--);
}
void delay(unsigned char i)
{
unsigned char j,k;
for(j=i;j>0;j--)
for(k=125;k>0;k--);
}
void display(unsigned int dat)
{
ge=dat%100%10;
shi=dat%100/10;
bai=dat/100;
P0=table[bai];
wei1=0;
wei2=1;
wei3=0;
wei4=0;
delay(5);
P0=table[shi];
wei1=0;
wei2=0;
wei3=1;
wei4=0;
delay(5);
P0=table[ge];
wei1=0;
wei2=0;
wei3=0;
wei4=1;
delay(5);
}
void main()
{
uint distance;
TX=0;
EA=1;
TMOD=0x10;
while(1)
{
EA=0;
TX=1;
delay_10us();
TX=0;
while(RX==0);
succeed_flag=0;
EA=1;
TH1=0;
TL1=0;
TF1=0;
TR1=1;
while(RX==1);
TR1=0;
EX0=0;
time_H=TH1;
time_L=TL1;
time=time_H;
time=time<<8;
time=time|time_L;
distance=time/58;
display(distance);
}
}
void timer1() interrupt 3
{
TH1=0;
TL1=0;
}