#include <reg51.h>
#define moto_go {R_moto1=0,R_moto2=1, L_moto3=0,L_moto4=1;} //前進
#define moto_left { R_moto1=0,R_moto2=1, L_moto3=0,L_moto4=0;} //左轉
#define moto_right {R_moto1=0,R_moto2=0, L_moto3=0,L_moto4=1;} //右轉
sbit ENA=P1^4;
sbit ENB=P1^2;
sbit hwl=P1^0; //左紅外
sbit hwr=P1^1; //右紅外
sbit R_moto1=P3^0; //IN1
sbit R_moto2=P3^1;//IN2
sbit L_moto3=P3^2; //IN3
sbit L_moto4=P3^3;//IN3
void run(void)
{
moto_go ;
}
void turnleft(void)
{
moto_left;
}
void turnright(void)
{
moto_right;
}
void Timer0Init()
{
TMOD|=0X01;//選擇為定時器0模式,工作方式1,僅用TR0打開啟動。
TH0=0XFC; //給定時器賦初值,定時1ms
TL0=0X18;
ET0=1;//打開定時器0中斷允許
EA=1;//打開總中斷
TR0=1;//打開定時器
}
void main()
{ run();
Timer0Init(); //定時器0初始化
while(1)
{
if(hwl==0&&hwr==0) run();
if(hwl==1&&hwr==0) turnleft();
if(hwl==0&&hw==1) turnright();
}
}
//調速
void Timer0() interrupt 1
{
static unsigned int i=0;
TH0=0XFC; //給定時器賦初值,定時1ms
TL0=0X18;
i++;
if(i<90) {ENA=1,ENB=1;}
if(i>90&&i<120) {ENA=0,ENB=0;}
if(i==120) i=0;
}
|