名称:
超声波测距作者:Acebit
信息:STC10F08单片机,晶振11.0592MHZ;超声波模块HM55B,测距范围1米;
LCD1602,串行发送数据,显示单位mm;
#include "def.h" //定义管脚
#include "reg51.h"
#include
#ifndef OSC110592
#define OSC110592
#endif
unsigned int qian,bai,shi,ge;
unsigned int k;
long result;
void init();
void PULSOUTus(unsigned int port);
bit Read_Port(unsigned int port);
void Write_Port(unsigned int port,bit state);
bdata unsigned char SBUF1;
sbit SBUF1_bit0 = SBUF1^0;
sbit SBUF1_bit1 = SBUF1^1;
sbit SBUF1_bit2 = SBUF1^2;
sbit SBUF1_bit3 = SBUF1^3;
sbit SBUF1_bit4 = SBUF1^4;
sbit SBUF1_bit5 = SBUF1^5;
sbit SBUF1_bit6 = SBUF1^6;
sbit SBUF1_bit7 = SBUF1^7;
void init() //initialization
{
TMOD=0x12;
PCON=00;
TR1=0;
TF1=0;
TR0=0;
TF0=0;
ET1=0;
ET0=0;
EA=0;
}
void delay_ms(unsigned int i)//延时子程序
{
unsigned int j;
for(;i>0;i--)
for(j=0;j<125;j++);
}
void putchar(char input) //模拟串口9600波特率,向LCD发送数据
{
SBUF1=input;
TL0=160;
TH0=160;
TF0=0;
TR0=1;
P26 = 0; //strat
while(!TF0);
TF0=0;
P26 = SBUF1_bit0; //0
while(!TF0);
TF0=0;
P26 = SBUF1_bit1; //1
while(!TF0);
TF0=0;
P26 = SBUF1_bit2; //2
while(!TF0);
TF0=0;
P26 = SBUF1_bit3; //3
while(!TF0);
TF0=0;
P26 = SBUF1_bit4; //4
while(!TF0);
TF0=0;
P26 = SBUF1_bit5; //5
while(!TF0);
TF0=0;
P26 = SBUF1_bit6; //6
while(!TF0);
TF0=0;
P26 = SBUF1_bit7; //7
while(!TF0);
TF0=0;
P26 = 1; //end
while(!TF0);
TF0=0;
TR0=0;
}
void PULSOUTus(unsigned int port)//HM55B启动脉冲
{
Write_Port(port,1);
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
Write_Port(port,0);
}
void Write_Port(unsigned int port,bit state)
{
switch (port)
{
case 0: P00=state;break;
case 1: P01=state;break;
case 2: P02=state;break;
case 3: P03=state;break;
case 4: P04=state;break;
case 5: P05=state;break;
case 6: P06=state;break;
case 7: P07=state;break;
case 8: P20=state;break;
case 9: P21=state;break;
case 10:P22=state;break;
case 11:P23=state;break;
case 12:P24=state;break;
case 13:P25=state;break;
case 14:P26=state;break;
case 15:P27=state;break;
}
}
//main program
void main()
{
init();
while(1)
{
TL1=0;
TH1=0;
Write_Port(15,0);
PULSOUTus(15);
Write_Port(15,1);
while(P27==0); //测回波时间
TR1=1;
while(P27==1);
TR1=0;
result=TH1*256+TL1;
result=result*0.187-150; //距离计算
k=(int)result;
putchar(22);//显示
putchar(12);
delay_ms(100);
qian=k/1000+48;
bai=(k00)/100+48;
shi=(k00)0/10+48;
ge=(k00)0+48;
putchar(qian);
putchar(bai);
putchar(shi);
putchar(ge);
putchar(m);
putchar(m);
delay_ms(500);
}
}