#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
unsigned char zkb1=0; //左边电机的占空比//
unsigned char zkb2=0; //右边电机的占空比//
unsigned char t=0; //定时器中断计数器 //
sbit LSEN1=P3^0;
sbit RSEN1=P3^1; //传感//
sbit ENA=P0^5;
sbit IN1=P0^4;
sbit IN2=P0^3;
sbit IN3=P0^2;
sbit IN4=P0^1;
sbit ENB=P0^0;
sbit led1=P2^0;
sbit led2=P2^1;
sbit led3=P2^2;
void init() //初始化
{
EA=1;
TMOD |=0x01;
TH0=(65536-100)/256; //执行一次xms
TL0=(65536-100)%256;
ET0=1;
TR0=1;
}
void T0_time() interrupt 1
{
TH0=(65536-100)/256;
TL0=(65536-100)%256;
if(t<zkb1)
{
ENA=1; //左电机转
}
else
{
ENA=0; //左电机停
}
if(t<zkb2)
{
ENB=1; //右电机转
}
else
{
ENB=0; // 右电机停
}
++t;
if(t>=50) //50一周
{
t=0;
}
}
void qianjin() //直行//
{
zkb1=12; //50 ,14% 7
zkb2=12; //50 7
}
void turn_left1() //左转//
{
zkb1=3; // //左电机
zkb2=18; ; //50 16% 8
}
void turn_right1() //右转函数//
{
zkb1=18; //50 8 //左电机
zkb2=3;
}
void xunji()
{
uchar flag;
if((RSEN1==0)&&(LSEN1==0)) //直/走/,未检测到
{ flag=0;}
else if((RSEN1==1)&&(LSEN1==0)) //右拐//
{ flag=1;}
else if((RSEN1==0)&&(LSEN1==1)) //左拐//
{ flag=2; }
switch (flag)
{
case 0:qianjin();led1=0;
break;
case 1:turn_right1();led2=0;
break;
case 2:turn_left1();led3=0;
break;
default://qianjin();
break;
}
}
void main()
{ init();
while(1)
{
IN1=0;
IN2=1;
IN3=0; //电机加电启动//
IN4=1;
while(1)
{
xunji();
}
}
}//成
|