KEY SERIAL NUMBER Building Robots with LEGO MINDSTORMS Copyright © 2002 by Syngress Publishing, Inc.. It seemed an entire world of potential robotics fans had just been waiting for thisp
Trang 1Mario Ferrari Giulio Ferrari Ralph Hempel
Technical Editor
T h e U LT I M AT E To o l f o r M i n d s t o r m s M a n i a c s !
• Discover the Undocumented Secrets behind the Design
of the Mindstorms System
• Become Inspired by the Techniques of World-Class Mindstorms Masters
• Build a Competitive Edge for Your Next Mindstorms Robotic Competition
Trang 2s o l u t i o n s @ s y n g r e s s c o m
With more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Ciscostudy guides in print, we continue to look for ways we can better serve theinformation needs of our readers One way we do that is by listening
Readers like yourself have been telling us they want an Internet-based vice that would extend and enhance the value of our books Based onreader feedback and our own strategic plan, we have created a Web sitethat we hope will exceed your expectations
ser-Solutions@syngress.com is an interactive treasure trove of useful
infor-mation focusing on our book topics and related technologies The siteoffers the following features:
■ One-year warranty against content obsolescence due to vendorproduct upgrades You can access online updates for any affectedchapters
■ “Ask the Author” customer query forms that enable you to postquestions to our authors and editors
■ Exclusive monthly mailings in which our experts provide answers toreader queries and clear explanations of complex material
■ Regularly updated links to sites specially selected by our editors forreaders desiring additional reliable information on key topics
Best of all, the book you’re now holding is your key to this amazing site
Just go to www.syngress.com/solutions, and keep this book handy when
you register to verify your purchase
Thank you for giving us the opportunity to serve your needs And be sure
to let us know if there’s anything else we can do to help you get the maximum value from your investment We’re listening
www.syngress.com/solutions
Trang 4Mario Ferrari Giulio Ferrari Ralph Hempel Technical Editor
T h e U LTI MATE To o l fo r M I N D STO R M S M a n i a c s !
Building Robots
with
LEGO MINDSTORMS
®
Trang 5Syngress Publishing, Inc., the author(s), and any person or firm involved in the writing, editing, or
production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be obtained from the Work.
There is no guarantee of any kind, expressed or implied, regarding the Work or its contents.The Work is sold AS IS and WITHOUT WARRANTY You may have other legal rights, which vary from state to state.
In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.
You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files.
Syngress Media®, Syngress®, and “Career Advancement Through Skill Enhancement®,” are registered trademarks of Syngress Media, Inc “Ask the Author UPDATE™,” “Mission Critical™,”“Hack Proofing™,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Syngress Publishing, Inc Brands and product names mentioned in this book are trademarks or service marks of their respective companies.
KEY SERIAL NUMBER
Building Robots with LEGO MINDSTORMS
Copyright © 2002 by Syngress Publishing, Inc All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
Printed in the United States of America
1 2 3 4 5 6 7 8 9 0
ISBN: 1-928994-67-9
Technical Editor: Ralph Hempel Cover Designer: Michael Kavish
Co-Publisher: Richard Kristof Page Layout and Art by: Shannon Tozier
Acquisitions Editor: Catherine B Nolan Copy Editor: Michael McGee
Developmental Editor: Kate Glennon Indexer: Robert Saigh
Freelance Editorial Manager: Maribeth Corona-Evans
Distributed by Publishers Group West in the United States and Jaguar Book Group in Canada.
Trang 6However, the publication of Building Robots with LEGO MINDSTORMS entitles
me to a one-time exemption from our rule I am lucky enough to be the father ofnine-year-old Sam Williams, who has taught me (among many important things) thejoy of building with LEGO Since helping Sam put together his first bricks at twoyears old to programming our latest MINDSTORMS robot (the optimisticallynamed “Chore-Doer 3000”), I have derived hundreds of hours of pleasure creatingprojects with Sam Perhaps the most ingenious thing about LEGO products, particu-larly the MINDSTORMS, is that the same product can be as challenging and enjoy-able to a 43 year old as it is to a nine year old
When presented with the chance to publish Mario and Giulio Ferrari’s book, Ijumped at the opportunity As I read the manuscript, I could sense the authors hadthe same passion for creating with LEGO MINDSTORMS that Sam and I have Iknew immediately that there was a market of at least two people for the book!
I had the opportunity to meet Mario Ferrari at the Frankfurt Book Fair justweeks prior to this book’s publication I am American and Mario is Italian, but thelanguage we spoke was that of two parents who have discovered a common passion
to share with our nine and ten year old sons
I hope you enjoy reading this book as much as we have enjoyed publishing it
—Chris Williams President, Syngress Publishing
FPO
Trang 7Letters from the Authors
October 1998 It was a warm and sunny October and I remember it as if it was justyesterday Giovanni, a colleague of mine, returns home to Italy from his honeymoon
in New York He carries in the office an enormous blue box whose cover reads
“LEGO MINDSTORMS Robotics Invention System.”When Giovanni opens thebox and shows me the contents, I already know I must have one
Let me go back to the late 70s I was a high school student and had left my manyyears of LEGO play behind me I was enthusiastically entering the rising personalcomputing era Many of you are probably simply too young to remember that
period, but “using” a computer mainly meant programming it.The computers of that
time had few resources and rather primitive user interfaces; they were essentially massstorage devices, or something like a large unreliable cassette recorder.We program-mers had to count and save every single byte, and even the most trivial tasks werevery challenging But at the same time, of course, it was great fun!
I developed a very strong interest in computer programming, and in ArtificialIntelligence in particular Machines and mechanical devices had always fascinated me,and it came quite naturally to me to turn to robotics as an expansion of this interest.There were some relatively cheap and compact computing devices that could provide
a brain for my creatures, but unfortunately I discovered very soon all the technicalproblems involved in building the hardware of even a very simple robot.Where could
I find motors? Which were the right ones? Where could I learn how to controlthem? What kind of gearing did I need? Imagine spending months folding aluminumplates, mounting bearings, assembling electronic circuits, connecting wires… andassuming you’re able to do all those things, what do you get? A simple tin box thatcan run across the room and change direction when it hits an obstacle.The effort wasdefinitely far greater than the results Another problem was that constructing a newproject meant starting again from scratch, with new materials I wasn’t patient
enough, so I decided that a hobby in robotics was not for me
The dream of robotics remained a dream Until Giovanni opened that box As
soon as I got my hands on my first LEGO MINDSTORMS Robotics InventionSystem (RIS) set, it proved to be the fast and flexible robotics system that I waslooking for I found that the microcomputer, called the RCX, was very simple to usebut powerful enough to let me drive complex devices I became more and more
vi
Trang 8intrigued by this toy, and through the Internet I soon discovered that I was not alone
It seemed an entire world of potential robotics fans had just been waiting for thisproduct, and the LEGO company itself sold much more of them than expected.From that October on, many things happened: I discovered LUGNET, the fan-tastic LEGO Users Group Network, the best resource ever for LEGO fans of anykind I created a small Web site where I published pictures and information about
my robotic creatures.Through these channels every day I got in touch with newpeople, and with some of them friendships have sprung up that go beyond ourcommon interests in LEGO robotics.This is really the most special and valuablething MINDSTORMS have given to me: Good friends all over the world
—Mario Ferrari
October 1999 Another warm and sunny October, but on one particular day theMedia Lab at the Massachusetts Institute of Technology (MIT) in Cambridge, MAhas a different look One large room at the facility is filled with exhibition tableswith piles of colorful LEGO pieces and strange constructions on them and, there arehundreds of adults and children, LEGO bricks in hand, showing off their robotic cre-ations and discussing the characteristics of their favorites.This is the world’s biggestgathering of LEGO MINDSTORMS fans—the Mindfest!
When and how did all this start? It seems only yesterday to me, but a year hadpassed since I discovered MINDSTORMS for the first time My brother Mariocalled me on the phone one evening, knowing I was about to leave on a short trip toNew York, and asked me to bring him home a new product from LEGO, a sort of aprogrammable brick that could be controlled via a standard computer I have to saythat I was very curious, but nothing more: I thought it might be a great new toy toplay around with, but I didn’t completely understand its possibilities.When I saw theRobotics Invention System (RIS) in the toy store, though, I immediately realizedhow great it could be, and that I must have one, too My own addiction to theLEGO MINDSTORMS began in that moment
Like nearly everyone under the age of 40, I’d built projects from the manyLEGO theme kits in my childhood I had the advantage of using the large quantity
of bricks that my older brothers and sisters had accumulated during the years, plussome new pieces and sets of the 80s Castles, pirates, trains… hours and hours of pure
Trang 9fun, creating a large number of any kind of building and adventures.When I was alittle older, I discovered the TECHNIC series, a wonderful world of machines, gears,mechanical tools, and vehicles, with endless construction possibilities.Then, like manyother people, I abandoned LEGO as a young adult, and it remained out of my life—until I bought that big blue box in New York that day
Why do I like LEGO MINDSTORMS so much? For me, it is mainly because itrequires different skills and combines different disciplines: computer programming,robotics, and hands-on construction.You have to combine theory and practice, and tocoordinate the design, construction, software, and testing processes.You can exerciseyour creativity and your imagination, and you have a great tool for doing this—atool that is at the same time easy to use and very powerful, and most important, thatdoesn’t limit your ideas
And there’s even more to the rewards of MINDSTORMS than that Let’s goback to Mindfest for a moment.Why would such an extraordinary group of people
of different ages, cultures, and nationalities travel from all over the world to spend anentire weekend playing with LEGO? What exactly do they have in common? Why
do some of the most famous Artificial Intelligence experts seriously discuss every ture of this product? There must be something really special about this “toy.”
fea-Joining an international community is one of the best things about playing withLEGO It is not only a toy, but also a way of thinking and living Just play with theMINDSTORMS for a while—you’ll see for yourself!
—Giulio Ferrari
Trang 10Author Acknowledgements
We would first like to thank Brian Bagnall for suggesting our names to SyngressPublishing when he heard Syngress was looking for an author to write a bookfocused on ideas and techniques for building MINDSTORMS robots.We are verygrateful to Syngress Publishing for having turned this suggestion into a real opportu-nity, and for having allowed us the great freedom of deciding the shape and content
of the book
Additional appreciation goes to Jonathan Knudsen, who encouraged us inembarking upon the adventure of writing a book, and who helped us in under-standing the world of technical publishing Another friend, Guido Truffelli, patientlyread every page of the manuscript Many thanks, Guido—your comments and sug-gestions were very valuable in making the book more complete and more useful.When Ralph Hempel accepted the offer to perform the technical edit of thebook, we were really excited Ralph’s contributions to MINDSTORMS robotics areimpressive, and range from mechanical solutions to extreme programming Hisinvolvement proved to be even more significant that we had even imagined
This was our first authoring experience, and all the Syngress staff has beenincredibly patient with us and very supportive A very special thank you goes to KateGlennon, our Developmental Editor, for having taught us how to transform a collec-tion of concepts and ideas into a book Mario wants to also thank his employer,EDIS, which granted him the time to focus more attention on the book
This book would have not been written without the contributions of the entireLUGNET MINDSTORMS Robotics community Its members are incredibly cre-ative, competent, helpful, and friendly, and they are always willing to share ideas andsolutions with other people.We have attempted to give proper credit to all thepeople whose ideas we mentioned in the book, and we apologize in advance forthose people who have been unintentionally left out
Last but not least, we’d like to express enormous gratitude to our families, whoencouraged and supported us through every moment of these intense months ofwriting
Trang 11Syngress Acknowledgements
We would like to acknowledge the following people for their kindness and support
in making this book possible
Richard Kristof and Duncan Anderson of Global Knowledge, for their generousaccess to the IT industry’s best courses, instructors, and training facilities
Karen Cross, Lance Tilford, Meaghan Cunningham, Kim Wylie, Harry Kirchner,Kevin Votel, Kent Anderson, and Frida Yara of Publishers Group West for sharingtheir incredible marketing experience and expertise
Mary Ging, Caroline Hird, Simon Beale, Caroline Wheeler,Victoria Fuller, JonathanBunkell, and Klaus Beran of Harcourt International for making certain that ourvision remains worldwide in scope
Anneke Baeten and Annabel Dent of Harcourt Australia for all their help
David Buckland,Wendi Wong, Daniel Loh, Marie Chieng, Lucy Chong, Leslie Lim,Audrey Gan, and Joseph Chan of Transquest Publishers for the enthusiasm withwhich they receive our books
Kwon Sung June at Acorn Publishing for his support
Ethan Atkin at Cranbury International for his help in expanding the Syngress
program
A special thanks to Sam Williams, who comes to the office every week with a
backpack full of LEGOs.Watching the look on his face when he opens a new kit is ajoyous event
Trang 12Modena, Italy, where he lives with his wife Anna and his childrenSebastiano and Camilla.
Giulio Ferrariis a student in Economics at the University of Modenaand Reggio Emilia, where he also studied Engineering He is fond ofcomputers and has developed utilities, entertainment software, and Webapplications for several companies Giulio discovered robotics in 1998,with the arrival of MINDSTORMS, and held an important place in thecreation of the Italian LEGO community He shares a love for LEGObricks with his oldest brother Mario, and a strong curiosity for the phys-ical and mathematical sciences Giulio also has a collection of 1200 dice,including odd-faced dice and game dice He studies, works, and lives inModena, Italy
Trang 13Technical Editor
Ralph Hempel(BASc.EE, P.Eng) is an Independent Embedded SystemsConsultant He provides systems design services, training, and program-ming to clients across North America His specialty is in deeply
embedded microcontroller applications, which include alarm systems,automotive controls, and the LEGO RCX system Ralph providestraining and mentoring for software development teams that are new toembedded systems and need an in-depth review of the unique require-ments of this type of programming Ralph holds a degree in ElectricalEngineering from the University of Waterloo and is a member of theOntario Society of Professional Engineers He lives in Owen Sound,Ontario with his family, Christine, Owen, Eric, and Graham
Trang 14Summary 15
Chapter 2 Playing with Gears 17
Introduction 18
Riding That Train:The Geartrain 21Worming Your Way:The Worm Gear 23Limiting Strength with the Clutch Gear 24Placing and Fitting Gears 26Using Pulleys, Belts, and Chains 31
Chains 35Making a Difference:The Differential 36Summary 39
Learn about Lego Gears
Trang 15xiv Contents
Chapter 3 Controlling Motors 41
Introduction 42Pacing,Trotting, and Galloping 43
Putting It All Together: Chassis, Modularity,
Summary 94
Explore LEGO Sensors
LEGO sensors come in two
families: active and
passive sensors Passive
simply means they don't
require any electric supply
to work The touch and
temperature sensors
belong to the passive
class, while the light and
rotation sensors are
members of the active
class.
Trang 16Contents xv
Chapter 6 Programming the RCX 97
Introduction 98
A Small Family of Programmable Bricks 100
Using the NQC Language 102Using Other Programming Languages 103
Summary 124
Chapter 8 Becoming Mobile 127
Introduction 128Building a Simple Differential Drive 128Keeping a Straight Path 130Using Sensors to Go Straight 130Using Gears to Go Straight 131Using Casters to Go Straight 134Building a Dual Differential Drive 136Building a Skid-Steer Drive 138Building a Steering Drive 140Building a Tricycle Drive 144Building a Synchro Drive 146
Understand the Benefits of Designing Modular Code
■ Readability
■ Reusability
■ Testability
Trang 17Introducing Some Specialized Components 155Buying Additional Parts 161Creating Custom Components 163Building Custom Sensors 164Solving Port Limitations 170Creative Solutions When
More RCX Ports Are Needed 172Summary 177
Chapter 10 Getting Pumped: Pneumatics 179
Introduction 180Recalling Some Basic Science 180
Controlling the Airflow 187Building Air Compressors 190Building a Pneumatic Engine 194Summary 198
Chapter 11 Finding and Grabbing Objects 199
Introduction 200Operating Hands and Grabbers 200Transferring Motion Using Tubing 203Understanding Degrees of Freedom 205
Summary 212
Chapter 12 Doing the Math 213
Introduction 214Multiplying and Dividing 215
Explore extra parts,
custom sensors, and tricks
for using the same motor
for more than one task:
■ Extra parts come from
either sets or service
packs
■ Custom sensors are a
new frontier, and
reveal a whole new
world of possibilities
■ Mechanical tricks
enable you to use the
same motor to power
multiple mechanisms.
Trang 18Contents xvii
Understanding Hysteresis 229Summary 232
Chapter 13 Knowing Where You Are 233
Introduction 234Choosing Internal or External Guidance 234Looking for Landmarks: Absolute Positioning 236
Measuring Movement: Relative Positioning 243Summary 246
Part II Projects 247 Chapter 14 Classic Projects 249
Trang 19xviii Contents
Chapter 16 Unconventional Vehicles 311
Introduction 312Creating Your Own SHRIMP 312
Creating Other Vehicles 328Elevator 328Train 328Cable Railway or Gondola 329Boat 329
Chapter 18 Replicating Renowned Droids 349
Introduction 350Building an R2-D2-Style Droid 350Programming the Droid 356Variations on the Construction 359Building a Johnny Five-Style Droid 361Variations on the Construction 366Summary 368
Chapter 19 Solving a Maze 371
Introduction 372
Using the Left Side—Right Side Strategy 374Applying Other Strategies 376
Use Angle Connectors
There are currently six
types of angle connectors
in the LEGO line,
numbered 1 to 6 In case
you’re wondering how the
numbers relate to angles,
here are the
Trang 20Contents xix
Building a Maze Runner 377Constructing the Maze Runner 377Programming the Runner 380
Variations on the Maze Runner 381Building a Maze Solver 382Constructing the Maze Solver 383Programming the Solver 387Summary 389
Chapter 20 Board Games 391
Introduction 392
Building the Hardware 393
Improving Your Game 396
Building a Visual Interface 397Building a Mechanical Interface 400Connecting and Programming
Variations on the Construction 408Playing Other Board Games 409Summary 410
Chapter 21 Playing Musical Instruments 411
Introduction 412
Building the Drummer 413Programming the Drummer 416Variations 417
Building the Pianist 417Programming the Pianist 422Changes and Improvements 423
to withstand the forces involved in the
performance