1. 程式人生 > >超聲波測距模組(LCD顯示)—基於51微控制器

超聲波測距模組(LCD顯示)—基於51微控制器

#include <reg52.h>

#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;

}