#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超声波发送,触发控制信号输入
sbit echo=P3^2; //RX超声波接受,回响信号的输出
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中断用来扫描数码管和计800MS启动模块
{
trig=1; //800MS 启动一次模块
_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; //高电平的计数位
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写数据
{
lcdrs=1;
lcdrw=0;
P0=date;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void lcd_init() //LCD初始化
{
lcd_write_com(0x38); //显示模式设置
lcd_write_com(0x0c); //LCD显示开/关及光标设置
lcd_write_com(0x06); //当写一个字符后地址指针加1,且光标加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; //设T0为方式1,GATE=1;
TH0=0;
TL0=0;
TR0=1;
ET0=1; //允许T0中断
EA=1;
while(1)
{ HC_init();
StartModule();
while(!echo); //当RX(echo)为零时等待while(echo==1)
TR0=1; //开启计数
while(echo); //当RX为1计数并等待
TR0=0; //关闭计数
conut(); //计算
delay(10); //100MS
distance_convert(distance);
lcd_display();
delay(20);
}
}
/********************************************************/
void zd0() interrupt 1 //T0中断用来计数器溢出,超过测距范围
{
flag=1; //中断溢出标志
}
|