#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
////电机驱动模块位定义////
sbit M11=P0^0;//左轮
sbit M12=P0^1;
sbit M23=P0^2;//右轮
sbit M24=P0^3;
sbit ENA=P0^4;//左轮使能PWM输入改变dj1数值控制转速sbit ENB=P0^5;//右轮使能PWM输入改变dj2数值控制转速////占空比变量定义////
unsigned char dj1=0;
unsigned char dj2=0;
uchar t=0;
////红外对管位定义////
sbit HW1=P1^0;//左前方
sbit HW2=P1^1;//右前方
sbit HW3=P1^2;//左后方
sbit HW4=P1^3;//右后方
////小车前进////
void qianjin()
{
M11=1;//左轮
M12=0;//
M23=1;//右轮
M24=0;//
dj1=50;
dj2=50;
}
////向左微调////
void turnleft2()
{
M11=1;
M12=0;
M23=1;
M24=0;
dj1=7;//左轮
dj2=50;//右轮
}
////向右微调////
void turnright2()
{
M11=1;
M12=0;
M23=1;
M24=0;
dj1=50;
dj2=7;
}
////向左大调////
void left()
{
M11=0;
M12=1;
M23=1;
M24=0;
dj1=7;
dj2=80;
}
////向右大调////
void right()
{
M11=1;
M12=0;
M23=0;
M24=1;
dj1=80;
dj2=7;
}
////循迹动作子函数////
void xj()
{
if(HW1==0&&HW2==0&&HW3==0&&HW4==0)//前进逻辑
{
qianjin();
}
if(HW1==1&&HW2==0&&HW3==0&&HW4==0)//左右微调
{
turnleft2();
}
if(HW1==0&&HW2==1&&HW3==0&&HW4==0)
{
turnright2();
}
if(HW1==1&&HW2==0&&HW3==1&&HW4==0)//左右大调
{
left();
}
if(HW1==0&&HW2==1&&HW3==0&&HW4==1)
{
right();
}
}
////初始化////
void init()
{
TMOD=0x01;
TH0=(65536-500)/256;
TL0=(65536-500)%256;
EA=1;
ET0=1;
TR0=1;
}
////定时器0中断////
void timer0() interrupt 1 using 1
{
TH0=(65536-500)/256;
TL0=(65536-500)%256;
t++;
if(t<dj1)ENA=1;
else ENA=0;
if(t<dj2)ENB=1;
else ENB=0;
if(t>=50)
{
t=0;
}
}
void main()
{
init();
P1=0Xff;
while(1)
{
/////////////////循迹模式/////////////////////
xj();
}
}。