#include<reg52.h>
#include <intrins.h>
#include <STDIO.H>
#define uchar unsigned char
#define uint unsigned int
sbit lcdrs=P3^5;
sbit lcdrw=P3^6;
sbit lcden=P3^4;
sbit trig=P1^0; //TX超聲波發(fā)送,觸發(fā)控制信號(hào)輸入
sbit echo=P3^2; //RX超聲波接受,回響信號(hào)的輸出
bit flag=0;
uint time;
#define NOP() {_nop_();_nop_();_nop_(); }
uchar table[]="Distance:";
uchar dis[]="000.0cm";
uchar cache[4]={0,0,0,0};
uint distance,t;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=121;y>0;y--);
}
void StartModule() //T1中斷用來掃描數(shù)碼管和計(jì)800MS啟動(dòng)模塊
{
trig=1; //800MS 啟動(dòng)一次模塊
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
trig=0;
}
void distance_convert( uint dat)
{
cache[0]=dat/100;
cache[1]=dat%100/10;
cache[2]=dat%10;
cache[3]=dat*10%10;
dis[0]=cache[0]+'0';
dis[1]=cache[1]+'0';
dis[2]=cache[2]+'0';
dis[4]=cache[3]+'0';
}
void count(void)
{
time=TH0*256+TL0; //高電平的計(jì)數(shù)位
TH0=0; //初始化
TL0=0; //初始化
distance=(time*1.7)/100; //算出來是CM
if(flag==1) //超出測量
{
flag=0;
printf("-----\n");
}
printf("distance=%f\n",distance);
}
void lcd_write_com(uchar com) //LCD寫指令
{
lcdrs=0;
lcdrw=0;
P0=com;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void lcd_write_data(uchar date) //LCD寫數(shù)據(jù)
{
lcdrs=1;
lcdrw=0;
P0=date;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void lcd_init() //LCD初始化
{
lcd_write_com(0x38); //顯示模式設(shè)置
lcd_write_com(0x0c); //LCD顯示開/關(guān)及光標(biāo)設(shè)置
lcd_write_com(0x06); //當(dāng)寫一個(gè)字符后地址指針加1,且光標(biāo)加1
lcd_write_com(0x01);
}
void lcd_dispaly()
{
uint num;
lcd_write_com(0x80+1);
num=0;
while(table[num]!='\0')
{
lcd_write_data(table[num]);
num++;
delay(10);
}
lcd_write_com(0x80+0x40+1);
num=0;
while(dis[num]!='\0')
{
lcd_write_data(dis[num]);
num++;
delay(10);
}
}
void main()
{
lcd_init();
TMOD=0x01; //設(shè)T0為方式1,GATE=1;
TH0=0;
TL0=0;
TR0=1;
ET0=1; //允許T0中斷
EA=1;
while(1)
{ HC_init();
StartModule();
while(!echo); //當(dāng)RX(echo)為零時(shí)等待while(echo==1)
TR0=1; //開啟計(jì)數(shù)
while(echo); //當(dāng)RX為1計(jì)數(shù)并等待
TR0=0; //關(guān)閉計(jì)數(shù)
conut(); //計(jì)算
delay(10); //100MS
distance_convert(distance);
lcd_display();
delay(20);
}
}
/********************************************************/
void zd0() interrupt 1 //T0中斷用來計(jì)數(shù)器溢出,超過測距范圍
{
flag=1; //中斷溢出標(biāo)志
}
|