Page 88 - The Unofficial Guide to Lego Mindstorms Robots
P. 88
77
Trusty Revisited
You've seen some small examples of NQC code. Now I'll show you how Trusty can be programmed using NQC. You'll be able
to compare the NQC programs to t he RCX Code programs from Chapter 3.
New Brains For Trusty
As you may recall, we used a c ounter to keep track of Trusty's state. The counter value was used to decide if Trusty would turn
left or right the next time the lig ht sensor left the black line. In NQC, we can store Trusty's state in a real variable. Plus, we'll
use symbolic constants to represent state values.
int state;
#define LEFT 0
#define RIGHT 1
Trusty's program has two tasks. The first task (main) tests the value of the light sensor. If it is over the black line, the robot is
set to move forward:
while (true) {
if (SENSOR_2 < DARK2)
On Fwd(OUT_A + OUT_C);
}
The DARK2 and POWER constants a re determined using #defines; this means it's easy to fiddle with their values, and our
program is easy to read.
The second task takes care of things when the ligh t sensor leaves the black line. Whenever the robot leaves the line, the
toggle() subroutine is called. tog gle() starts the robot turning. Then we wait a little while; if the robot is still not on
the black line, we call toggle() again to turn back the other way:
task lightWatcher() {
while (tr ue) {
if (SE NSOR_2 > LIGHT2) {
toggle();
Wait(TIMEOUT);
if (SENSOR_2 > LIGHT2) {
to ggle();
Wait(TIMEOU T ∗ 2);
}
}
}
}
The toggle() subroutine perform s two important functions. First, it makes Trusty turn, based on the value of the state
variable. Second, it updates the value of state; if it was RIGHT, it will be LEFT, and vice versa.