Page 76 - The Unofficial Guide to Lego Mindstorms Robots
P. 76

65


          Program Flow

          You've seen how to control the RCX's outputs and inputs. But robot programs aren't very interesting un less they can make
          d ecisions 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'v e ever programmed in other languages (particularly C), this will look familiar.

          W aiting
          Although it might not seem important, N QC 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—m aybe the robot needs to move forward or turn
          fo r a little while, or you want to give a sound time to play. The co mmand 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
          ta sk for a full second. Note that this only applies to the cu rrent 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:

              unti l (boolean condit ion) [statements]
              U se  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 unti l has an em pty 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 co mpare values and = to assign values.
   71   72   73   74   75   76   77   78   79   80   81