root / trunk / code / projects / linefollowing / lineFollow.c @ 1841
History | View | Annotate | Download (1.57 KB)
1 |
#include "lineFollow.h" |
---|---|
2 |
|
3 |
|
4 |
|
5 |
void lineFollow_init()
|
6 |
{ |
7 |
analog_init(0);
|
8 |
lost = 0;
|
9 |
} |
10 |
|
11 |
|
12 |
|
13 |
int lineFollow()
|
14 |
{ |
15 |
int colors[6]; |
16 |
int position;
|
17 |
|
18 |
|
19 |
updateLine(colors); |
20 |
position = lineLocate(colors); |
21 |
|
22 |
//not on line
|
23 |
if(position == NOLINE)
|
24 |
{ |
25 |
if(lost++>20) |
26 |
{ |
27 |
orb1_set_color(GREEN); |
28 |
orb2_set_color(GREEN); |
29 |
motors_off(); |
30 |
return LINELOST;
|
31 |
} |
32 |
} |
33 |
//on line
|
34 |
else
|
35 |
{ |
36 |
position*=30;
|
37 |
orb1_set_color(GREEN); |
38 |
orb2_set_color(ORB_OFF); |
39 |
motorLeft(min(SPEED+position, 255));
|
40 |
motorRight(min(SPEED-position, 255));
|
41 |
lost=0;
|
42 |
} |
43 |
return 0; |
44 |
} |
45 |
|
46 |
|
47 |
|
48 |
|
49 |
void updateLine(int* values) |
50 |
{ |
51 |
for(int i = 0; i<5; i++) |
52 |
values[i] = assignColor(i, updateIR(i)); |
53 |
} |
54 |
|
55 |
|
56 |
int updateIR(int n) |
57 |
{ |
58 |
//maps the sensors to the analog input ports
|
59 |
int ports[5] = {13, 12, 3, 2, 9}; |
60 |
|
61 |
return analog_get10(ports[n]);
|
62 |
} |
63 |
|
64 |
|
65 |
|
66 |
int assignColor(int port, int analog) |
67 |
{ |
68 |
if (analog < 150) |
69 |
return WHITE;
|
70 |
else
|
71 |
return BLACK;
|
72 |
} |
73 |
|
74 |
|
75 |
int lineLocate(int* colors) |
76 |
{ |
77 |
int i;
|
78 |
int wsum = 0; |
79 |
int count=0; |
80 |
|
81 |
for(i = 0; i<5; i++) |
82 |
{ |
83 |
count+=(colors[i]+1)/2; |
84 |
wsum += (i)*colors[i]; |
85 |
} |
86 |
if(count==0) |
87 |
return NOLINE;
|
88 |
|
89 |
return (wsum/count)-4; |
90 |
} |
91 |
|
92 |
|
93 |
int updateBarCode()
|
94 |
{ |
95 |
//maps the sensors to the analog input ports
|
96 |
int ports[2] = {8,1}; |
97 |
|
98 |
return analog_get10(ports[1]) | analog10(ports[2]); |
99 |
} |
100 |
|
101 |
|
102 |
int min(int x, int y){return x>y ? y : x;} |
103 |
|
104 |
void motorLeft(int speed){ |
105 |
speed-=127;
|
106 |
if(speed>=0)motor_l_set(FORWARD, 160+speed*95/128); |
107 |
else motor_l_set(BACKWARD, 160-speed*95/127); |
108 |
} |
109 |
|
110 |
void motorRight(int speed){ |
111 |
speed-=127;
|
112 |
if(speed>=0)motor_r_set(FORWARD, 160+speed*95/128); |
113 |
else motor_r_set(BACKWARD, 160-speed*95/127); |
114 |
} |
115 |
|