在贴出程序来吧
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
#define L_GO {IN3=1;IN4=0;}
#define R_GO {IN1=1;IN2=0;}
#define L_BACK {IN3=0;IN4=1;}
#define R_BACK {IN1=0;IN2=1;}
#define L_STOP {IN3=IN4=1;}
#define R_STOP {IN1=IN2=1;}
#define D 205//占空比分子
#define RTIME 730
#define LTIME 1200
sbit ENL=P2^7;
sbit ENR=P2^6;
sbit IN1=P2^2;
sbit IN2=P2^3;
sbit IN3=P2^0;
sbit IN4=P2^1;
sbit one=P0^0;
sbit two=P0^1;
sbit thr=P0^5;
sbit fou=P0^4;
sbit fiv=P0^2;
sbit six=P0^3;
sbit sev=P0^6;
sbit eig=P0^7;
uint mid,D_left,D_right;
uchar temp;
void Delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void TranL(uint L) //改变左轮占空比,参数最大值276,因256个计数值
{
mid=L/1.085069;
TH0=TL0=D_left=255-mid;
}
void TranR(uint R)//参数最大值276
{
mid=R/1.085069;
TH1=TL1=D_right=255-mid;
}
void Init()
{
TMOD=0x22;//定时器0,1八位自动重装模式
TH0=0x18;//默认250uS左,占空比5/6,直行
TL0=0x18;
TH1=0x18;//默认250uS右,占空比5/6,直行
TL1=0x18;
EA=1;
ET0=1;
ET1=1;
ET2=1;
T2CON=0x04;//定时器2,16位自动重装
RCAP2L=0xec; //定时器2初值,约300uS
RCAP2H=0xfe;
TR2=1;
}
void Go()
{
TranL(D);//占空比?/300
TranR(D);//占空比?/300
L_GO
R_GO
}
void Back()
{
TranL(200);//占空比?/300
TranR(200);//占空比?/300
L_BACK
R_BACK
}
void TurnLeft()
{
TranL(0);
TranR(D);
L_STOP
R_GO
}
void TurnRight()
{
TranL(D);
TranR(0);
L_GO
R_STOP
}
void Turnright1()
{
TranL(200);
TranR(200);
L_GO
R_BACK
}
void main()
{
Init();
Delay(300);
while(1) //12精度13 14cm,3478:10 11cm,56没测
{
while(1)
{
if(one==0&&two==0)
{
if(thr&&fou&&sev&&eig)
{
Delay(3);
if(one==0&&two==0&&thr&&fou&&sev&&eig)
{
L_STOP
R_STOP
Delay(1000);
TurnRight();
Delay(RTIME);
L_STOP
R_STOP
Delay(1000);
break;
}
}
if((thr==0||fou==0)&&sev&&eig)
{
Delay(3);
if(one==0&&two==0&&(thr==0||fou==0)&&sev&&eig)
{
L_STOP
R_STOP
Delay(1000);
TurnLeft();
Delay(LTIME);
L_STOP
R_STOP
Delay(1000);
break;
}
}
if((sev==0||eig==0)&&thr&&fou)
{
Delay(3);
if(one==0&&two==0&&(sev==0||eig==0)&&thr&&fou)
{
L_STOP
R_STOP
Delay(1000);
TurnRight();
Delay(RTIME);
L_STOP
R_STOP
Delay(1000);
break;
}
}
}
if(one==0&&two&&thr&&fou&&sev&&eig==0||one==0&&two&&thr&&fou&&sev==0&&eig==0||one==0&&two==0&&thr&&fou&&sev&&eig==0) //左转
{
L_STOP
R_STOP
Delay(1000);
TurnRight();
Delay(RTIME);
L_STOP
R_STOP
Delay(1000);
break;
}
if(one&&two==0&&thr==0&&fou&&sev&&eig||one==0&&two==0&&thr==0&&fou&&sev&&eig||one&&two==0&&thr==0&&fou==0&&sev&&eig) //右转
{
L_STOP
R_STOP
Delay(1000);
TurnLeft();
Delay(LTIME);
L_STOP
R_STOP
Delay(1000);
break;
}
if(one==0&&two==0&&thr==0&&fiv&&six&&eig==0)
{
L_STOP
R_STOP
Delay(500);
Turnright1();
Delay(1725);
L_STOP
R_STOP
Delay(500);
/* Back();
while(thr==0&&eig==0);
Delay(500);
if(thr&&fou&&sev&&eig)
{
TurnLeft();
Delay(TIME);//默认左转
break;
}
if((thr==0||fou==0)&&sev&&eig)
{
TurnLeft();
Delay(TIME);//左转
break;
}
if((sev==0||eig==0)&&thr&&fou)
{
TurnRight();
Delay(TIME);//右转
break;
} */
}
else
{
Go();
// Delay(500);
}
}
}
}
void Timer_2()interrupt 5
{
TF2=0;
ENL=ENR=1;
TR0=TR1=1;
}
void Timer_0()interrupt 1
{
ENL=0;
TR0=0;
}
void Timer_1()interrupt 3
{
ENR=0;
TR1=0;
} |