参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <reg52.h>

sbit LED1=P2^7;//大灯 0亮
sbit LED2=P2^2;

sbit LF1=P0^2;//左前电机
sbit LF2=P0^3;
sbit RF1=P0^4;//右前电机
sbit RF2=P0^5;
sbit LB2=P0^0;//左后电机
sbit LB1=P0^1;
sbit RB1=P0^6;//右后电机
sbit RB2=P0^7;

sbit XJ1 = P2^4;//右边红外传感器的数据口
sbit XJ2 = P2^5;//左边红外传感器的数据口

sbit BZ1=P2^3;//左右避障传感器数据口
sbit BZ2=P2^6;

unsigned char zkb1 = 0;//定义了一下左边两个轮的占空比
unsigned char zkb2 = 0;//定义了一下右边两个轮的占空比
int t = 0;

void delayms(unsigned int ms)
{
unsigned char i=100,j;
for(;ms;ms--)
{
while(--i)
{
j=10;
while(--j);
}
}
}

void PIT_Init()
{
EA = 1;
TMOD |= 0x01;
TH0 = (65536 - 200) / 256;
TL0 = (65536 - 200) % 256;
ET0 = 1;
TR0 = 1;
}

void timer()interrupt 1
{
TH0 = (65536-200)/256;
TL0 = (65536-200)%256;

if(t<zkb1)
{
LF1=0;
LF2=1;
LB1=0;
LB2=1;
}
else
{
LF1=0;
LF2=0;
LB1=0;
LB2=0;
}

if(t<zkb2)
{
RF1=0;
RF2=1;
RB1=0;
RB2=1;
}
else

{
RF1=0;
RF2=0;
RB1=0;
RB2=0;
}

t = (t + 1) %50;
}

void run() //跑直线
{
zkb1=7;
zkb2=7;
}

void right()
{
zkb1=12;
zkb2=0;

}
void left()
{
zkb1=0;
zkb2=12;
}
void stop()
{
zkb1=0;
zkb2=0;
}
void delay(unsigned int k)
{
unsigned int x,y;
for(x=0;x<k;x++)
{
for(y=0;y<200;y++);
}
}
void xunji()
{
unsigned char flag;
if((XJ1==1)&&(XJ2==0))
{
flag = 0;//左边检测到黑线
}
else if((XJ1==0)&&(XJ2==1))
{
flag = 1;//右边检测到黑线
}
else if((XJ1==1)&&(XJ2==1))
{
flag = 3;
}
else
{
flag = 4;
}
if((BZ1==0)||(BZ2==0))
{
flag = 5;
}
switch(flag)
{
case 0: right();delay(5);stop();LED1=1;LED2=0;delay(5);break;
case 1: left();delay(5);stop(); LED1=0;LED2=1;delay(5);break;
case 3: run();delay(1);stop(); LED1=1;LED2=1; delay(1);break;
case 4: run();delay(1);stop(); LED1=1;LED2=1; delay(1);break;
case 5: stop();delay(5);break;
default: run();delay(5);stop(); LED1=1;LED2=1; delay(11);break;
}
}



void main()
{
PIT_Init();
LED1=0;
LED2=0;
while(1)
{
xunji();
}

}