超声波测距模块(1602LCD显示)—基于51单片机

#include 



#define uint unsigned int

#define uchar unsigned char





sbit Trig = P1^0; //控制端

sbit Echo = P1^1; //接收端

sbit dula = P2^6;

sbit wela = P2^7;

sbit RS = P3^5;

sbit RW = P3^6;

sbit EN = P3^4;





uchar table[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};

uchar table1[] = {0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,0x87,0xff,0xef};//带小数点的数





void timer0_init()//定时器0,1的初始化

{

    TMOD = 0x11;

TH0 = 0;

TL0 = 0;

TR0 = 1;

ET0 = 1;

TH1 = 0xaf;

TR1 = 1;

ET1 = 1;

EA = 1;

} 





void DelayUs2x(uchar t)//大约延时t*2+5us

{

    while(--t);

} 





void delayMs(uchar x)

{

    uint i,j;

for(i = x;i > 0;i--)

for(j = 100;j > 0;j--);

}



//判断液晶忙,如果忙则等待

void delay(int z)

{

       int x,y;

       for(x=z;x>0;x--)

       for(y=114;y>0;y--);

}

void Read_Busy()

{

       uchar busy;

       P0 = 0xff;

       RS = 0;

       RW = 1;

       do

       {

              EN = 1;

              busy = P0;

              EN = 0;

       }while(busy & 0x80);

}

//写LCD1602命令一个字节

void Write_Cmd(uchar cmd)

{

       Read_Busy();//判断忙

       RS = 0;

       RW = 0;

       P0 = cmd;

       EN = 1;

       EN = 0;

}

//写一个字节数据

void Write_Dat(uchar dat)

{

       Read_Busy();

       RS = 1;

       RW = 0;

       P0 = dat;

       EN = 1;

       EN = 0;

}





uint distance,time;

void main()

{

       timer0_init();

       Trig = 0;

       Echo = 0;

       Write_Cmd(0x38);//设置16*2显示

       Write_Cmd(0x0f);//开显示 显示光标,光标闪烁

       Write_Cmd(0x01);//清屏



       while(1)

       {

              Write_Cmd(0x01);        

              Write_Cmd(0x06);

              Write_Cmd(0x80|0x02);

                     Write_Dat((distance/1000)+'0');//将所算距离的每一位以字符形式输出

                     Write_Dat(((distance/100)%10)+'0');

                     Write_Dat(((distance/10)%10)+'0');

                     Write_Dat('.');

                     Write_Dat((distance%10)+'0');      

              delay(10);

       }

}





void timer0()interrupt 1

{

       TH0 = 0;

       TL0 = 0;

} 

void timer1()interrupt 3{



              Trig = 1;

       DelayUs2x(5);//给至少10us的高电平信号

       Trig = 0;

       while(Echo == 0);//等待高电平

       TR0 = 1;

       while(Echo);//等待低电平

       P3 = 0xf0;

       TR0 = 0;

       time = TH0*256+TL0;//time为毫秒级时间

       distance = (int)(time*0.017*10);//根据声速为每秒三百四十米计算

       TH0 = 0;

       TL0 = 0;

}

 

你可能感兴趣的:(超声波测距模块(1602LCD显示)—基于51单片机)