大家可以自己动手试试做个属于自己的51智能小车
#include<reg52.h>
#include<intrins.h>
#define uint unsigned int
#define uchar unsigned char
#define ulong unsigned long
sbit IN1=P1^0;
sbit IN2=P1^1;
sbit IN3=P1^2;
sbit IN4=P1^3;
sbit Sevro_Motor=P2^0;
sbit Echo=P2^3;
sbit Trig=P2^4;
sbit Left_val=P2^1;
sbit Right_val=P2^2;
uchar PWM_val;
uchar Set_val;
uint x,y,time,timer;
ulong S;
void delay(uint z)
{
for(x=z;x>0;x--)
for(y=1000;y>0;y--);
}
void MeasureDistance() //启动测距信号
{
Trig=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
Trig=0;
}
void head()
{
IN1=1;
IN2=0;
IN3=1;
IN4=0;
}
void back()
{
IN1=0;
IN2=1;
IN3=0;
IN4=1;
}void stop()
{
IN1=0;
IN2=0;
IN3=0;
IN4=0;
}
void CountDistance()
{
while(!Echo);
TR0=1;
while(Echo);
TR0=0;
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(time*1.7)/100;
}
void Servo_PWM()
{
if(PWM_val<=Set_val)
Sevro_Motor=1;
else
Sevro_Motor=0;
if(PWM_val>=50)
PWM_val=0;
}
void time1()interrupt 3
{
TH1=(65536-100)/256;
TL1=(65536-100)%256;
timer++;
PWM_val++;
Servo_PWM();
}
void timer0()interrupt 1
{
}
void init()
{
P2=0xff;
TMOD=0x11;
TH1=(65536-100)/256;
TL1=(65536-100)%256;
TH0=0;
TL0=0;
TR1=1;
ET1=1;
ET0=1;
EA =1;
time=0;
timer=0;
S=0;
PWM_val=0;
delay(50);
Set_val=21;
}
//21是中,19是左,23是右
void main()
{
init();
while(1)
{
if(timer>=400)
{
timer=0;
MeasureDistance(); //启动检测
CountDistance(); //计算距离
delay(10);
if((S<35)&&(Left_val==1)&&(Right_val==0)) //距离小于20CM
{
stop();
Set_val=22;
delay(20);
back();
delay(80);
Set_val=21;
head();
}
else if((S<35)&&(Left_val==0)&&(Right_val==1))
{
stop();
Set_val=19;
delay(20);
back();
delay(80);
Set_val=21;
head();
}
else if((S<35)&&(Left_val==0)&&(Right_val==0))
{
stop();
delay(20);
Set_val=22;
back();
delay(80);
Set_val=21;
head();
}
else if((S<35)&&(Left_val==1)&&(Right_val==1))
{
Set_val=19;
back();
delay(80);
Set_val=21;
head();
}
/*else if(S>=30)
{
Set_val=21;
head();
}
else if((S>=30)&&(Left_val==1)&&(Right_val==0))
{
Set_val=19;
head();
delay(50);
Set_val=21;
head();
}
else if((S>=30)&&(Left_val==0)&&(Right_val==1))
{
Set_val=22;
head();
delay(50);
Set_val=21;
head();
}*/
if((Left_val==1)&&(Right_val==1))
{
head();
}else if((Left_val==0)&&(Right_val==1))
{
Set_val=22;
head();
delay(50);
Set_val=21;
head();
}else if((Left_val==1)&&(Right_val==0))
{
Set_val=20;
head();
delay(50);
Set_val=21;
head();
}else if((Left_val==0)&&(Right_val==0))
{
stop();
}
}
}
}
|