#includereg52.h#includeintrins.h#defineuintunsignedint#defineucharunsignedchar#defineNOP(){_nop_();_nop_();_nop_();_nop_();}//------LCD引脚-----sbitLCD_RS=P2^6;sbitLCD_RW=P2^5;sbitLCD_EN=P2^7;//------超声波引脚-------sbitTx=P3^3;//触发控制信号输入sbitRx=P3^2;//回响信号输出ucharcodetable[]={DistanceTest:};//LCD第一行显示uchartemp_dis[]={000.0cm};//LCD第二行longintt,distance;ucharcache[4]={0,0,0,0};//--------延时-------voiddelay(uintms){uintt;while(ms--)for(t=0;t120;t++);}//-------读LCD状态-------ucharread_lcd_state(){ucharstate;LCD_RS=0;LCD_RW=1;LCD_EN=1;_nop_();state=P0;LCD_EN=0;_nop_();returnstate;}//-------忙等待------voidlcd_busy_wait(){while((read_lcd_state()&0x80)==0x80);NOP();}//----------LCD写指令----------voidlcd_write_com(ucharcom){lcd_busy_wait();LCD_RS=0;//RS为0时,写指令,RS为1时,写数据LCD_RW=0;P0=com;NOP();LCD_EN=1;NOP();LCD_EN=0;}//----------LCD写数据----------voidlcd_write_data(uchardat){lcd_busy_wait();LCD_RS=1;LCD_RW=0;P0=dat;NOP();LCD_EN=1;NOP();LCD_EN=0;}//-------LCD初始化-------voidlcd_init(){LCD_EN=0;lcd_write_com(0x38);//LCD显示模式设置lcd_write_com(0x0c);//LCD显示开/关及光标设置lcd_write_com(0x06);//当写一个字符后地址指针加1,且光标加1lcd_write_com(0x01);//显示清屏}//---------设置液晶显示位置-----------voidset_lcd_pos(ucharp){lcd_write_com(p|0x80);}//---------液晶显示程序----------voidlcd_print(ucharp,uchar*s,uintlow){uintnum;set_lcd_pos(p);for(num=0;numlow;num++){lcd_write_data(s[num]);delay(1);}}voidHC05_Init(){Tx=1;//触发脉冲NOP();NOP();NOP();NOP();Tx=0;distance=0.17*t;//距离计算}voiddistance_convert(longintdat){cache[0]=dat/1000;cache[1]=dat/100%10;cache[2]=dat/10%10;cache[3]=dat%10;temp_dis[0]=cache[0]+'0';temp_dis[1]=cache[1]+'0';temp_dis[2]=cache[2]+'0';temp_dis[4]=cache[3]+'0';}//------------主程序-----------voidmain(){lcd_init();delay(5);TMOD=0x19;EA=1;//开总中断TR0=1;//启动定时器EX0=1;//开外部中断IT0=1;//设置为下降沿中断方式while(1){HC05_Init();distance_convert(distance);lcd_print(0x01,table,14);lcd_print(0x44,temp_dis,8);}}//外部中断0voidint0()interrupt0{t=(TH0*256+TL0);//计算高电平持续的时间,上升沿到来时候开始计时,下降沿到来进入外部中断,关闭计时器,停止计时TH0=0;TL0=0;}