#include "intrins.h"
#include"reg52.h"
#define uchar unsigned char
#define unit unsigned int
typedef unsigned int u16;
typedef unsigned char u8;
unsigned int zkb1=0;
unsigned int zkb2=0;
unsigned int t=0;
sbit RSEN=P1^4;
sbit LSEN=P1^5;
sbit VSEN=P1^6;
sbit left1=P2^1;
sbit left2=P2^2;
sbit right1=P2^3;
sbit right2=P2^4;
sbit pwmleft=P2^7;
sbit pwmright=P2^6;
u16 left_speed,right_speed,timer1,S,state,time,timer;
void delay(u16 i)
{
while(i--);
}
void left()
{
left1=0; //左轮后退
left2=1;
right1=1; //右轮前进
right2=0;
left_speed=20;
right_speed=30;
}
void right()
{
left1=1; //左轮前进
left2=0;
right1=0; //右轮后退
right2=1;
left_speed=40;
right_speed=25;
}
void forward()
{
left1=1; //左轮前进
left2=0;
right1=1; //右轮前进
right2=0;
left_speed=35;
right_speed=30;
}
void stop()
{
left1=0; //左轮停止
left2=0;
right1=0; //右轮停止
right2=0;
}
void back()
{
left1=0; //左轮后退
left2=1;
right1=0; //右轮后退
right2=1;
left_speed=30;
right_speed=30;
}
void bizhang()
{
u16 l=500;
back();
delay(500);
stop();
delay(l);//暂停
left();
delay(1200);//左转
stop();
delay(l);//暂停
forward();
delay(2000);//直走
stop();
delay(l);//暂停
right();
delay(1400);//右转
stop();
delay(l);//暂停
forward();
delay(2000);//直走
stop();
delay(l);//暂停
right();
delay(1400);//右转
stop();
delay(l);//暂停
while(LSEN==0&&RSEN==0)
{
forward();
}
while(LSEN==1||RSEN==1)
{
forward();
while(LSEN==1||RSEN==1)
{
left();
}
}
}
void xunji()
{
uchar flag;
if((LSEN==0)&&(RSEN==0)&&(VSEN==1))
{flag=0;}
else if((LSEN==1)&&(RSEN==0)&&(VSEN==1))
{flag=1;}
else if((LSEN==0)&&(RSEN==1)&&(VSEN==1))
{flag=2;}
else if(VSEN==0)
{flag=3;}
else if((LSEN==1)&&(RSEN==1))
{flag=4;}
switch(flag)
{
case 0:forward();
break;
case 1:left();
break;
case 2:right();
break;
case 3:bizhang();
break;
case 4:stop();
break;
}
}
void TimerInit()
{
TMOD=0X11;//选择为定时器1和0的模式,工作方式1
TH0 = 0xFF;
TL0 = 0xff; //1us
TH1=0;
TL1=0;
ET0=1;//打开定时器0中断允许
EA=1;//打开总中断
TR0=1;//打开定时器
}
void main()
{
TimerInit();
while(1)
{
xunji();
}
}
void Time0(void) interrupt 1 //3 为定时器1的中断号 1 定时器0的中断号 0 外部中断1 2 外部中断2 4 串口中断
{
if(timer1>=100) //PWM周期为1000*1us
{
timer1=0;
}
if(timer1 <right_speed)
{
pwmright=1;
}
else
{
pwmright=0;
}
if(timer1 <left_speed)
{
pwmleft=1;
}
else
{
pwmleft=0;
}
TH0 = 0xFF;
TL0 = 0xff; //1us
timer1++;
timer++;
}
|