`
`S
`
`aha
`
`pier
`
`3%
`A
`.35 :the"'§RC
`
`2’
`
`LE5
`
`£)RC[;
`
`‘Yf’
`
`é_3‘Tqi,'§e‘‘r
`
`E
`
`:K
`
`M«#3.».,_,.
`§,,.,¢m.,,M.
`
`
`,.337
`
`,..:3
`,.2223.,
`
`...w.x..(,.
`
`wwxmfifia
`
`WW
`
`vs
`,we?;.
`
`do
`
`..<wx.,H_;..
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`ature of robotics
`
`architecture and then a’
`.
`'
`it. We will describe its
`__1V€‘ you a taste of the broad range oflanguages and pro-
`gramming environments available, fi‘om which you can choose yo 7
`focus Will be on two ofthem in particular: RCX Code, the graphic progran1~
`ming system supplied with the kit,
`language for the RCX.
`
`c C E
`
`. f ‘
`
`I f c l
`
`complete code example, which is
`~'ell—organized code t
`'
`meant to help explain how to
`hat is easy to undeiu
`stand and maintain and is designed to familiarize you with the programming
`structures you’ll find later in the book.
`What ls the RCX?
`
`The RCX is
`
`their computers—~but
`the external World are
`
`
`
`98
`
`Chapter 6 ° Programming the RCX
`
`troduction, this book is not
`about pro
`many good resources about
`programming languages
`prograniming the RCX in p
`articul
`ar. However, the n
`(often called met/zatromrs)
`is such that it comb"
`electronics, and software
`es ofniechanics,
`,meaning you cannot discuss a robots mechanics with
`getting into the sofiware that controls the elt
`'
`Similarly, you c
`annot Write the progr
`the robot itself in your mind. This
`
`gran1n1ing~there ;
`and techniques,
`
`ai e that explaining
`ely poor description. For
`skip the topic, we need to lay the foundations
`you to understand the few code examples contained in the book.
`
`
`
`
`
`in any way, since it is permanently written on the chips, while the data in the
`RAM can be replaced or modified. The RAM requires a continuous power supply
`in order to retain its content.W1ien the supply breaks, everything gets erased.
`Above the processor and circuit layer you find the ROM code.When you
`unpack your brand new RCX, there’s already some code stored in its internal
`ROM tl1at’s aimed at providing some basic functionality to the RCX: input ports
`signal conversion, display and output ports control, and IR communication. If
`you are familiar with the architecture of a personal computer, you can compare
`this ROM code to the ba.sic input/output system (BIOS), the low—level machine
`code which is in charge of booting the computer at startup and interfacing with
`the peripherals.
`An RCX with just the ROM code is as useless as a personal computer with
`-just the BIOS. On top of the ROM code layer the RCX runs thefirmware,
`I which, to continue with our comparison to computers, is its operating sy5tem.The
`terrri firmware denotes a kind of software the user normally doesrft alter or
`V change in any way; it’s part of the system and provides standard functionality, as
`operating systems do. In RCX, the firmware is not burned into the system like
`ROM code, rather it is stored in the internal RAM, and you download it
`L from your PC using the infrared interfaee.The LEGO firmware was copied to
`Your PC during the installation of the MINDSTORMS CD—ROM, and trans—
`red to your RCX by the setup process.
`, The firmware is not the final layer of the system: on top of it there’s your
`I tlcode and data.They will be stored in the same RAM where the firmware is,
`Elli frorn a logical standpoint they are considered to be placed at a higher level.
`<3 explained earlier, you write your code on the PC, then send it to the
`p¥CX.throu.gh the infrared interface.The IVIINDSTORMS software on the PC
`.6, called RCX Code, translates your program (made of graphical code blocks)
`i3.C0mpact form called byzferode. The RCX receives this bytecode via the IR
`
`Programming the RCX - Chapter 6
`
`99
`
`user interface?You write a program on your PC, then transfer it to the RCX
`with the help of the IR tower (a device designed to work as a link between the
`13C and the RCX), and, finally, the RCX executes it.
`To understand how the RCX works, imagine a structure made of multiple
`1ayers.At the very bottom is the processor, an Hitachi H8300, which executes the
`machine code instructions.The processor cooperates with additional components
`that convert signals from the ports into digital data, using chips that provide
`memory for data and program storagejust as with most computers, the memory
`of the RCX is made up of two types: read—only memory (ROM) and random
`access memory (RAM).The content of the ROM cannot be altered or cancelled
`
`.
`
`,
`
`.
`
`
`
`100
`
`
`Chapter 6 - Programming the RCX
`
`remains supplied just to keep the firmware in existence, and this is the
`reason why the RCX will slowly drain the batteries even when switched
`off. lf you plan not to use it for more than a few days, we suggest you
`remove the batteries to preserve them. Remember that when you need
`your RCX again, you will have to reload the firmware.
`
`Let’s summarize the process from the top to the bottom level:
`3 You write your program using RCX Code, the MINDSTORMS soft-
`ware on the PC side.
`
`
`
`H RCX Code ztutomatically translates your program into a compact
`format called byzfecode.
`Using the IR link between the PC~y'ia the IR tower—~to the RCX,
`you transfer the bytecode Version of your program to the RAM of the
`
`H The firmware interprets your bytecode and converts it into machine
`code instructions, calling the ROM code routines to perform standard
`system operations.
`
`I The RCX processor executes the machine code.
`
`
`
`
`
`Programming the RCX ° Chapter 6
`
`101
`
`devices the ability to be programmed from a PC, with which it communicates
`through the “tower,” which in this case is based on radio frequency instead of
`infrared transmission. But the similarities end here, and the Cybermaster has more
`limitations than the RCX:
`
`I
`
`lts three input ports work with passive sensors only.
`
`5 The firmware is in ROM instead of RAl\/I.This means that its not pos—
`sible to upgrade it to a newer version.
`'
`
`E The RAM is much smaller than the one in the RCX and can host only
`very short programs.
`
`The Scout, contained in the Robotics Discovery Set, is programmable from
`the PC with the same IR tower of the RCX (not included in the set), but fea-
`
`tures a larger display that allows some limited programming, or better said, it
`allows you to choose from among various predefined behaviors. it features two
`
`output ports, two input ports (passive sensors only), and one embedded light
`sensor. Like for the Cybermaster, the firmware is in ROM and cannot be
`upgraded or modified.
`
`Using LEGO RCX Code
`
`C
`
`T
`
`RCX Code is the graphical programming tool that LEGO supplies to program
`the RCX. If you have installed the MINDSTORMS CD—ROM, followed the
`lessons, and tried some projects, you’re probably already familiar with it.
`VRCX Code has been targeted to kids and adults with no programming expe~
`rience, and for this reason it is very easy to use.You write a program simply by
`dragging and connecting code blocks into a sequence of instructions, more or less
`if ike using actual LEGO bricks.
`“There are different kinds of code blocks that correspond to different func~
`ns;You can control motors, watch sensors, introduce delays, play sounds, and
`pplrect the flow of your code according to the state of sensors, timers, and coun-
`€r...7RCX Code also provides a simple way to organize your code into
`‘ ourines, groups of instructions that you can call from your main program as if
`hieY'W€re
`a single code block.
`_When you think your code is ready to be tested, you download it to the
`C!X»lIhrOL1gh the IR toWer.The RCX has five progrzmz slots that can host five
`Vptindent programs.V‘Vhen downloading the code, you choose which slot to
`iilload to, and with the Prgm push—button on your RCX, you select which
`
`
`
`
`
` 102
`
`The intuitiveness of RCX Code
`enced users, but it has some major dr
`I
`lts set ofinstructions is very limited, and doesn’t disclose all the power
`your RCX is capable of. Sooner or later you will start desiring a more
`powerful language.
`
`makes it the ideal Comp
`awbacks:
`
`anion for ineXperj_
`
`Chapter 6 - Programming the RCX
`
`I
`
`Its graphical interface is not suitabl
`code blocks, though very intuitive
`follow when you have tenths or h
`For these reasons, you’ll find that RCX Code is a barrier to the development
`of complex projects.
`
`e for large programs.The sequence of
`for small programs, becomes h ard to
`undredths of them.
`
`actually offers many more possi—
`. lt’s like having a car whose
`motor is ca able of 100 m h but with an accelerator
`edal that allows vou to
`P
`P
`J
`P
`reach no more than 50 mph.The power is there, but the interface doesn't allow
`you to get at it. This fact drove some independent developers to create new pro—
`
`most from the LE
`
`of making a new interface on the PC side thatls
`able to generate bytecode and transfer it to the RCX.
`Developed and maintained by Dave Baum, the language called Not Quite C
`(NQC) has achieved enormous popularity among MINDSTORMS fans and is by
`far the most widespread ofthis category. NQC is based on C~like syntax; ifyou’re
`
`I
`
`lt’s based on the original LEGO firmware, thus ta
`
`proven to be rock solid.
`
`5
`
`Dave Baum puts a lot of effort int
`new features and acknowledging o maintaining it, continuously adding
`new opportunities offered by the
`
`4I>
`
`
`
`
`
`
`
`Some of the projects discussed in this book actually require that you go
`beyond the limits imposed by RCX Code.This is the main reason why we chose
`NQC to illustrate the few programming examples. NQC also has the advantage
`that, being a textual language, it allows for a Very compact representation that
`better suits the format ofa book.
`
`"Using ther Programming Languages
`is it The fact that LEGO placed the firmware of the RCX in the RAM left the
`M
`P "system open to other languages that follow a more radical approach. Instead of
`
`A substituting the software that produces bytecode on the PC side, they replaced the
`1
`firmware on the RCX. It’s important to note that installing any of these alterna-
`tive environments doesn’t entail any risk at all for your RCX.You can always
`i‘
`turn to your original system.
`" All the work that has been done in this direction heavily relies on Kckoa
`Pt'oudfoot’s pioneering hacking of the RCX. Kekoa patiently disassembled the
`LEGO firmware and documented all the routines and their calls, thus laying the
`tfmllldations for the subsequent alternative firmware versions.
`
`_
`
`
`
`of
`l
`
`1t
`
`Programming the RCX - Chapter 6
`
`103
`
`LEGO firmware. NQC supported the new RCX 2 firmware Version
`well before it was officially released in any LEGO product.
`
`It is multiplatform, both on the host side (it runs on PC, Mac, and Linux
`machines) and on the target side (it supports all the LEGO pro-
`grammable bricks: RCX, Scout, Cybermaster).
`
`It is self~contained.To use NQC you don’t need any other tools than a
`.
`.
`.
`.
`.
`.
`simple text editor (Windows Notepad 1S enough).The installation proce-
`dure is as easy as copying a file.
`
`5
`
`E
`
`H There are many documents and tutorials, in many different languages,
`that help new users understand all the details.
`
`5 The NQC compiler is a command—line tool, with no user interface, but
`eo le have develo ed nice integrated develo ment environments that
`P
`P
`P
`27
`P
`encapsulate NQC inside a productive system that includes editors, tools,
`dia nostics, data lo Gin , and other utilities, as well as, most im ortantl ,
`g
`gr:
`g
`P
`Y
`the Bricx Command Center.
`
`I NQC is free software released under the Mozilla Public License (MPL).
`
`
`
`
`
`104
`
`Chapter 6 - Programming the RCX
`
`Using legOS
`
`In 1999, l\/larkus Noga started The legOS Project, the first attempt to Write a
`replacement firmware for the RCX. Noga’s goal was to bypass all the limitations
`of the bytecode interpreter to run the code directly on the Hitachi H8300 pro-
`cessor of the RCX.A legOS prograni is a collection of system management rou-
`tines that you link to your own C or C++ code and load to the RCX in place
`of the firmware.
`Wliat was initially an individual effort turned into a collective open source
`p}‘0_j€Ct under the Mozilla Public License.Tl1e legOS Project is now managed by
`Luis Villa and Paolo Masetti and maintained by a team ofa dozen developers.
`The installation is not always straiglitforward, especially r"or\7\/indows
`niachines.You need to be a programming expert because What you have to deal
`with here is true C, not the simplified and friendly NQC version.You have to
`mamge cross~compilcrs and Unix emulators if you don't run a Unix—lil<e
`machine, so legOS is definitely not For everyone. But For this price it unleashes
`the full power of your RCX up to its last bit.You get full control of any resource
`and any device, can use any C construct and structure, and can address any single
`byte of memory. Plus, your code runs at an astonishing speed when compared to
`the interpreted bytecode.
`
`Using pbFort‘n
`
`The pbForth language (the name stands for progm/Izz/ml)/e /irfr/e FORTH) is the
`result of Ralph Hempels experience in designing and programming embedded
`systems, a field where FORTH is particularly well suited. Conceived in the six-
`ties, the FORTH language has a strong tradition in robotics, automation, and sci-
`entific applications. More than a language, FORTH is an interactive
`environment. The traditional concepts of editing source files, compiling, linking,
`and so on, don’t translate very Well to FORTH; it’s mainly a stand—alone system.
`Ralph Hempel’s implementations make no exception to this rule.You down-
`load the pbForth kernel to your RCX, and from that moment on you dialog with
`it using a simple terminal emulator. For this reason, pbForth is very portable and
`very easy to install on any platform.
`If you haVen’t any experience with FORTH, it will probably seem a bit
`strange to you in the beginning. The language is based on the past ‘X zzamriazz, also
`called reverse polish notation (RPN), which requires you to write the operator
`after the operands.
`
`
`
`
`
`
`
`Programming the RCX ° Chapter 6
`
`105
`
`If you decide to give pbForth a try, you will discover the benefits of an
`extensible system that naturally leads you to program in terms of layers.You
`might find it challenging to learn, but it’s a productive-—and fun-tool with
`which you can write compact and efficient code.
`
`Using lel@S
`
`Jose Solorzano started the TinyVl\/l Project, a small Java footprint for the RCX.
`. TinyVM was designed to be as compact as possible, and for this reason lacked
`much of the extended functionality typical of Java systems. Over the foundation
`ofTinyVM,jose and other developers designed le]GS, a fully functional java
`implementation that includes floating point support, mathematical functions,
`multiprogram downloading, and much more. LejOS is an Open Source project
`and, like legOS, is under continuous development.
`lejOS is the newcomer on the scene ofl\/lIi\lDSTORl\/l8 programming, but
`we foresee a great future for it. its complete, portable (currently to PC and
`UniX—like machines), Very easy to install, fast, efficient, and based upon a
`widespread language.There are also some visual interfaces under development
`that will make this system even more attractive to potential users.
`
`Using Other Programming
`Tools and Environments
`
`We know we didn’t cover all the available programniing tools for the RCX.
`There are others, like Gordon's Brick Programmer, or Brick Command, that
`follow the same solution of NQC and convert a textual program into bytecode.
`There are also a few more replacements for the firmware, like QC or TinyVl\/1.
`And, finally, some other tools, like ADA for the RCX, that translate source code
`into NQC code. They are good tools, solid and well—tcsted, but We choose to
`describe the most representative and Widespread in each class,We recommend
`you look at Appendix A for further information about the soft‘ "are we intro»
`duced here and about other possible choices; the list is so long we are sure you’ll
`find the tool that fits your needs. In the same appendix, you will find some links
`to other tools that, though not intended for programming, can help you monitor
`YOUY RCX, transfer data to the PC, graph the status of the input ports, and more.
`
`
`
`
`
`106
`
`Chapter 6 - Programming the RCX
`
`Divide and Conquer:
`Keeping Your Cede Organized
`
`
`
`he program
`of which are a bit complex,
`with.We chose to Write all
`it combines power with compactness. it’s e
`to install and learn, and has become a widespread stan
`
`your favorite progmmming Ianguagrs.
`What we said in Chapter 5
`
`
`
`
`
`Programming the RCX - Chapter 6
`
`107
`
`Input port 1 is attached to a touch sensor connected to the bumper. It
`closes (goes from O to 1) when the bumper is pressed.
`
`5
`
`Input port 2 is attached to a face-down light sensor that reads the line.
`
`Here is the initial code you should write:
`
`int floor,line;
`
`task Maim)
`(
`
`Initialize();
`
`Calibratell;
`
`Go»Straight():
`
`while(true)
`
`{
`
`Check_Bumper();
`
`Follow4Line();
`
`3”
`
`EX,
`
`3]}
`
`("D
`
`L
`
`i
`
`X
`
`The main level of your program is quite simple, because at this point you’re
`not concerned with what Go_Straight or the other subroutines mean in terms
`of actions, you’re only concerned with the logic that connects the different situa-
`ftio1is.You are deciding the rules that affect the general behavior of the robot and
`“you don’t want to enter into the details of how it can actually go straight. This
`result is achieved by encapsulating the instructions that make your robot go
`' aight into a subzrowine, a small unit which “knows” what the robot requires in
`i order to go straight.This approach has another important adVantage:Your code
`will be more general because it doesn’t depend on the architecture of the robot.
`“ For example, for one specific robot “go straight” will mean switching motors A
`?tI1dpC on in the forward direction, while for another it might mean switching on
`T5}20l§O‘r B in the reverse direction.\X/hen you want to adapt the program to a dif-
`tent architecture, you simply change the implementation details contained in
`l1E lQW—level subroutines, without having to intervene on the logic flow.
`‘
`l—>€t’S come back to your main task to examine it in deeper detail. The first
`notion is actually placed before the beginning of the task: It declares that you
`0mg to use two 1/czriables named floor and line and intended to contain integer
`
`
`
`
`
`108
`
`Chapter 6 - Programming the RCX
`
`
`
`neither assigning nor reading the Variables, you are simply
`declaring that you
`need two of them. In other \VOI‘dS,
`you are asking NQC to prepare two boxes
`with the names just mentioned.
`When the user presses the Run button 0
`After it has completed initialization and C
`the robot in straight motion, then it ente
`
`n the RCX, the main task begins.
`alibration procedures, the program starts
`rs an endless loop Where the program
`ving obstacles and following the line.
`e instructions delimited by the op en and
`close brace forever. In your case, it will e
`Xecute the Check_Bumper subroutine,
`then the Follow_line, then the Check Bu
`_ mper again in a continuous loop that
`only the user can interrupt using the Run button.
`Everything is clear and simple, as it should be. Now let’s
`happens at a lower level in our subroutines.
`Any program will typically ’
`motor power, configure the sensors,
`
`have a look at What
`
`'
`
`void Initialize()
`{
`
`SetSensor(SENSOR_l,SENSOR_TOUCH);
`SetSensor(SENSOR_2,S3NSOR_LIGHT);
`
`
`
`xmmmmwu
`
`
`
`
`
`
`
`
`
`i..When you run the program, the calibration procedure begins and informs
`you with a beep that it Waits for the first reading.You place your robot with the
`light sensor on the floor, far from the line, and push the bumper. The program
`reads the light sensor and stores that Value as a typical “floor” Value in thefloar
`” Var‘i’able.Then it beeps again while Waitinglto read the line.You place the robot
`K Witll the sensor just over the line and push the bumper again, making it detect
`” gtl1€“line” light value and store it in the line Variable. The robot finally beeps
`’
`i‘ in, meaning the calibration process has finished and that the next push on the
`mpfir will put it in motion.
`This sort of pre—run phase is quite useful in many other situations, such as
`V“ YOU need to prepare the robot for operations by either reading some envi-
`“W-
`miilflental Variable or resetting mechanisms that might have been left in an
`a
`-
`.
`.
`us
`ll‘ HQVVII state by previous executions.
`
`Programming the RCX ° Chapter 6
`
`109
`
`void Ca1ibrate()
`
`{
`
`WaitBumperPress();
`
`floQr=SENSOR_2;
`
`WaitBumperPress();
`
`line=SENSORw2;
`
`WaitBumperPress();
`
`void Wait_Bumper_Press()
`
`{
`
`PlaySOuI1d ( SOUND_DOUBLE_BEEP) ,-
`
`while (S3NSOR_l==O);
`
`// wait for bumper press
`
`while (SENSOR_l:=1);
`
`// wait for bumper release
`
`This code shows that in some situations you can recycle a sensor and use it
`for more than a single purpose: during the calibration process, the bumper is used
`as a trigger to tell the robot that it’s time to read a Value. It also shows that sub
`
`routines can be nested. In other words, you can make a subroutine call another
`subroutine. In this particular case, the WaitBumperPress is a small service sub-
`routine that procluces a beep and then waits until the bumper switch gets pressed
`and released.
`
`. 7.
`
`
`
`
`
`110
`
`Chapter 6 - Programming the RCX
`
`The CheCk_Bumper procedure is in charge of testing whether the robot
`has hit an obstacle, and if so, how it should react:
`void Check_Bumper()
`{
`
`if (SENSOR_l== )
`f
`
`StOp();
`Remove_Obstacle{) 7
`
`Go_Straight();
`
`It checks the bumper, and,
`if found closed, stops the robot, calls the
`Remove__ObstacIe subroutin
`e to Clear the path and then resumes motion.
`Testing the bumper is as simpl
`e as checking if SE-NSOR__1 has become equal to
`l, which means that the touch sensor connected to port 1 has been pressed.You
`notice that we apply here the same concepts used at the main level: enc
`details into routines at a lower level.
`
`“floor” Value, it
`turns right toward the line. lflion the contrary,
`it reads too much of the “line”
`value, it turns lefi, away from the line.
`(See Chapter 4 for a discussion of this
`method.)
`
`void Follow_Line()
`{
`
`#define SENSITIVITY 5
`if
`
`(SENSOR_2<=floor+SENSITIVITY)
`Turn_Right();
`
`// reading too "floor"
`
`else if (SENSOR_2>=line—SENSITIVITY)
`Turn_Left();
`
`// reading too “line”
`
`
`
`
`
`Programming the RCX ' Chapter 6
`
`111
`
`*
`
`DEE <oUT_A+oUT_c 3
`
`I
`
`f1‘urn_Le f 1; ( )
`
`
`
`of simplicity, you can consider a constant to be like a Variable whose Value cannot
`be changed by the program. In this particular case, your program defines the con-
`stan.t SENSITIVITY with the value 5.This value is used together with the floor
`and Z2’;-ze Variables to decide what the robot should do. An example with actual
`numbers can make the things clearer: suppose the Calibrate routine placed the
`Value 55 in the floor Variable and the Value 75 in the line variable.The program
`tests if SENSOR_1 is less than or equal to floor + SENSITIVITY, which results in
`55 + 5 = 60, to decide if the robot has to turn right toward the line. Similarly, it
`tests if SENSOR_l is greater than or equal to floor — SENSITIVITY, which cor-
`responds to 75 — 5 = 70, and if this is the case, it makes the robot turn left, away
`from the li11e.While the readings remain greater than 60 and lower than 70, the
`robot goes straight.You can change the Value of SENSITIVITY to make your
`robot more or less reactive to readings: An increase will narrow the range of Values
`that allow the robot to go straight, thus your robot will make more corrections in
`order to remain close to the edge of the line.
`The code you wrote so far is rather general and could work for a broad class
`of robots. Now the time has come to write the part of the program that depends
`on the physical architecture of your robot.
`The Go_Straight routine will be Very straightforward in most cases.You
`I know from the initial assumptions that the robot has two side wheels (or tracks)
`driven by two independent motors. In Chapter 8, we will explore this configura-
`tion, called dfierezitial drive, in greater detail. For the moment, let’s stick to the fact
`that if both the motors go forward, the robot goes forward and straight. If one of
`the motors stops, the robot turns toward the side of the stationary wheel.This
`I t‘s"slmowledge is enough to Write the following routines, which control motion:
`
`I
`
`\
`
`Q. Void Go_Straight ()
`
`onFwd (OU’I‘_A+OUT_C) ;
`
`
`
`
`
`112
`
`Chapter 6 - Programming the RCX
`4.L
`
`Off(OUT_A);
`
`OnFwd(OUT_C}
`
`z
`
`void Turn_Right()
`{
`
`Off(OUT_C);
`
`OnFwd(OUT_A)
`
`1
`
`needs
`
`of the
`
`35
`
`made
`
`Ru
`
`All t}
`
`muff!’
`same
`
`well-
`
` secom
`
`appr
`
`you:
`titas
`mar
`
`ally
`the
`
`diff
`act
`
`mc
`
`tasf
`
`th<
`CW
`
`
`
`
`
`tie
`
`Programming the RCX - Chapter 6
`
`113
`
`There’s one last routine left: RemoVe_Obstacle. Let’s say your robot features
`a Very simple arm that works with a single motor and only requires a timed acti-
`Vation:
`
`void Remove_Obstacle()
`
`{
`
`OnFwd(OUT_B);
`
`Wait (200);
`
`OnRev(OUT_B);
`
`Wait(200);
`
`Off (oUr_B) ,-
`
`
`
`The statement Wait(2GO) makes the program wait for 200 hundredths of a
`second, or two seconds.This parameter depends on the time your mechanism
`needs to remove the obstacle, and it is once again related to the physical structure
`of the robot.
`
`Your program is now finished and ready to be tested. We hope this example
`made you realize the benefits of a modular and well—structured code.
`
`Running Independent Tasks
`
`if
`
`T
`
`,
`
`All the tools you can choose from to program your RCX support some form of
`rniilzfitaskzflg, that is, they support two or more independent tasks that run at the
`same time. This is not particularly evident when you use RCX Code, but it’s a
`M\i?V€ll-ClOC111T1€I1C€d
`feature in all the alternative environments.
`Multitasking can be helpful in many situations and it’s often a tempting
`approach, but you should use it with a lot of care because it will not always make
`our life easier. Let’sgo back for a moment to" our previous’ example: would mul-
`i titasking have been a good choice? Didn’t your robot have two different tasks to
`manage: line following and obstacle detection? ‘Well, it did, but they were mutu-
`eXclusive~——after all, your robot was not following the line wlzile it removed
`the obstacle. In cases like this, and in many others, your robot is asked to perform
`. rent activities one at a time more often than it is asked to perform different
`Ctivities at the same time. Using multitasking, you would have made your code
`,0”/‘_CpOmpleX, because of the additional instructions needed to synchronize the
`Q51“-Wlleii the Rem0Ve_Obstacle task stops the robot, it should communicate
`Fo1Iow__Line task to susp end line following, and communicate again when it
`
`an lit: resumed.
`
`
`
`114
`
` Chapter 6 ° Programming the RCX
`
`In designing a multitasking application, you are required to move from a
`sequential, step—by—step flow to an ev€1zr—rIrz'u€n
`scheme, which usually requires
`additional work to keep the processes coordinated.\X/hile sequential program-
`ming is like following a recipe to cook something, you can compare multitasking
`to preparing two or more recipes at the same time.This is quite a common pi-ac V
`tice in any kitchen, but requires some experience to manage the allocation of
`resources (stoves, oven, mixer, blender...), respond to the events (somethings ready .
`to be taken out of the oven) and coordinate the operations so the tasks don’t
`conflict with each other.You have to think in terms ofp2*.f0i'z'rz'es:‘X7hich dish
`should you put in the oven first? Programming independent tasks implies the
`same concerns:You must handle the situations where two tasks want to control
`the same motor or play two different sounds.The RCX is well—equipped to
`manage resource allocation and to support event—driven programs, and NQC
`gives you full access to these features. However, most of the effort is still on your
`shoulders: no tool
`13l{€S up for the disadvantages inherent in a bad design.
`In our experience with LEGO robotics, there are few actual situations where
`multitasking is absolutely necessary, or even useful. Our suggestion is that you
`approach it only when your robot performs some really independent activities,
`like playing background music while navigating a room, or responding to mes—
`sages while looking for a light source.
`
`Summary
`In this chapter, you took some first steps on your path to programming LEGO
`robots.\X7e started describing the RCX, the LEGO programmable unit that’s the
`core ofyour robots, to unveil some ofits secrets.You discovered how its architec-
`ture can be easily understood in terms of layers: your program, its translation into
`bytecode, the interpreter in the firmware, and the processor which executes the
`operations.
`To create your program on a PC, you can choose from many available tools;
`we briefly described RCX Code, the original LEGO graphic programming envi~
`ronrnent, and NQC, the most widely accepted independent language for the
`RCX. We also reviewed a few other environn1ents———legOS, pbFORTH, le]OS~
`which follow a more radical approach to the goal of getting the most from the
`RCX: replacing its firmware.
`The second part of the chapter does for programming what the previous
`chapter did for building: it establishes some guidelines. Oddly enough, the two
`arenas share a lot, since layered architecture and modularity principles apply just
`
`
`
`
`
`Programming the RCX - Chapter 6
`
`115
`
`as much to the body of the robot as they do to its brain~—With the notable dif-
`ference that sometimes you have good reason not to follow those principles in
`the hardware. In other words, there is no excuse for badly organized sofiwarel We
`used a short but complete program Written in NQC to put these principles into
`practice, showing how they can improve the readability, reusability, and testability
`of your code.