#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
unsigned char zkb1=0 //**左边电机的占空比**//
unsigned char zkb2=0 //**右边电机的占空比**//
unsigned char t=0; //**定时器中断计数器**//
sbit LSEN2=P2^0;
sbit LSEN1=P2^1;
sbit RSEN1=P2^2;
sbit RSEN2=P2^3; //**传感器***/
sbit IN1=P1^0;
sbit IN2=P1^1;
sbit IN3=P1^2;
sbit IN4=P1^3;
sbit ENA=P1^4;
sbit ENB=P1^5;
//**********初始化定时器 中断***********//
void init()
{
TMOD=0x01;
TH0=(65536-100)/256;
TL0=(65536-100)%256;
EA=1;
ET0=1;
TR0=1; }
//***********中断函数+脉宽调制***********//
void timer0() interrupt 1
{
if(t<zkb1)
ENA=1;
else
ENA=0;
if(t<zkb2)
ENB=1;
else
ENB=0;
t++;
if(t>=50)
{t=0;}
}
//******************直行******************//
void qianjin()
{
zkb1=50;
zkb2=50;
}
//***************左转函数1***************//
void turn_left1()
{
zkb1=0;
zkb2=50;
}
//***************左转函数2***************//
void turn_left2()
{
zkb1=0;
zkb2=50;
}
//***************右转函数1***************//
void turn_right1()
{
zkb1=50;
zkb2=0;
}
//***************右转函数2***************//
void turn_right2()
{
zkb1=50;
zkb2=0;
}
//***************循迹函数*****************//
void xunji()
{
uchar flag;
if((RSEN2==1)&&(RSEN1==0)&&(LSEN1==0)&&(LSEN2==1))
{ flag=0; }
//*******直行*******//
else if((RSEN2==1)&&(RSEN1==1)&&(LSEN1==0)&&(LSEN2==1))
{ flag=1;}
//***左偏1,右转***//
else if((RSEN2==1)&&(RSEN1==0)&&(LSEN1==1)&&(LSEN2==1))
{ flag=2; }
//***右偏1,左转***//
else if((RSEN2==0)&&(RSEN1==0)&&(LSEN1==0)&&(LSEN2==1))
{ flag=3; }
//***右偏2,左转***//
else if((RSEN2==1)&&(RSEN1==0)&&(LSEN1==0)&&(LSEN2==0))
{ flag=4;}
//***左偏2,右转***//
switch (flag)
{
case 0:qianjin();
break;
case 1:turn_right1();
break;
case 2:turn_left1();
break;
case 3:turn_left2();
break;
case 4:turn_right2();
break;
default: break;
}
}
//****************主程序****************//
void main()
{
init();
zkb1=50;
zkb2=50;
while(1)
{
//******给电机加电启动******//
IN1=1;
IN2=0;
IN3=1;
IN4=0;
ENA=1;
ENB=1;
while(1)
{
xunji(); //*********寻迹**********//
}
}
}