|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区
您需要 登录 才可以下载或查看,没有账号?立即注册
×
#include<reg52.h>//#include<delay.h>#include <intrins.h>#define uchar unsigned char#define uint unsigned intsbit lcdrs=P2^3;sbit lcden=P2^2;sbit trig=P2^0; //超声波发送//sbit echo=P3^2; //超声波接受//P0____________DB0-DB7uchar dis[]="Disp_HC-SR04";uchar num[]="0123456789";uint distance;void delay(uint z){uint x,y;for(x=z;x>0;x--)for(y=121;y>0;y--);}void HC_init(){ TMOD=0x09; TR0=1; TH0=0;TL0=0;}uint HC_jisuan(){ uint dist,timer; timer=TH0; timer<<=8; timer=timer|TL0; dist=timer/53; //晶振11.0592MHz 距离cm=微秒us/58 return dist; //1个机器周期是12个时钟周期 timer*12/(58*11.0592)=timer/53} void HC_run(){ uint tempH=0x00,tempL=0x00; TH0=0;TL0=0; trig=0; trig=1; delay(1); trig=0; while((TH0-tempH!=0||TL0-tempL!=0)||(TH0==0&&TL0==0)) { tempH=TH0; tempL=TL0; } delay(1);}void lcd_write_com(uchar com) //LCD写指令{ lcdrs=0; P0=com; delay(1); lcden=1; delay(1); lcden=0;}void lcd_write_data(uchar date) //LCD写数据{ lcdrs=1; P0=date; delay(1); lcden=1; delay(1); lcden=0;}void lcd_init() //LCD初始化{ lcden=0; lcd_write_com(0x38); lcd_write_com(0x0c); lcd_write_com(0x06); lcd_write_com(0x01);}void lcd_display(uchar temp){ uint i; lcd_write_com(0x82); for(i=0;i<12;i++) { lcd_write_data(dis); } lcd_write_com(0x80+0x41); lcd_write_data('D'); lcd_write_data('i'); lcd_write_data('s'); lcd_write_data('t'); lcd_write_data('a'); lcd_write_data('n'); lcd_write_data('c'); lcd_write_data('e'); lcd_write_data(':'); lcd_write_data(num[temp/100]); lcd_write_data(num[temp/10%10]); lcd_write_data(num[temp%10]); lcd_write_data('c'); lcd_write_data('m'); }void main(){ lcd_init(); HC_init(); while(1) { HC_run(); distance=HC_jisuan(); lcd_display(distance); delay(200); }} |
|