|
幫忙看看謝謝大家
單片機源程序如下:
#include <reg52.h>#define uint unsigned int
#define uchar unsigned char
sbit IN11=P1^6; //左前輪
sbit IN12=P1^7;
sbit IN13=P1^4; //右前輪
sbit IN14=P1^5;
sbit IN21=P1^0; // 左后輪
sbit IN22=P1^1;
sbit IN23=P1^2; //右后輪
sbit IN24=P1^3;
sbit S1=P0^3; //速度
sbit S2=P0^2;
sbit S3=P0^1;
sbit S4=P0^0;
sbit D1=P2^3; //循跡
sbit D2=P2^2;
sbit D3=P2^1;
sbit D4=P2^0;
uchar counter,compare;
void a () //左輪前進(jìn)
{
IN11=1;
IN12=0;
IN21=1;
IN22=0;
}
void aa () //左輪后退
{
IN11=0;
IN12=1;
IN21=0;
IN22=1;
}
void b ()
{
IN13=0; //右輪前進(jìn)
IN14=1;
IN23=0;
IN24=1;
}
void bb ()
{
IN13=1; //右輪后退
IN14=0;
IN23=1;
IN24=0;
}
void car_stop () //停止
{
IN11=1;
IN12=1;
IN13=1;
IN14=1;
IN21=1;
IN22=1;
IN23=1;
IN24=1;
}
void Timer0_Init() //100微秒@11.0592MHz
{
TMOD &= 0xF0; //設(shè)置定時器模式
TMOD |= 0x01; //設(shè)置定時器模式
TL0 = 0xA4; //設(shè)置定時初始值
TH0 = 0xFF; //設(shè)置定時初始值
TF0 = 0; //清除TF0標(biāo)志
TR0 = 1; //定時器0開始計時
ET0=1; //定時器0中斷允許開關(guān)
EA=1; //定時器總開關(guān)
PT0=0; //定時器0中斷優(yōu)先級
}
void Timer0_Routine() interrupt 1 //中斷函數(shù)
{
TL0 = 0xA4;
TH0 = 0xFF;
compare=6;
counter++;
if(counter>=20)
{
counter=0;
}
if(counter<compare)
{
S1=1;
S2=1;
S3=1;
S4=1;
}
else
{
S1=0;
S2=0;
S3=0;
S4=0;
}
}
void car_go() //小車向前
{
compare=5;
a();
b();
}
void car_back()//小車向后
{
compare=5;
aa();
bb();
}
void car_leftgo()//左拐
{
compare=5;
aa();
b();
}
void car_rightgo() //右拐
{
compare=5;
a();
bb();
}
void delayms (uint x)
{
int i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void xunji ()
{
if(D1==1&&D2==1&&D3==1&&D4==1) //全檢測到黑線
{
car_go ();
}
if(D1==0&&D2==1&&D3==0&&D4==0) //中間右側(cè)檢測到黑線,小車偏左,小車向右移動
{
car_rightgo ();
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_go ();
}
}
if(D1==0&&D2==0&&D3==1&&D4==0) //中間左側(cè)檢測到黑線,小車偏右,小車向左移動
{
car_leftgo ();
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_go ();
}
}
if(D1==0&&D2==0&&D3==1&&D4==1) //直角左拐
{
car_go ();
delayms(500);
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_stop();
delayms(500);
car_leftgo ();
}
}
if(D1==1&&D2==1&&D3==0&&D4==0) //直角右拐
{
car_go ();
delayms(500);
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_stop();
delayms(500);
car_rightgo ();
}
}
if((D1==0&&D2==0&&D3==0&&D4==1)||(D1==0&&D2==1&&D3==0&&D4==1)||(D1==0&&D2==1&&D3==1&&D4==1)) //銳角左拐
{
car_go ();
delayms(500);
delayms(500);
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_stop();
delayms(500);
car_leftgo();
}
}
if((D1==1&&D2==0&&D3==0&&D4==0)||(D1==1&&D2==0&&D3==1&&D4==0)||(D1==1&&D2==1&&D3==1&&D4==0)) //銳角右拐
{
car_go ();
delayms(500);
delayms(500);
if(D1==0&&D2==0&&D3==0&&D4==0)
{
car_stop();
delayms(500);
car_rightgo();
}
}
if(D1==0&&D2==1&&D3==1&&D4==0)
{
car_go();
}
}
void main ()
{
Timer0_Init();
car_go ();
while (1)
{
xunji ();
}
} |
|