Page 85 - The Unofficial Guide to Lego Mindstorms Robots
P. 85
74
PlayTone(277, HALF);
PlayTone(330, GRACE);
PlayTone(311, HALF);
PlayTone(277, HALF); Wait (2∗HALF);
PlayTone(247, HALF);
PlayTone(311, HALF);
PlayTone(208, HALF);
PlayTone(208, 2∗ BEAT);
Wait(GRACE + 5∗HALF + 2∗BEAT + HALF);
stop main;
Float(OUT_A + OUT_C);
}
W hen the sing task is done playing music, it stops the main task with the stop command. Then it turns the motors off.
The order is critical. If we turne d off the motors and then stopped the main task, it's possible that main would turn on the
motors again before it was stopp ed. Multithreaded programming is powerful but tricky.
Each RCX program can have up to ten tasks.
Subroutines
A subrou tine is a group of commands th at you will execute frequently. Subroutines offer a way to clean up your source code
and red u ce the size of compiled programs. Subroutines in NQC are defined in much the same way as tasks. The following
program has one subroutine, called wiggle(). The main task shows how this subroutine is called:
task main() {
wiggle();
Wait(200);
wiggle();
}
sub wiggle() {
OnFwd(OUT_A);
OnRev(OUT_C);
Wait(20);
OnFwd(OUT_C);
OnRev(OUT_A);
Wait(20);
Off(OUT_A + OUT_C);
}
Subroutines execute as part of the task from which they are called. It works just as if the call to wiggle() was replaced with
the commands it contains. The nice thing about subroutines is that their code is defined once, but you can call it as many times
as you like from other places in your program. You could accomplish the same sorts of things with subroutines and macros, but
subroutines are more