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

46


          The environment does provide a counter, which we'll use in lieu of a variable to hold the turning direction. Although you can't
          assign values directly to the counter, you can do two things: reset it to zero and add one to it. Trusty will use just two values, 0
          an d 1, to mean turn left and turn right, respectively.

          Coping with Failure

          Our basic assumption about Trusty is that he will drive off the black line on alternating sides. But this probably won't really
          happen all the time, parti cularly if the black line has curves in it. What Trusty needs is some way to figure o ut if he's turning
          th e wrong way, away from the line instead of toward it. For this purpose, we'll use a timer. If Trusty doesn't find the line within
          a certain time interval, we'll have him switch state and turn back the other way.

          The real world is a very challenging place. You should always assume that bad things will happen to your robot and try to
          create a program that responds appropriately.

          T he Program

          Figure 3-3 shows Trusty's basic program. It begins by setting the two motors to the forward direction at speed 4. The central
          decision point is the light sensor watcher. If the sensor sees the black line, Trusty moves straight ahead. If the sensor sees the
          white background, then the program resets the timer and calls a subroutine called toggle. This subroutine turns the robot left
          or right, alternating each time it is called.























                                                        Figure 3-3.
                                              A top-level view of Trusty's software
   52   53   54   55   56   57   58   59   60   61   62