#include <reg52.h>
#include <intrins.h>
typedef unsigned char u8;
typedef unsigned int u16;
#define HIGH 5
#define ALL 10
u16 tt,a=1,b=0,c;
u16 timer=0;
bit flag=0;
u16 time=0,S=0;
sbit E18R = P0^0;
sbit E18L = P0^1;
sbit TRIG = P0^3;
sbit ECHO = P0^2;
sbit ENAB = P2^7;//1右电机B左电机A
sbit IN1B = P2^6;//0
sbit IN2B = P2^5;//1
sbit IN3B = P2^4;//1
sbit IN4B = P2^3;//0
sbit ENBB = P2^2;//1
sbit ENAF = P1^0;//1//左电机B右电机A
sbit IN1F = P1^1;//0
sbit IN2F = P1^2;//1
sbit IN3F = P1^3;//0
sbit IN4F = P1^4;//1
sbit ENBF = P1^5;//1
void timer0init()
{
TMOD|=0X10;
TH0=0;
TL0=0;
ET0=1;
EA=1;
}
void timer0() interrupt 1
{
flag=1;
}
void delay100ms(void) //误差 0us
{
unsigned char a,b,c;
for(c=19;c>0;c--)
for(b=20;b>0;b--)
for(a=130;a>0;a--);
}
void start()
{
TRIG=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
TRIG=0;
}
void count()
{
while(ECHO==1);
TR0=1;
while(ECHO==0);
TR0=0;
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(time*1.7)/100;//计算值为cm
// if((S>=30)||flag==1)
// {
// flag=0;
// }
}
void avoid()
{
if(S<30)
{
ENAF=0;
ENBF=1;
IN3F=0;
IN4F=1;
}
else
{
flag=0;
ENAF=1;
ENBF=1;
IN1F=0;
IN2F=1;
IN3F=0;
IN4F=1;
}
}
/*主函数*/
void main()
{
P1 = 0X33;
while(1)
{
start();
count();
avoid();
delay100ms();
}
}
|