新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 基于C8051單片機超聲波測距電平觸發(fā)編寫

基于C8051單片機超聲波測距電平觸發(fā)編寫

作者: 時間:2016-11-29 來源:網(wǎng)絡(luò) 收藏
#include
#include #define uchar unsigned char#define uint unsigned intvoid SYSCLK_Init (void);void PORT_Init (void); void  StartModule() ;void display(unsigned char bai,unsigned char shi,unsigned char ge);void delay(unsigned int z);void timerinit();void delay(unsigned int z);void Timer_Count(void);unsigned int  time=0;uchar i;uchar j;unsigned long S=0;unsigned char qian,bai,shi,ge;bit flag =0;sbit lcdrs=P2^5;sbit lcden=P2^7;sbit lcdwr=P2^6;sbit  RX = P0^1;sbit  TX = P0^0;uchar abc[]={0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39};   //1234567;uchar result[3];void delay(void){int a=10000;while(a!=0){a--;}}void write_com(uchar com){lcdrs=0;P3=com;delay();lcden=1;delay();lcden=0;}void write_date(uchar dat){lcdrs=1;P3=dat;delay();lcden=1;delay();lcden=0;}void init(){lcdwr=0;lcden=0;write_com(0x38);write_com(0x0c);write_com(0x06);write_com(0x01);}void main(){unsigned int valA;WDTCN = 0xde;WDTCN = 0xad; timerinit();                      SYSCLK_Init ();                                                                 PORT_Init ();                        init();lcdrs=0;lcdwr=0;write_com(0x40);while(1){    RX=1;StartModule();for(valA=100;valA>0;valA--){if(RX==1){Timer_Count();}}}}void SYSCLK_Init (void){OSCICN = 0x05;                                                                                  }void PORT_Init (void){XBR0    = 0x04;                     // Enable UART0XBR1    = 0x00;XBR2    = 0x40;                     // Enable crossbar and weak pull-upsP0MDOUT |= 0xff;                    // enable TX0 as a push-pull outputP2MDOUT  = 0xe0;                    // P2口設(shè)為推挽方式P3MDOUT  = 0xff;                    // P2口設(shè)為推挽方式      }void Conut(void){time=TH0*256+TL0;TH0=0;TL0=0;S=(uint)(time*1.7*1.6*1.5)/10;     //算出來是MMif((S>=7000)||flag==1) //超出測量范圍顯示“-”{ flag=0;display(0x80,0x80,0x80);}else{bai=S/100;shi=S%100/10;ge=S%10;display(bai,shi,ge);}}void zd0() interrupt 1    //T0中斷用來計數(shù)器溢出,超過測距范圍{flag=1;        //中斷溢出標(biāo)志RX=0;}void  StartModule()            //啟動模塊{TX=1;                        //啟動一次模塊_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();/*   _nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();*/TX=0;}void Timer_Count(void){TR0=1;       //開啟計數(shù)while(RX);   //當(dāng)RX為1計數(shù)并等待TR0=0;    //關(guān)閉計數(shù)Conut();   //計算}void timerinit(){TMOD=0x01;     //設(shè)T0為方式1,GATE=1;TH0=0;TL0=0;         ET0=1;             //允許T0中斷EA=1;      //開啟總中斷   }/*********************************************************/void display(unsigned char bai,unsigned char shi,unsigned char ge){ uchar i;result[0]=abc[bai];result[1]=abc[shi];result[2]=abc[ge];write_com(0x40);for(i=0;i<3;i++){write_com(0x80+i+1);write_date(result[i])  ;}}


評論


技術(shù)專區(qū)

關(guān)閉