Page 65
Program Flow
You've seen how to control the RCX's outputs and inputs. But robot programs aren't very interesting unless they can make decisions and repeat actions. In this section, I'll sketch out NQC's
program control commands. NQC supports a standard set of conditional branches and loops; if you've ever programmed in other languages (particularly C), this will look familiar.
Waiting
Although it might not seem important, NQC includes a command that tells the robot to do nothing for a certain amount of time. This is often useful if you need to allow some time for something to
happen—maybe the robot needs to move forward or turn for a little while, or you want to give a sound time to play. The command is:
Wait(expression ticks)
This command causes the current task to pause for the supplied hundredths of a second; a call to Wait(100) will pause the task for a full second. Note that this only applies to the current
task—other tasks will continue to execute. I'll talk more about tasks a little later.
A variation on this theme is the concept of waiting for an event, like a press on a touch sensor, or a certain time of day. The following command waits for a condition to become true:
until (boolean condition) [statements]
Use this command to wait for the given condition to become true. You could, for example, wait for the value of input 1 to become 4 like this:∗
until (SENSOR_1 == 4);
This particular until has an empty body, which means it won't do anything each time the condition is tested—it simply waits until the condition is true. The following program beeps every
half second until you press a touch sensor on input 1 four times:
task main() {
SetSensor(SENSOR_1, SENSOR_PULSE);
until (SENSOR_1 == 4) {
PlaySound(SOUND_CLICK);
Wait(50);
}
}
∗ As in C, conditional expressions are very different from evaluations. Use
== to compare values and = to assign values.
Page 66
Loops
A loop is a series of commands that you want to be executed repeatedly. NQC offers three flavors of loop:
repeat (expression value) [statements]
This command simply repeats the given statements value times.
while (boolean condition) [statements]
This loop repeats the supplied statements until condition is no longer true.
do [statements] while (boolean condition)
This loop is similar to while but the statements are executed before the condition is tested. The statements will always be executed at least once, which is not true for a while loop.
Let's look at an example. The following code plays a sound every half second while a light sensor attached to input 3 sees dark: