`
`
`
`
`
`
`
`
`
`
`
`dCo
`
`'nquer:
`ala'n
`-rga7n-ize' " '
`'
`
`'
`
`-
`-
`‘
`.p. -,_
`-
`..
`LEGO A/S,.Ez<‘ 2105‘
`Rubicon Comm'un canons, LP.V..-,LEGO A S
`IPR2016—01187‘
`'
`‘
`-
`
`
`
`
`
` Chapter 6 - Programming the RCX
`
`Introduction
`
`821
`about programming the RC
`X in particular.
`(often called met/zatrom'rs)
`is such tl
`electronics, and software,
`
`bout programn‘iing languages and techniques,
`
`OH 1'
`the robot itselfin y
`0‘
`though we are goinD
`have such a strong relatio
`the first while ignoring t
`
`without
`at drives the mach ine.
`aving a general bl ueprint of
`
`projects
`are that explaining
`y poor description. For
`need to lay the foundations
`
` about programming-\there
`
`
`
`[I
`
`C
`C
`
`t f l
`
`f
`
`( l N
`
`E
`
`i
`i.
`
`look at its features and discover ho
`architecture and then give you
`gramming environments availa
`focus will
`
`a taste ofthe bl’O‘
`ad range ofl
`anguages and pro—
`U
`ble, from which y
`ou c
`an choose your favorite. Our
`. ode, the graphic program—
`QC, the most widespread independent
`
`ming system Supplied with the
`language for the RCX.
`The last sections of the ch
`apter prov
`ide a complete code example, which is
`meant to help expl
`ain how to write wel
`l—organized code that is easy to under»
`stand and maintain, and is designed to
`familiarize you with the programming
`structures you ’11 find later in the book.
`
`What Is the RCX?
`
`The RCX is
`
`a computer.You are used to
`
`
`
`
`
`
`
`
`
`
`
`'-...g.-‘.,.,_',V.,1,“wuqmmwflamazingflmmmmnm::".a».,
`
`aggfib55;,ugfifégrmgmmmumpn.emumeasmr1AM:....a..
`
`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
`PC and the RCX), and, finally, the RCX executes it.
`To understand how the RCX works, imagine a structure made of multiple
`layers. 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
`memo1y for. data and program storagejust as with mosr 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
`
`in any way, since it is permanently written on the chips, while the data in the
`RAM can be replaced or modifiedThe RAM requires a continuous power supply
`in order to retain its content.When 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 that’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 ofa personal computer, you can compare
`this ROM code to the basic 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 withjust the ROM code is as useless as a personal computer with
`just the BIOS. On top ofthe ROM code layer the RCX runs the firmware,
`- which, to continue with our comparison to computers, is its operating systemThe
`.- termfirmtmre denotes a kind of software the user normally doesn't alter or
`Changein any w;ay its part of the system and provides Standard functionality, as
`‘_ operating systems do. In RCX, the firmware15 nor burned into the system like
`the ROM code, rather it is scoredin the internal RAM, and you downloadit
`'35me your PC using the inflated interface The LEGO firmware was copied to
`Vour PC during the installation ofthelMINDSTORMS CD—ROM, and trans—
`erred to your RCX by the setup process
`The firmwareis not the final layer ofthe system: on top ofit there’s your
`prI'Code and data. They will be storedin the same RANI where the firmwareis,
`pip-30m a logical stmdpoint they are considered to be placed at a higher level.
`We CXplained earlier, you w1ite your code on the PC, then sendit to the
`X through the infrared interface. The MINDSTORMS softwaie on the PC
`1d Called RCX Code tianslates your program (made of graphical code blocks)
`Compact form called bylcrodt’. The RCX receives this bytecode via the IR
`
`
`
`
`
`
`
`100
`
`Chapter 6 - Programming the RCX
`
`interface and stores it in its RAM.\Vlren you press the Run button, t
`he firmwne
`starts I'i'Ifé’lpi'Cf/llg the bytecode
`and converting its instructions into actions.
`
`
`
`Let’s summarize the process From tl1e top to the bottom level:
`I You write your program using RCX Code, the MINDSTORMS soft—
`ware on the PC side.
`
`5 RCX Code automatically translates your program into a compact
`Format called byreron’e.
`5 Using the IR link between the PC—Via the IR towerfito the RCX,
`you transfer the bytecode version of your program to the RAM ofthe
`RCX
`
`II The Firmware interprets your bytecode and converts it into machine
`code instructions, calling the ROM code routines to perform Standard
`system operations.
`
`a
`
`The RCX processor executes the machine code.
`Most ofthese steps are hidden to the user, who simply prepares the program
`on the PC, downloads it to the RCX, presses the Run button, and watches the
`
`program execute.
`
`A Small Family of Programmable Bricks
`The RCX belongs to a small LEGO famil
`y ofprogrammable brides. The firsr to
`appear on the scene was the Cy
`bermaster,
`a unit that incorporates two motors,
`three input ports, and one outp
`ut port. It shares with the MINDSTORNIS
`
`
`
`
`
`
`
`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
`
`Its three input ports work with passive sensors only.
`
`a The firmware is in ROM instead ofRAM. This means that its not pos—
`sible to upgrade it to a newer version.
`
`a The RAlVl 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
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`" RCX Code is the graphical programming tool that LEGO supplies to program
`
`the RCX. If you have installed the MINDSTORJVIS CD—ROM, followed the
`lessons, and tried some projects, you’re probably already familiar with it.
`RCX Code has been targeted to kids and adullts with no programming expe-
`
`rience. and for this reason it is very easy to use. You write a program simply by
`‘-"_dragging and connecting rode bloc/es into a sequence ofinstructions more 01 less
`
`like using actual LEGO bricks.
`‘
`‘fTh'ere are different kinds of code blocks that correspond to different func—
`
`tions: You can control motor,s watch sensors. introduce delays play sounds. and
`direct the flow of your code according to the state of sensors timers, and coun—
`
`CF RCX Code also provides a simple way to organize your code into
`
`ubrqrrtz‘nes, groups ofinstructions that you can call from your main program as if
`
`63‘ Were a single code block.
`
`When you think your code is ready to be tested you download it to the
`'Xthrough the IR tower The RCX has five program slots that can l1osr five
`
`Pfindent prog1ams When downloading the code, you choose which slot to
`anoad to, and with the Prgm push—button on your RCX. you select which
`
`grim to execute
`
`
`
`upgraded or modified.
`
`Using LEGO RCX Code
`
`
`
`
`
`
`
`102
`
`Chapter 6 - Programming the RCX
`
`The intuitiveness ofRCX Code makes it the ide
`enced users, but it has some major drawbacks:
`
`al companion for inexperi-
`
`B
`
`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.
`lts graphical interface is not suitable for large programs. The sequence of
`code blocks, though very intuitive for small programs, becomes hard to
`follow when you have tenths or hundredths of them.
`For these reasons, you’ll find that RCX
`of complex projects.
`
`
`
`Using the NQC Language
`The LEGO firmware is a solid, well—
`tested software that provides a rather com—
`plete functionality.The surprising thing is that it actually offers many
`more possi-
`bilities than what the RCX Code discloses to us. It’s like having a c
`ar whose
`motor is capable of 100 mph but with
`an accelerator pedal that allows ,
`reach no more than 50 mphThe powe
`r is there, but the interface doesn‘t
`you to get at it. This fact drove some in
`dependent developers to cre
`ate new pro—
`gramming environments able to get the
`mOSt from the LEGO firi
`mvare, pro—
`viding access to those fe
`atures that RCX Code conceals.
`5
`All ofthem share the
`ame approach, which consists of making
`a new interface on the PC side that’s
`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 MlNDSTORMS fans and is by
`far the most widespread ofthis category NQC is based on C—like syntax; if you’re
`not a programmer, or ifyou have no experience with C, don’t be frightened by
`ry smooth learning curve, and comes with a lot of documenta—
`tion and tutorials.
`any reasons:
`The success ofNQC has come about for m
`It‘s based on the original LEGO firmware, thus taking advantage ofits
`II
`ability to produce very reliable code, and at the same time freeing all of
`RCX Code’s hidden power. Even from its very first releases NQC has
`
`Code is a barrier to the development
`
`allov~
`
`a
`
`proven to be rock solid.
`
`Dave Baum puts a lot of effort into m
`new features and
`acknowledging new
`
`aintaining it, continuously adding
`opportunities offered by the
`
`.
`l
`
`
`
`
`
`1
`a:
`”
`:7
`9::
`if;
`f
`"
`
`ME-rmtaeraenattmmanagersymusnt'maammtm
`
`'i—
`
`of
`
`N
`
`
`
`l
`
`Programming the RCX - Chapter 6
`
`103
`
`I
`
`I
`
`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, Cybermasrer).
`It is self-containedTo use NQC you don’t need any other tools than a
`simple text editor (\Vindows Notepad is enough).The installation proce—
`dure is as easy as copying a file.
`
`I! There are many documents and tutorials, in many different languages,
`that help new users understand all the details.
`
`3
`
`The NQC compiler is a command—line tool, with no user interface, but
`people have developed nice integrated development environments that
`encapsulate NQC inside a productive system that includes editors, tools,
`diagnostics, data logging, and other utilities, as well as, most importantly,
`the Bricx Command Center,
`
`II NQC is free software released under the Mozilla Public License (MPL).
`
`
`
`
`
`
`
`
`
`fix{are}
`
`
`
`Some ofthe projects discussed in this book actually require that you go
`beyond the limits imposed by RCX CodeThis 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.
`
`
`
`f'Using Other Programming Languages
`.HThe fact that LEGO placed the firmware ofthe RCX in the RAM left the
`"system open to other languages that follow a more radical approach. Instead of ~
`' _§ubfiituting the software that produces bytecode on the PC side, they replaced the
`
`5 firmware on the RCX. It’s important to note that installing any ofthese alterna—
`'3. tive environments doesn’t entail any risk at all for your RCX.You can always
`
`
`a ' eturn to your original system.
`”All the work that has been done in this direction heavily relies on Kekoa
`
`Btoudfoot’s pioneering hacking of the RCX. Kekoa patiently disassembled the
`
`EGO firmware and documented all the routines and their calls, thus laying the
`OutldatiOIis for the subsequent alternative firmware versions.
`
`
`
`'
`
` wwwisyngressxom -
`
`
`
`
`
`104
`
`Chapter 6 - Programming the RCX
`
`Using legOS
`
`in 1999, Markus Noga startedThe legOS Project, the first attempt to write a
`replacement firmware For the RCX. NngtS goal was to bypass all the limitations
`oFthe bytecode interpreter to run the code directly on the Hitachi H8300 pro—
`cessor ofthe RCX. A legOS program is a collection ofsysrem management rou—
`tines that you link to your own C or C++ code and load to the RCX in place
`oFthe firmware.
`
`\X/hat was initially an individual effort turned into a collective open source
`projeCt under the MOZilla Public LicenseThe legOS Project is now managed by
`Luis Villa and Paolo Masetti and maintained by a team ofa dozen developers.
`The installation is not always straightfin'ward, especially For Windows
`machinesiYou need to be a programming expert. because what you have to deal
`with here is true C, not the simplified and Friendly NQC versionYou have to
`manage cross—compilers and Unix emulators if you don't run a Unix—like
`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 construcr and structure, and can address any single
`byte of memory. Plus, your code runs at an astonishing speed when compared to
`the interpreted bytecode.
`
`Usmg prorth
`
`
`
`The prorth language (the name stands for progrm/i/Iiablc [Mir/e FORTH) is the
`result of Ralph Hempel’s 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. Hempelis implementations make no exception to this ruleYou down—
`load the prorth kernel to your RCX. and From that moment on you dialog with
`it using a simple terminal emulator. For this reason, prorth 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 beginningThe language is based on the pustfix notation, 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 prorth a try, you will discover the benefits of an
`extensible system that naturally leads you to program in terms oflayers.Y0u
`might find it challenging to learn, but it’s a productive—and fun—tool with
`which you can write compact and efficient code.
`
`Using leJOS
`
`“lose Solorzano started the TinyVM 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 ofjava systems. Over the foundation
`ofTinyVMJose and other developers designed lejOS. a quy 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 of MINDSTORMS programming, but
`we foresee a great future for it. It’s complete, portable (currently to PC and
`
`Unix-like machines), very easy to install, fast= efficient, and based upon a
`widespread languageThere 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 programming 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 TinyVM.
`‘ And, finally. some other tools, like ADA for the RCX, that translate source code
`into NQC code.They are good tools, solid and well—tesred, but we choose to
`describe the most representative and widespread in each classNVe recommend
`you look at Appendix A for further information about the software
`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
`y0ur RCX, transfer data to the PC, graph the status of the input ports, and more.
`
`a
`
`
`
`
`
`
`
`106
`
`Chapter 6 - Programming the RCX
`
`Divide and Conquer:
`Keeping Your Code Organized
`Up to this point the few programming examples you met were written in a Sort
`ofpseudo—code very close to plain natural language. The use ofpseudo—code
`allows the programmer to “play computer” and understand what the program
`does, but to complete the projects ofthe book, some of which are a bit complex,
`you need a real environment to run and test the code withWe chose to write all
`
`the documentation available from. its official Web site, listed in Appendix A. Even
`if you don’t choose NQC, we’re sure you can easily translate our examples into
`your favorite programming language.
`What we said in Chapter 5 about keeping your construction designs modular
`applies to programming as well. Organizing the code into logical sub units is a
`good programming practice that will often. help you in the debugging process.
`Unless your robot is designed for a very simple task, try to split its code into
`blocks that correspond to the different situations its expected to manage and to
`the actions it should perform.The Latin motto “divide et impera” applies well to
`programs: the more you divide the code into small sections, the better you can
`control and understand the program's behavior.
`We will use an example to clarify this concept and introduce other tips: Say
`your robot has been designed to follow a black line, detect small obstacles with a
`bumper and remove them from its path by pushing the obstacles away with some
`kind of arm.As we explained earlier, it’s impossible to write a program without
`having at precise idea of how the robot is designed and what it is expected to do.
`For the example we are going to illustrate, we made the following assumptions
`about the robot and the environment:
`
`I The line is darker than the floor.
`II The robot will follow the left border of the line (e.g., It turns right to
`go toward the line, left to go away from line).
`
`B Output port B operates the arm.
`
`
`
`
`
`
`
`
`
`3”
`
`N::
`
`('D
`
`
`
`mWfiQhémmstwirskmmvflzzsmummfimmvmzmzmmsart-mamarlzwmmummmmsm-f“.
`
`
`
`1'
`
`'A
`’
`
`Programming the RCX - Chapter 6
`
`107
`
`5
`
`I!
`
`Input port 1 is attached to a touch sensor connected to the bumper. [t
`closes (goes from O to 1) when the bumper is pressed.
`
`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 Mainl)
`
`(
`
`Initialize();
`
`Calibrate():
`
`Go_Straight();
`
`while(true)
`
`(
`
`Check_Bumper();
`
`Follow_Line();
`
`The main level of your program is quite simple, because at this point you’re
`not concerned with what G0_Straight or the other subroutines mean in terms
`'-' of-actions, you’re only concerned with the logic that connects the different situa-
`5.11
`j'j :"'“ti'ons:'You are deciding the rules that affect the general behavior ofthe robot and
`'
`you don’t want to enter into the details oflww it can actually go straightThis
`result is achieved by encapsulating the instructions that make your robot go
`straight into a subroutine, a small unit which “knows” what the robot requires in
`-.0rder to go straight.This approach has anocher important advantagezYour code
`W111 be more general because it doesn’t depend on the architecture of the robot.
`F0Fexample, for one specific robor “go straight” will mean switching motors A
`al’ld C on in the forward direction, While for another it might mean switching on
`i 9%? B in the reverse direction.When you want to adapt the program to a dif—
`f F611; architecture, you simply change the implementation details contained in
`low—level subroutines, without having to intervene on the logic flow.
`Le TS Come back to your main task to examine it in deeper detailThe first
`.VCtion is actually placed before the beginning of the task: It declares that you
`30mg to use two variables namedfloor and line and intended to contain integer
`
`
`.wwwsy areas-CO,
`
`
`._i_-
`
`
`
`
`
`
`
`
`
`108
`
`Chapter 6 ~ Programming the RCX
`
`numbers. A variable is like a box with a nan
`1e written on ithou can pl
`ace some‘ '
`thing inside, a specific number—that is, you
`can assign a value to the variable. Or '
`you can watch what’s inside the box,
`reading the variable. At this Stage, you are
`neither assigning nor reading the vari
`ables, you are simply declaring that you
`need two of them. In other words, y
`ou are asking NQC to prepare two boxes
`with the names just mentioned.
`When the user presses the Run butto
`n on the RCX, the main task begins
`After it has completed initialization
`and calibration procedures, the program starts
`the robot in straight motion, then it
`enters an endless loop where the program
`continuously manages its tw
`0 tasks: removing obstacles and following t
`he line.
`The while(’true) statement
`repeats all the instructions delimited b
`y the open and
`close brace forever. in your
`case, it will execute t
`he Check_Bumper subroutine,
`then the Follow_line, then the Check‘Bumper
`again in a continuous loop that
`only the user can interrupt using the Run butt
`On.
`Everything is clear and simple,
`as it should be. Now let’s have a look
`happens at a lower level in our sub
`routines.
`Any program will typically include an. initialization
`section, where you set the
`motor power, configure tl
`1e sensors, reset timers and counters
`abl
`and initialize vari—
`es. This is not required when you use RCX
`Code, because it automatically
`configures the input ports for you. NQC,
`like the other textual environments,
`requires that you explicitly decl
`are what kind ofsensor you connect to each port:
`void Initialize ()
`(
`
`Se [Sens or ( SENSOR_1 , SENSOR_TOUCH)
`SetSensor (SENSOR_2 , SENSOR_LIGHT);
`
`l
`
`The word void is what tells NQC that you are describing
`a subroutine, and
`itls followed by the name you choose for itThe SetSensor
`statements are used
`to configure input port 1 for a touch sens
`or'and input port 2 for a light sensor.
`The ta/i'bmfio/z routine is designed to i
`nform your robot of the actual light
`readings it should expect on its path.We
`discussed this topic briefly in Chapter 4,
`explaining t
`hat keeping your program independent from particular cases is a good
`general programming practice. In this example, it means you should not write the
`light sensor threshol
`'
`'
`i
`the possibility to
`read them from the
`at you have declared thefloor and
`line variables for.
`
`
`
`."m’ifi‘i‘kfitfifiéfi’fiififii‘fiflim.-
`
` i:
`h,1,."5
`2%15'
`
`
`
`
`Mew-ire”:x
`
`
`
`
`
`.xteézmzmmsmmmxmsm.‘smfmflimimfi‘.
`:mawwzmzwnwarmgmw
`
`
`
`
`
`
`
`
`
`
`
`it - ....When you run the program, the calibration. procedure begins and informs
`r you with a beep that it waits for the first readingYou place your robot with the
`light sensor on the floor, far from the line, and push the bumper. The program
`‘
`,
`
`f-‘~;_rrcads the light sensor and stores that value as a typical “floor” value in thefloor
`‘vafiableThen it beeps again while waiting to re
`ad the line.You place the robot
`
`::".'V.V,ith the sensor
`just over the line and push the bumper again, making it detect
`{ff-V1.6 ‘p‘line” ligh
`t value and store it in the line variableThe robOt finally beeps
`
`gain, meaning the calibration process has finished and that the next push on the
`
`*bgtnper will put it in motion.
`
`_This sort ofpre-run phase is quite useful in many other situations, such as
`hen you need
`to prepare the robot for operations by either reading some envi—
`
`engtal variable or resetting mechanisms that might have been left in an
`'Wn state by previous executions.
`
`
`
`Programming the RCX - Chapter 6
`
`109
`
`void Calibrate()
`(
`
`WaitBumperPress();
`
`floor=SENSOR_2;
`
`waitBumperPress();
`
`line=SENSOR_2;
`
`WaitBumperPress();
`
`void Wait_Bumper_Press()
`
`{
`
`PlaySound(SOUND_DOUBLE_BEEP);
`
`while (SENSOR_1== );
`
`// wait for bumper press
`
`while (SENSOR_1==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 produces a beep and then waits until the bumper switch gets pressed
`and released.
`
`.
`
`
`
`
`
`
`
`110
`
`Chapter 6 ' Programming the RCX
`
`The Check_Bumper procedure is in charge of teSting whether. the robot
`has hit an obstacle, and ifso, how it should react:
`
`void Check_Bumper()
`(
`
`if (SENSOR_1==1)
`{
`
`StOp(l;
`
`Remove_0bstacle();
`
`Go_Straight();
`
`“.1
`
`It checks the bumper, and, if found closed, stops the robot, call5 the
`Remove_0bstacle subroutine to clear the path and then resumes motion.
`Testing the bumper is as simple as checking if SENSOR_1 has become equal to
`l, which means that the touch sensor connected to port 1 has been pressedYou
`notice that we apply here the same concepts used at the main level
`: encapsulating
`details into routines at a lower level.
`The Follow_Line routine is what keeps your roboc close to the line edge—
`let’s say the left edge. If the light sensors read too much of the “floor” v
`alue, it
`turns right toWard the line. If, on the contrary,
`it reads too much of the “line”
`value, it turns left,
`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>=1ins—SENSITIVITY)
`Turn_Left();
`else
`
`// reading too ”line"
`
`Go_Straigh:();
`
`The method used in this subroutine deserve
`5 some explanation. First of all, the
`word #define tells NQC that the following word denotes a constant; for the sake
`
`
`
`u
`
`
`
`
`
`
`
`Programming the RCX ' Chapter 6
`
`111
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`
`'
`
`_
`
`.2 void Go_Scraigh:()
`
`ofsimplicity, 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—
`stant SENSITIVITY with the value 5.This value is used together with thefloor
`and line 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 thefloor variable and the value 75 in the line variableT‘he program
`tesrs if SENSOR_1 is less than or equal tofloor + SENSITIVITY, which results in
`55 + 5 = 60, to decide if the robot has to turn right toward the line. Similarly; it
`tests if SENSOR_1 is greater than or equal to floor — SENSITIVITY, which cor—
`responds to 75 — S = 70, and if this is the case, it makes the robot turn left, away
`from the line. While the readings remain greater than 60 and lower than 70, the
`robOt goes straightYou can change the value of SENSITIVITY to make your
`robor 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 ofyour robot.
`The Go_Straight routine will be very straightforward in most cases.You
`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 (ifii'eiztt’al drive, in greater detail. For the moment, let’s stick to the facr
`that if both the motors go forward, the robot goes forward and Straight. [tone of
`"_-"-the motors stops, the robot turns toward the side ofthe stationary wheelThis
`' T"'knowledge is enough to write the following routines, which control mOtion:
`
`
`
`
`
`
`_"OfiFwd (OUT_A+OUT_C) ,-
`
`d Stopl)
`
`ff (OUT_A+0UT_C)
`
`l
`
`'yTurn_Le f t ( )
`
` jijWW'
`' 'v‘visiir'i " Fés‘fsécom’:
`
`
`
`
`
` Chapter 6 ' Programming the RCX
`
`Off(OUT_A);
`
`Oand(OUT_C);
`
`void Turn_Right ()
`rL
`
`Off(OUT_C)
`
`I
`
`
`
`
`
`
`
`
`
`
`SCCOH<
`
`needs
`ofthe
`
`Y(
`
`n1ade
`
`Ru
`
`AH d
`
`Inn/ff
`san1e
`
`well-
`
`I
`
`app:
`you:
`titas
`nlar
`
`
`
`
`
`
`
`afly
`the
`
`difl
`act
`
`n1c
`
`ca§
`
`th<
`CQ.‘
`
`
`
`
`
`
`
`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:
`
`Programming the RCX - Chapter 6
`
`113
`
`void Remove_0bstacle()
`(
`
`Oand(OUT_B) ;
`
`Wai: (200) ,-
`
`OnRev(OUT_B) ;
`
`Wait: (200) ;
`Off (our_a) ;
`
`The statement Wait(200) makes the program wait for 200 hundredths ofa
`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 ofa modular and well-Structured code.
`
`Running Independent Tasks
`All the tools you can choose from to program your RCX support some form of
`. 5 multitasking, 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
`‘ well—documented feature in all the alternative environments.
`Multitasking can be helpful in many situations and it’s often a tempting
`’ugpproach; but you should use it with a lot of care because it will not always make
`your. life. easier. Let’sgo back for a moment to our previous e
`sample: would mul—
`‘fitasking have been a good choice?
`Didn’t your robot have two different tasks to
`
`‘...-Ifi€lnage:
`line following and obstacle detection? Well, it did, but they were mutu—
`ally Exclusive—after all, your robot was noc following the line til/rile it removed
`thépbstacle In cases like this, and in many others,_your robot is asked to perform
`dlgétent activities one at. a nine more often than it is asked to perform different
`I
`aCtlvities at the SCII'I'IC’
`til-He. Using multitasking, you would have made your code
`more:rF_0mpleX, because ofthe additional instructions needed to synchronize the
`t-a$l<5-'.Wl1<ir1 the Remove_Obstacle task stops the robot, it should communicate
`th F9u0W_Line task to suspend line following, and communicate again when it
`be resumed.
`
`1
`1
`
`
`
`i
`l
`l
`‘
`i
`i
`l
`
`
`
`til2
`
`:.
`5'42».
`
`ammrremt—mmmamamrmes
`eréwmmasfimyémmwmfl
`
`5
`
`
`
`
`
`
`
`
`
`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 elem—driven scheme, which usually requires
`additional work to keep the processes coordinated.While 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 prac-
`rice 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 otherYou have to think in terms ofprz'm'in'cs: \X/hich dish
`should you put in the oven first? Programming independent tasks implies the
`same concernszYou must handle the situations where two tasks want to control
`the same motor or play two different soundsThe 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 makes 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