#include "REG52.H"
#include <intrins.h>
#include <lcd12864.h>
//传感器接口
sbit RX = P1^1;
sbit TX = P1^0;
unsigned char distance[5] ={0,0,0,0,0};//用于显示距离
//unsigned char code hanzi[] = {"distance"};
//变量声明
unsigned int time=0;
unsigned int timer=0;
unsigned char posit=0;
unsigned long S=0;
char num=0;
bit flag=0;
//延时1ms
void delay(unsigned int x)
{
unsigned int i,j;
for(i=0;i<x;i++)
for(j=0;j<121;j++);
}
void Delay12us() //@11.0592MHz 12us延时
{
unsigned char i;
_nop_();
_nop_();
_nop_();
i = 30;
while (--i);
}
void Conut(void)
{
time=TH0*256+TL0; //读出T0的计时数值
TH0=0;
TL0=0; //清空计时器
S=(time*1.7)/100; //算出来是CM
//声音的速度是340m/s,时间的单位是us,计算到秒需要将时间数据/1000000,
//长度=速度*时间,340*time/1000000,长度数据单位是m转换成cm需要乘以100得到340*time/10000,
//小数点都向左移两位得到3.4*time/100,因为超声波是往返了,所以再除以2,得到距离数据(time*1.7)/100
if(flag == 1)
{
flag = 0;
LCD12864_SetWindow(1,0,"ERROR");
}
else
{
distance[0]=S%1000/100 + 0x30; //将距离数据拆成单个位赋值
distance[1]=S%1000%100/10+ 0x30;
distance[2]=S %10 +0x30;
distance[3]='c';
distance[4]='m';
}
}
/**********************************************************************************************************/
//定时器0
void zd0() interrupt 1 //T0中断用来计数器溢出,超过测距范围
{
flag=1; //中断溢出标志
}
void StartModule() //超声波发送函数
{
unsigned char i; //发送8次
for(i = 0; i < 8; i++)
{
TX = 1;
Delay12us();
TX = 0;
Delay12us();
}
}
/**********************************************************************************************************/
////定时器1
//void zd3() interrupt 3 //T1中断用来扫描数码管和计800MS启动模块
//{
// TH1=0xf8;
// TL1=0x30; //定时2ms
//
// timer++; //变量加
// if(timer>=400) //400次就是800ms
// {
// timer=0;
// TX=1; //800MS 启动一次模块
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// _nop_();
// TX=0;
// }
//}
/**********************************************************************************************************/
//主函数
void main(void)
{
LCD12864_Init();//初始化LCD
LCD12864_SetWindow(0, 0,"distance:"); //液晶显示函数
TMOD=0x01; //设T0为方式1,
TH0=0;
TL0=0;
// TH1=0xf8; //2MS定时
// TL1=0x30;
// ET0=1; //允许T0中断
// ET1=1; //允许T1中断
// TR1=1; //开启定时器
// EA=1; //开启总中断
delay(1000);
while(1)
{
EA = 0;
StartModule(); //超声波发送函数
TR0=1; //开启计数
while(RX ==1); //等待超声波信号返回 (程序运行一直卡在这)
TR0=0; //关闭计数
EA = 1;
if(TF0 == 0)
{
Conut(); //计算
LCD12864_SetWindow(1,0,distance);//12864显示距离
}
else
{
LCD12864_SetWindow(1,0,"error");//12864显示距离
}
delay(100);
}
}
你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答
本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。
因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。