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

79


          arbitrarily. Next, main configure s input 2 for a light sensor. Finally, it starts the lightWatcher task.

          Using Two Light Sensors

          In this section, I'll present an NQC program that wor ks  with the two light sensor version of Trusty. As you may recall,
          programming this robot in RCX  Code was cumbersome.

          The programming is a lot cleaner in  NQC. It's pretty straightforward to translate Table 3-1 into source code. The basic strategy
          is to use a state variable to repr esent the four states of the robot, represented by the four lines of Table 3-1. Then one task
          examines the sensors and updates the state  variable. Another task examines the state variable and sets the motors appropriately.

          The four possible states are r epresented by constant values. A fifth value, INDETERMINATE, is used when one or both of the
          light sensor values is not in the d ark or light range:

              #define BOTH_ON 3
              #define LEFT_ON 1
              #define RIGHT_ON 2
              #define BOTH_OFF 0
              #define INDETERMINATE 255

          The  main  task simply  tests the value  of the  state  va riable and sets the  motors accordingly. No action is taken  for
          BOTH_OFF and INDETERMINATE:

              while  (true) {
                  if  (state == BOTH_ON)
                      OnFwd(OUT_A + OUT_C);
                  else if (state == LEFT_ON) {
                      Off(OUT_A);
                      OnFwd(OUT_C);
                  }
                  else if (state == RIGHT_ON) {
                      Off(OUT_C);
                      OnFwd(OUT_A)   ;
                  }
              }

          A separate task, watcher, exam ines the light sensor values and sets the state variable. Here is the entire source code for
          the two sensor version of Trusty:

              int state;

              // "ON" re  fers to whether the light
              // sensor is on the line. If it is,
              // the light sensor is seeing black.
              #define BOTH_ON 3
              #define LEFT_ON 1
   85   86   87   88   89   90   91   92   93   94   95