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

207


              int seek_enlightenment(int argc, char ∗∗argv) {
                  int baseline, current, loop_count, result;

                  seek_command = COMMAND_NONE;

                  // Get a baseline.
                  baseline = process_light(SENSOR_2);

                  loop_count = 0;

                  while(1) {
                      msleep(50); // Slow things down a little.
                      // Every so often, increase the baseline.
                      if (++loop_count == 5) {
                           if (baseline < 100) baseline++;
                           loop_count = 0;
                      }
                      current = process_light(SENSOR_2);
                      lcd_int(current ∗ 100 + baseline);
                      lcd_refresh();
                      // If the current value is somewhat less than the baseline…
                      if (current < (baseline - FUDGE)) {
                           // Set the baseline from the current value.
                           baseline = current;
                           // Search for something better.
                           if (sys_time % 2 == 0) seek_command = COMMAND_LEFT;
                           else seek_command = COMMAND_RIGHT;
                           result = wait_for_better(baseline, 1000);
                           if (result == -1) {
                               // If that timed out, search back the other direction.
                               if (seek_command == COMMAND_LEFT) seek_command = COMMAND_RIGHT;
                               else if (seek_command == COMMAND_RIGHT) seek_command =
                               COMMAND_LEFT;
                               result = wait_for_better(baseline, 2000);
                               if (result != -1) baseline = result;
                               // If there's nothing better, bail.
                           }
                           // Set the new baseline.
                           else baseline = result;
                      }
                      // Relinquish control.
                      seek_command = COMMAND_NONE;
                  }
                  return 0;
              }

              int cruise_command;

              int cruise(int argc, char ∗∗argv) {
                  cruise_command = COMMAND_FORWARD;
                  while (1) sleep(1);
                  return 0;
              }
   213   214   215   216   217   218   219   220   221   222   223