/***********************************************************************************************************/
//hc-sr04 超聲波測距模塊 DEMO 程序
//晶振:11。0592
//接線:模塊TRIG接 P0.2 ECH0 接P0.1
//數碼管:共陽數碼管P1接數據口,P2.5 P2.4 P2.3接選通數碼管
/***********************************************************************************************************/
#include <reg52.h> //器件配置文件
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit RX = P1^3;
sbit TX = P1^4;
sbit wela = P2^7;
sbit dula = P2^6;
unsigned int time=0;
unsigned int timer=0;
unsigned long S=0;
bit flag =0;
sbit rw=P1^1;
sbit rs=P1^0;
sbit lcden=P2^5;
uchar disbuff[]={0,0,0,0};
uchar code table[]={"wrong"};
uchar code table1[]={"Welcome to use!"};
//液晶部分
void delay(uint z) //延時函數
{
uint x,y;
for(x=z;x>0;x--)
for(y=50;y>0;y--);
}
void write_com(uchar com) //寫命令
{
rs=0;
lcden=0;
P0=com;
lcden=1;//只有在一個高脈沖下數據才被寫入
delay(2);
lcden=0;
}
void write_date(uchar date)//寫數據
{
rs=1;
lcden=0;
P0=date;
lcden=1;//只有在一個高脈沖下數據才被寫入
delay(2);
lcden=0;
}
void display()//刷新顯示函數
{
uchar k;
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(time*1.7)/100; //算出來是CM
if((S>=700)||flag==1) //超出測量范圍顯示“-”
{
write_com(0x80+0x40+6);
for(k=0;k<5;k++)
write_date(table[k]);
flag=0;
}
else
{
disbuff[0]=S%1000/100;
disbuff[1]=S%1000%100/10;
disbuff[2]=S%1000%10 %10;
write_com(0x80+0x40+6);
write_date(0x30+disbuff[0]);
write_date(0x30+disbuff[1]);
write_date(0x30+disbuff[2]);
write_date('c');
write_date('m');
}
}
void yejininit()
{
uint p;
dula=1;
P0=0x00;
dula=0;
wela=1;
P0=0xff;
wela=0;
rw=0;
rs=0;
lcden=0;
write_com(0x38); //設置16*2顯示,5*7點陣,8位數據接口
write_com(0x0c); //開顯示,不開光標,不閃動
write_com(0x06); //寫一個字符后地址加1,不整屏移動
write_com(0x01); //顯示清0;;市局指針清0
write_com(0x80);
for(p=0;p<15;p++)
write_date(table1[p]);
}
/********************************************************/
void zd0() interrupt 1 //T0中斷用來計數器溢出,超過測距范圍
{
flag=1; //中斷溢出標志
}
/********************************************************/
void zd3() interrupt 3 //T1中斷用來掃描數碼管和計800MS啟動模塊
{
TH1=0xf8;
TL1=0x30;
timer++;
if(timer>=400)
{
timer=0;
TX=1; //800MS 啟動一次模塊
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
TX=0;
}
}
/*********************************************************/
void main( void )
{
TMOD=0x11; //設T0為方式1,GATE=1;
TH0=0;
TL0=0;
TH1=0xf8; //2MS定時
TL1=0x30;
ET0=1; //允許T0中斷
ET1=1; //允許T1中斷
TR1=1; //開啟定時器
EA=1; //開啟總中斷
yejininit();
while(1)
{
while(!RX); //當RX為零時等待
TR0=1; //開啟計數
while(RX); //當RX為1計數并等待
TR0=0;
display(); //關閉計數
}
}
|