资源描述:
《超声波测距程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#defineucharunsignedchar#defineuintunsignedint#defineulongunsignedlonguinttemp=0;datauinti;datauchardispram[5];ucharcodetable[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0x0F8,0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E,0xBF,0xFF};//"0","1","2","3","4","5","6","7"
2、,"8","9","A","B","C","D","E","F","-",""sbitb=P1^0;sbitt=P1^7;voidcs_t();//超声波发生函数voiddelay(uintz);voidyanshi(uinta);voiddisplay();datauchartestok;voidmain(){dataulongtime;P0=0xff;P2=0xff;TMOD=0x11;IE=0x80;while(1){cs_t();delay(1);//TR0=1;testok=0;EX0=1;ET0=1;while(!testok)display();//等待接收完
3、毕。if(1==testok)//距离计算{time=TH0;time=(time<<8)
4、TL0;time*=172;//声音传播速度,1/2(172)为往返路程的一半time/=10000;if(time<=10)//当距离小于等于10CM的时候P1^7变为低电平{t=0;}else{t=1;}dispram[0]=table[time%10];//倒数第一位time/=10;dispram[1]=table[time%10];//倒数第二位time/=10;dispram[2]=table[time%10];//倒数第三位dispram[3]=(time/10);//
5、if(0==dispram[3])dispram[3]=table[17];}else{dispram[0]=table[16];dispram[1]=table[16];dispram[2]=table[16];dispram[3]=table[16];}for(i=0;i<100;i++)display();}}voiddisplay(){P2=0xfe;P0=dispram[0];yanshi(2);P2=0xfd;P0=dispram[1];yanshi(2);P2=0xfb;P0=dispram[2];yanshi(2);P2=0xf7;P0=dispram[3]
6、;yanshi(2);}/*超声接收程序(外中断0)*/voidcs_r(void)interrupt0{TR0=0;ET0=0;EX0=0;testok=1;}/*超时清除程序(内中断T0)*/voidovertime(void)interrupt1{EX0=0;TR0=0;ET0=0;testok=2;}voidcs_t(){ucharlop;lop=20;TH0=0x00;TL0=0x00;TR0=1;while(lop--){b=~b;_nop_();_nop_();_nop_();_nop_();_nop_();}}voidyanshi(uinta){uintx,
7、y;for(x=a;x>0;x--)for(y=110;y>0;y--);}voiddelay(uintz){while(z--);}1脚:接地2脚:接P3.2口3脚:接P1.0口4脚:接VCC,5V