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

201


              tm_start();

              return 0;
            }

          Let's start at the  bottom and work our  way up. The  main()  method uses  execi()  to start the two tasks:
          display_task()    and stop_task(). The process ID of the di splay task is saved away in the pid variable so that it can
          b e stopped later. The last thing main() does is call tm_start() to start the task manager, which actually handles running
          the tasks.

          The stop_task() waits for the  Run button to be pressed. When the button is pressed, stop_task() calls kill() to
          st op the display process. What's that call to msleep() at the beginning of stop_task()? When legOS first boots on the
          RCX, it's waiting for the  Run  bu tton to be pressed. As soon as it is, your program is started. It's very possible that
          stop_task()  will already be running  b efore you  have a chance to take your  finger off the  Run  button. The call to
          m sleep() simply delays a little while to g ive you a chance to release the Run button.

          The  display_task()  is straightforward.  It alternates between displaying "Hello" and "nurse"  on the  display, looping
          forever until it is killed by stop_task().

          Waiting (unistd.h)

          For a le  w  t                                          ):
               c aner  ay o wait for specific events, consider wait_event(

          wakeup_t wait_event(wakeup_t (∗wakeup)(wakeup_t), wakeup_t dat a)
          U se this function to wait for a specific event. The function pointed at b y wakeup is called, with data as a parameter, until it
          returns a non-zero result. At this point, wait_event( ) will return.

          It's not hard to use wait_event(), but it's certainly not obvious. It helps to look at some of the examples that come with
          legOS. The  following is a rewrite of the previous example that uses wait_ev ent() instead of a while loop:

              #include "conio.h"
              #include "direct-button.h"
              #include  "unistd.h"
              #include  "sys/tm.h"

              pid_t pid;

              int d isplay_task(int argc, char ∗∗argv) {
                  w hile(1) {
                      cputs("Hello");
                      lcd_refresh();
                      sleep (1);
                      cputs("nurse");
                      lcd_refresh();
   207   208   209   210   211   212   213   214   215   216   217