#include<reg52.h>
#include<intrins.h>
#include<stdio.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit Trig = P2^0;
sbit Echo = P2^1;
sbit Servo = P2^7;//
uchar flag=0;
uchar control=15;
uchar servorTime=0;
void delay(uchar z)
{
uchar i,j;
for(i = z;i>0;i--)
for(j=114;j>0;j--);
}
void Delay10us() //@11.0592MHz
{
unsigned char data i;
_nop_();
i = 25;
while (--i);
}
void Delay20ms() //@11.0592MHz
{
unsigned char data i, j;
i = 216;
j = 37;
do
{
while (--j);
} while (--i);
}
void Timer0_Init() //100??@11.0592MHz
{
TMOD |= 0x11;
TL0 = 0;
TH0 = 0;
ET0 = 1;
}
void Timer1_Init() //100??@11.0592MHz
{
TMOD |= 0x11;
TL1 = 0xAE;
TH1 = 0xFB;
TF1 = 0;
TR1 = 1;
EA = 1;
ET1= 1;
}
void main()
{
uint time,distance;
Timer0_Init();
Timer1_Init();
Echo = 0;
Trig = 0;
servorTime=0;
while(1)
{
Trig = 1;
Delay10us();
Trig = 0;
while(Echo==0);
TR0 = 1;
while(Echo);
TR0 = 0;
time = TH0*256+TL0;
distance = (int)(time*0.017);
TH0 = 0;
TL0 = 0;
if(distance < 30)
{
control=15;
servorTime = 0;
TR1 = 1;
Delay20ms();
Delay20ms();
TR1 = 0;
}
else
{
control=5;
servorTime = 0;
TR1 = 1;
Delay20ms();
Delay20ms();
TR1 = 0;
}
}
}
void Timer0() interrupt 1
{
TH0 = 0;
TL0 = 0;
}
void Timer1() interrupt 3
{
TH1 = 0xFB;
TL1 = 0xAE;
servorTime++;
if(servorTime <= control)
Servo = 1;
else
Servo = 0;
if(servorTime==200)
{
servorTime = 0;
}
}
|