Page 89 - The Unofficial Guide to Lego Mindstorms Robots
P. 89
78
Here is the whole program:
int state;
#define LEFT 0
#define RIGHT 1
#define DARK2 35
#define LIGHT2 40
#define POWER 7
#define TIMEOUT 50
task main() {
state = LEFT;
SetSensor(SENSOR _2, SENSOR_LIGHT);
SetPower(OUT_A + OUT_C, POWER);
start lightWatcher;
while (true) {
if (SENSOR_2 < DARK2)
OnFwd(OUT_A + OUT_C);
}
}
task lightWatcher() {
while (true) {
if (SENSOR_2 > LIGHT2) {
toggle();
Wait(TIMEOUT);
if (SENSOR_2 > LIGHT2) {
toggle();
Wait(TIMEOU T ∗ 2);
}
}
}
}
sub toggle() {
if (stat e == LEFT) {
OnRev (OUT_A);
OnFwd(OUT_C);
state = RIGHT;
}
else {
OnFwd(OUT_A) ;
OnRev(OUT_C) ;
state = LEFT;
}
}
The main task performs three important initializations which I haven't mentioned yet. First, main initializes the value of the
state variable. It just uses LEFT