#include "reg52.h"
sbit D1 = P2^0;
sbit D2 = P2^1;
sbit Trig = P1^5;
sbit Echo = P1^6;
double time;
double dist;
void Delay10us() //@11.0592MHz
{
unsigned char i;
i = 2;
while (--i);
}
void Time0Init()
{
TMOD &= 0xF0; //ÉèÖö¨Ê±Æ÷ģʽ
TMOD |= 0x01;
TL0 = 0;
TH0 = 0;//ÏȲ»¼Æʱ,³õʼֵÉ趨ΪÁã¯ÎªÁã
}
void startHC()
{
Trig = 0;
Trig = 1;
Delay10us();
Trig = 0;
}
void main()
{
Time0Init();
while(1){
startHC();
while(Echo == 0);
TR0 = 1;
while(Echo == 1);
TR0 = 0;
time = (TH0*256+TL0)*1.085;//1.085Ϊÿһ¸öÂö³åµÄʱ¼ä£¬µ¥Î»Îªus
dist = time*0.017;
if(dist <= 10){
D1 = 0;
D2 = 1;
}else{
D1 = 1;
D2 = 0;
}
//定时器数据清零以便下一次使用
TL0 = 0;
TH0 = 0;
}
}
【上官】超声波测距代码
最新推荐文章于 2024-01-02 22:39:38 发布