490

The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 2: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 3: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

quickbuildingreferencechart

Page 4: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK

Page 5: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK

abeginner’sguidetobuildingandprogrammingrobots

laurensvalk

Page 6: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK.Copyright©2010byLaurensValk.

Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.

Page 7: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Fifthprinting

14131256789

ISBN-10:1-59327-211-1ISBN-13:978-1-59327211-1

Publisher:WilliamPollockProductionEditor:RileyHoffmanCoverandInteriorDesign:OctopodStudiosCoverPhotograph:JochemdeKlerkTechnicalReviewers:DamienKee,MartijnBoogaarts,andRichardLiCopyeditor:KimWimpsettCompositor:RileyHoffmanProofreaders:NancySixsmithandXanderSoldaatIndexer:ValerieHaynesPerry

Forinformationonbookdistributorsortranslations,pleasecontactNoStarchPress,Inc.directly:NoStarchPress,Inc.38RingoldStreet,SanFrancisco,CA94103phone:415.863.9900;fax:415.863.9950;[email protected];www.nostarch.com

LibraryofCongressCataloging-in-PublicationDataValk,Laurens.TheLEGOMindstormsNXT2.0discoverybook:abeginner’sguidetobuildingandprogrammingrobots/LaurensValk.p.cm.Includesindex.ISBN-13:978-1-59327211-1ISBN-10:1-59327-211-11.Robots--Designandconstruction--Popularworks.2.Robots--Programming--Popularworks.3.LEGOtoys.I.Title.TJ211.15.V3532010629.8’92--dc222010011157

NoStarchPressandtheNoStarchPresslogoareregisteredtrademarksofNo

Page 8: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

StarchPress,Inc.Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespectiveowners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weareusingthenamesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementofthetrademark.LEGO®,MINDSTORMS®,thebrickconfiguration,andtheminifigurearetrademarksoftheLEGOGroup,whichdoesnotsponsor,authorize,orendorsethisbook.Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthiswork,neithertheauthornorNoStarchPress,Inc.shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.

Page 9: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

abouttheauthor

LaurensValkisamemberoftheMINDSTORMSCommunityPartners(MCP),agroupofMINDSTORMSenthusiastswhohelptestanddevelopnewNXTproducts.HehasbeeninventingrobotswiththeMINDSTORMSNXTsetssincetheirintroduction.LaurensenjoysdesigningrobotsthatcanbebuiltwithjustoneNXTset,makingiteasyforMINDSTORMSfansworldwidetofollowhisbuildinginstructions.Oneofhisrobotdesigns,Manty,appearsonthebackoftheNXT2.0set’sboxasabonusrobot.HeisacoauthorofLEGOMINDSTORMSNXTOne-KitWonders(NoStarchPress)andacontributortoTheUnofficialLEGOMINDSTORMSNXT2.0Inventor’sGuide(NoStarchPress).He’salsoacontributortothepopularNXTSTEPblog(http://thenxtstep.blogspot.com/).LaurenslivesintheNetherlands,wherehestudiesMechanicalEngineeringatDelftUniversityofTechnology,andhemaintainshiswebsiteaboutroboticsathttp://www.laurensvalk.com/.

Page 10: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

aboutthetechnicalreviewer

Dr.DamienKeeholdsaPhDinroboticsandabachelor’sdegreeinelectricalengineering,bothfromtheUniversityofQueensland,Australia.Hehasbuiltawidevarietyofrobots,frommaze-solvingmicetohumanoidstorobotsthatdispensetrafficcones.DamienhasbeenheavilyinvolvedwiththeRoboCupJuniorcompetitionsince2001,andin2009hewaselectedchairmanofRoboCupJuniorAustraliaandtechnicalchairoftheRoboCupJuniorInternationalRescueCommittee.Since2003,Damienhasbeenconductingroboticsworkshopsforteachers,educators,andstudentsworldwide,andhehaswrittenseveralteacherresourcebooks.HeisamemberoftheMINDSTORMSCommunityPartners;acontributortotheNXTSTEPblog;andeditorinchiefofTheNXTClassroom(http://theNXTclassroom.com/),awebsiteprovidingresourcesandsupportforteachers.

Page 11: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

briefcontents

acknowledgments

introduction

partIgettingstartedchapter1collectingtheequipmentforyourrobot

chapter2buildingyourfirstrobot

chapter3creatingandmodifyingprograms

chapter4workingwithprogrammingblocks:move,sound,anddisplay

chapter5waiting,repeating,andotherprogrammingtechniques

partIIbuildingandprogrammingrobotswithsensorschapter6understandingsensors

chapter7usingthetouch,color,androtationsensors

chapter8shot-roller:aroboticdefensesystem

chapter9strider:thesix-leggedwalkingcreature

partIIIcreatingadvancedprogramschapter10usingdatahubsanddatawires

Page 12: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

chapter11usingdatablocksandusingdatawireswithloopsandswitches

chapter12usingvariables,constants,andplayinggamesontheNXT

partIVadvancedrobotprojectschapter13snatcher:theautonomousroboticarm

chapter14hybridbricksorter:sortbricksbycolorandsize

chapter15CCC:thecompactchimneyclimber

appendixtroubleshootingandsolvingconnectionproblems

index

Page 13: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

contentsindetail

acknowledgments

introductionwhythisbook?isthisbookforyou?howdoesthisbookwork?

thediscoverieswhattoexpectineachchapter

gettinghelp:thecompanionwebsiteconclusion

PARTIGETTINGSTARTED1collectingtheequipmentforyourrobotwhat’sinthebox

theNXTbricktheNXT-Gprogrammingsoftwarethetestpad

insertingbatteriesconclusion

2buildingyourfirstrobotbuildingtheexplorer

buildingtip:beamsandaxlesbuildingtip:frictionandnonfrictionpinsconnectingthecables

usingtheNXTbuttonstonavigateontheNXTbrick

Page 14: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

turningonthebrickselectingandchoosingitemsturningoffthebrickrunningaprogram

conclusion

3creatingandmodifyingprogramsaquickfirstprogramcreatingabasicprogram

1.programmingpalette2.workarea3.startarea4.NXTcontroller

workingwiththeNXT-Gsoftware5.configurationpanel6.littlehelpwindow7.programnavigationbar8.toolbar9.robocenter

controllingtherobotremotelyconclusion

4workingwithprogrammingblocks:move,sound,anddisplaywhatdoprogrammingblocksdo?

usingblockstocreateprogramsusingdifferentprogrammingblocks

themoveblockseeingthemoveblockinactionunderstandingtheconfigurationpanel

Discovery#1:Accelerate!understandingtheconfigurationiconsmakingaccurateturns

Page 15: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery#2:LookingBack!Discovery#3:MoveThat’Bot!Discovery#4:RoboSpeller!

thesoundblockunderstandingthesoundblockconfigurationsseeingthesoundblockinaction

Discovery#5:WhichDirectionDidYouSay?!Discovery#6:BetheDJ!

thedisplayblockunderstandingthedisplayblockconfigurationsseeingthedisplayblockinaction

furtherexplorationDiscovery#7:Subtitles!Discovery#8:Navigator!Discovery#9:CircleTime!Discovery#10:W8fortheExplorer!Discovery#11:RoboDancer!BuildingDiscovery#1:ExploringArt!

5waiting,repeating,andotherprogrammingtechniquesthewaitblock

understandingthewaitblocksettingsseeingthewaitblockinaction

Discovery#12:CountDown!moreonthemoveblock:movingunlimited

theunlimitedoptionthedurationunlimitedsettinginactionproblemswithmovingunlimited

theloopblockusingtheloopblockunderstandingtheloopblocksettingsseeingtheloopblockinaction

Discovery#13:GuardtheRoom!

Page 16: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery#14:Triangle!usingloopblockswithinloopblocks

makingyourownblocks:themyblockcreatingmyblocksusingmyblocksinprograms

Discovery#15:MyTriangle!Discovery#16:MyTune!

editingmyblocksparallelsequencesofblocks

usingparallelsequencesinaprogramDiscovery#17:Let’sMultitask!Discovery#18:ComplexFigures!BuildingDiscovery#2:Mr.Explorer!

furtherexploration

PARTIIBUILDINGANDPROGRAMMINGROBOTSWITHSENSORS6understandingsensorswhataresensors?

understandingthesensorsintheNXT2.0kitDiscovery#19:MindYourHead!

understandingtheultrasonicsensorcreatingtheultrasonicsensorattachmentpollingsensors

programmingwithsensorssensorsandthewaitblock

Discovery#20:HelloandGoodbye!sensorsandtheloopblock

Discovery#21:AvoidWallsandaBadMood!Discovery#22:FollowMe!

Page 17: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery#23:HappyTunes!sensorsandtheswitchblock

Discovery#24:SeetheDistance!Discovery#25:StoporTurn?Discovery#26:IntruderAlarm!Discovery#27:Ultrasound!BuildingDiscovery#3:RailroadCrossing!

furtherexploration

7usingthetouch,color,androtationsensorsthetouchsensor

creatingthebumperattachmentwithtouchsensorsprogrammingwiththetouchsensoravoidingwallswithtouchsensors

Discovery#28:OnlyTwoIsEnough!Discovery#29:SmartDecisions!

thecolorsensorcreatingthecolorsensorattachmentusingtheviewmodetopollthecolorsensorprogrammingwiththecolorsensor

BuildingDiscovery#4:CleanThatTestPad!Discovery#30:TellMeWhatYouSee!Discovery#31:ExpertLineFollowing!Discovery#32:WhichButtonDidYouPress?!Discovery#33:SoundBot!

usingtheNXTbuttonsassensorstherotationsensors

usingtheviewmodetopolltherotationsensormakingprogramswithrotationsensors

Discovery#34:CirclingDegrees!Discovery#35:RotationalMusic!

furtherexplorationDiscovery#36:ColortheBall!

Page 18: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery#37:UltrasonicLineFollowing!BuildingDiscovery#5:AutomaticHouse!

8shot-roller:aroboticdefensesystembuildingtheshot-roller

connectingthecablesprogrammingtheshot-roller

thecompletepalettethecolorlampblock

Discovery#38:AColoredVoice!themotorblock

Discovery#39:AMotorBlockTask!autonomousmodelightsensormode

Discovery#40:DangerousIntruderAlarm!remote-controlmode

Discovery#41:CombiningSensorPower!furtherexploration

Discovery#42:ResearchwiththeNXT!BuildingDiscovery#6:LookBeforeYouShoot!BuildingDiscovery#7:Catapult!

9strider:thesix-leggedwalkingcreaturebuildingstrider

connectingthesensorcablesunderstandingstrider’swalkingtechniqueprogrammingstrider

creatingthewalk-forwardmyblockcreatingthewalk-leftandwalk-rightmyblocksusingthemyblocksinaninteractiveprogram

Discovery#43:TriangleTime,Again!Discovery#44:WalkinginSixDirections!

Page 19: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingthescaredstriderprogramfurtherexploration

Discovery#45:WalkingattheSpeedofLight!BuildingDiscovery#8:TiredofWalking?!Discovery#46:RemoteControl!BuildingDiscovery#9:APairofEyesintheBack!

PARTIIICREATINGADVANCEDPROGRAMS10usingdatahubsanddatawiresbuildingSmartBotaprogramtogetstartedwithdatawires

understandingthesampleprogramhowdodatahubsanddatawireswork?

creatingasecondexampleprogramwithdatawiresanddatahubsusingdataplugs:inputandoutputblockconfigurationswhenusingdatawiresdeletingdatawires

Discovery#47:GrowingCircles!Discovery#48:DynamicSpeed!Discovery#49:MotorInput!

sensorblocksconfiguringasensorblockconfiguringatouchsensorblockconfiguringacolorsensorblockconfiguringarotationsensorblock

datawiretypesthenumberdatawirethelogicdatawire

Discovery#50:TouchSensorWires!

Page 20: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

thetextdatawireDiscovery#51:ReadtheSensorReadings!

thebrokendatawiremultipledatawireconnections

connectingmultiplewirestodifferentplugsconnectingmultiplewirestoonedataplugusingsettingswithbothinputandoutputplugs

Discovery#52:MultifunctionalWires!usinghelpfordataplugs

tipsformanagingdatawireshidingunuseddataplugsusingdatawiresacrossyourprogram

Discovery#53:LookingforHelp!Discovery#54:TurnUptheVolume!Discovery#55:ControltheThrottle!Discovery#56:SmartBotIsWatchingYou!BuildingDiscovery#10:APoliteSmartBot!

furtherexploration

11usingdatablocksandusingdatawireswithloopsandswitchesdatablocks

themathblockDiscovery#57:MathPractice!Discovery#58:RandomSound!

therandomblockthecompareblockthelogicblock

switchblocksanddatawiresDiscovery#59:And,Or,XOr,orNot?Discovery#60:TotalorElse!

configuringswitchblockswithdatawiresusingnumberandtextdatawiresandswitchblocksconnectingdatawirestoinsideswitchblocks

Page 21: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

loopblocksanddatawiresDiscovery#61:PressAnyKeytoContinue!Discovery#62:ArithmeticRotations!BuildingDiscovery#11:BionicHand!

furtherexploration

12usingvariables,constants,andplayinggamesontheNXTusingvariables

definingavariableusingthevariableblockcreatingaprogramwithavariable

Discovery#63:Oldvs.New!Discovery#64:SmarterCountProgram!

usingconstantsusingtheconstantblockcreatingaprogramwithconstants

playingagameontheNXTdefiningthevariablesstep1:displayingatargetrandomlystep2:waitinguntilabuttonispressedstep3:storingwhichbuttonispressedstep4:comparingthepositionandbuttonvariablesstep5:adjustingthescorestep6:displayingthecurrentscorestep7:makingtheprogramrepeatfor30secondsexpandingtheprogram

Discovery#65:Smart-GameProgramAdvanced!Discovery#66:BrainTrainer!BuildingDiscovery#12:Whack-a-Mole!

furtherexploration

Page 22: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PARTIVADVANCEDROBOTPROJECTS13snatcher:theautonomousroboticarmunderstandingthegrabber

thegrabbingmechanismtheliftingmechanism

buildingthesnatchercreatingobjectsprogrammingthesnatcher

creatingthemyblockscreatingthefinalprogramtroubleshootingthesnatcher

furtherexplorationDiscovery#67:IDon’tLikeBlue!Discovery#68:LightinaCorner!BuildingDiscovery#13:TabletopCleaner!

14hybridbricksorter:sortbricksbycolorandsizeunderstandingthesortingtechnique

thedrivingmodulethescanningmoduleidentifyingabrick’ssize

buildingthehybridbricksorterconnectingthecablesfindingbrickstousewithyoursorterfindingbuckets

programmingthehybridbricksortercreatingthemyblockscreatingthefinalprogram

Discovery#69:High-SpeedSorting!Discovery#70:QuatroBrickSorter!Discovery#71:IntelligentSorting!

Page 23: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

BuildingDiscovery#14:HybridBrickShooter!furtherexploration

15CCC:thecompactchimneyclimberunderstandingtheclimbingtechnique

stayingbalancedonthex-axisbalancingonthey-axis

buildingthecompactchimneyclimberpreparingachimneyprogrammingthecompactchimneyclimber

step1:extendingthearmsstep2:climbingandstayingbalancedstep3:goingdown,stayingbalanced,andstoppingtroubleshootingtheCCC

furtherexplorationDiscovery#72:Altimeter!BuildingDiscovery#15:AerialTram!

appendixtroubleshootingandsolvingconnectionproblemsusingtheNXTcontrollertodownloadprogramstotheNXT

usingtheNXTwindowproblemsconnectingtoanNXTwithUSBproblemsdownloadingprogramstotheNXT

usingBluetoothtodownloadprogramstotheNXTfindingaBluetoothdongleconnectingtotheNXTwithBluetoothproblemsconnectingtoanNXTwithBluetooth

conclusion

index

Page 24: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

acknowledgments

Thebookyouholdinyourhandsistheresultofmorethanayearofhardwork,andIwouldneverhavecompletedwritingitwithoutthehelpofmanyothers.First,I’dliketothankFayRhodesandJimKellyforintroducingmetobookwriting.IfIhadn’thadtheopportunitytocoauthorLEGOMINDSTORMSNXTOne-KitWonderswiththemin2008,Imightneverhaveconsideredwritingmyownbook,especiallyinalanguagethatisnotmynativetongue.

Next,I’dliketothanktheLDrawcommunityfordevelopingmanytoolsrequiredtomakeclearbuildinginstructions,especiallyPhilippeHurbainformakingdetailed3DdrawingsoftheNXTsetcomponents;TravisCobbsfordevelopingLDViewtovisualizethebuildingsteps;andKevinClaguefordevelopingLPUB4,whichallowedmetoorganizemybuildinginstructionsinawaythatwouldmakethemeasytofollow.ThankstootoJohnHansenforlettingmeusehistooltotakescreenshotsoftheNXTdisplay.

Thanksalsotoallwhohavebeendirectlyinvolvedinthisbook:RichardLiandMartijnBoogaartsforcarefullytestingmyrobotsandtheirbuildinginstructions;JochemdeKlerkfortakingthecoverphotograph;MicahEdelblutfortakingthephotographsusedinFigure9-4,Figure10-1,andFigure10-16;myparentsfortheiradviceonhowtomanageworkingonthisbook;andXanderSoldaatforproofreadingthebookfortechnicalaccuracy.SpecialthanksgototechnicaleditorDamienKeeforreadingallofthechaptersearlyontomakesuretheywereunderstandableandclear.

Further,manythanksgotothepeopleatNoStarchPress,whohavebeenwonderfulcolleaguesinthepastyear.IespeciallythankWilliamPollockforconvertingthetextinthisbookintoclearandsmoothEnglishandforhisconstructivecriticismtomakeeverysectioninthisbookusefulandworthreading.IalsothankRileyHoffmanformanagingthisprojectandformakingallthepagesinthisbooklookasgoodastheydo.

ThankstoeveryoneelsewhosupportedmewhileIworkedonthisbook.MyfriendsandtheNXTbuilderseagerlyawaitingthepublicationofthisbookencouragedmetocompletethisbookandkeptmegoinguntilitwasfinished.

Finally,thankstotheLEGOcompanyforLEGOMINDSTORMSNXT,thewonderfulproductonwhichthisbookisbased.NotonlyistheNXTfuntoplaywith,butitbringspeopleallovertheworldtogetherwhootherwisemight

Page 25: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

neverhavemet.

Page 26: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

introduction

YouprobablyalreadyknowthatLEGOMINDSTORMSNXT2.0isaroboticskitthatletsyoubuildandprogramyourownrobots.IfirstbecameinvolvedwithMINDSTORMSin2005whenIwas13yearsold.BackthenIhadjustenoughmoneytobuyaMINDSTORMSRoboticsInventionSystem,theversionavailableatthattime.Thusbeganmynewhobby,andastimepassed,IbecamemoreandmoreinvolvedintheworldofMINDSTORMS.Theresultisthebookyou’reholding(publishedin2010).ItspurposeistohelpyouexplorethepossibilitieswithMINDSTORMSinhopesthatyou’llhavejustasmuchfunwiththisroboticskitasIhave.

whythisbook?TheLEGOMINDSTORMSNXT2.0roboticskitincludesnumerouspartsandplansforfourrobotsthatyouprogramusingacomputer.Ithinkyou’llfindthatit’salotoffuntobuildandprogramtherobots,butthegoingcanbeabitroughwhenyou’rejustgettingstarted.Thekitprovidesyouwiththetoolsyouneedtomaketherobotswork,butthekit’suserguidecoversonlyafractionofwhatyouneedtoknowtobuildandprogramyourownrobots.

ThisbookisdesignedasaguidebooktohelpyoudiscoverthepoweroftheLEGOMINDSTORMSNXT2.0roboticskit;you’lllearntheskillsyou’llneedtomakeyourrobotsreallydowhatyouwantthemtodo.Inotherwords,withthisbook,yourroboticskitwon’tendupgatheringdustontheshelf!

isthisbookforyou?ThisbookassumesnopreviousexperiencewitheitherbuildingorprogrammingLEGOMINDSTORMS.Asyouread,you’llmovefrombasictoadvancedprogrammingandbuildincreasinglysophisticatedrobots.NewusersshouldbegininChapter1andthenfollowthestep-by-stepinstructionsinChapter2to

Page 27: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

buildandprogramabasicrobot,whilemoreexperiencedMINDSTORMSusersmightsimplystartwithachaptertheyfindchallengingandmoveonfromthere.TheadvancedprogrammingsectioninPartIIIandtherobotdesignsinPartIVwillbeespeciallyinterestingformoreadvancedreaders.

howdoesthisbookwork?Althoughyoucoulduseitassuch,thisbookisn’tintendedasareferencemanual;it’smorelikeaworkbook.I’vemixedtogetherbuilding,programming,androboticchallengestoavoidlong,theoreticalchaptersthatcanbehardtowadethrough.Forexample,you’lllearnbasicprogrammingtechniquesatthesametimethatyoulearntomakeyourfirstrobotmove,butyou’lllearnaboutsensorsasyoubuildanewrobot.ThereasonforthisapproachisthatIthinkthatdoingisthebestwaytolearnhowtobuildandprogramMINDSTORMSrobots.

thediscoveriesAsyoulearntoprogramyourrobotsandasyoubuildtherobotsinthisbook,you’llnoticemany“Discovery”sectionsthroughoutthechapters.Eachnewprogrammingtechniqueissupportedwithexamplesandthesediscoveries.Iencourageyoutotrythediscoveriesandnotjusttakewhat’swrittenforgranted.

Thisbookincludes72programmingdiscoveriestohelpyoubuildyourprogrammingskillsand15buildingdiscoveries,showingyouhowtofurtherexpandonthebook’srobotdesignsandgetyoustartedcreatingyourownoriginalrobots.Ifyouhavetroublewithanyofthediscoveries,visitthebook’scompanionwebsite(http://www.discovery.laurensvalk.com/)toaskquestionsortoshareyourexperiences.

whattoexpectineachchapterThebookissplitintofourparts.Here’sabriefoverviewofeachpart.Someofthetermsusedheremaybenewtoyou,butyou’lllearnthemasyoureadthebook.

partI:gettingstarted

Page 28: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PartIbeginsbytakingyouthroughthepiecesintheNXT2.0roboticskitinChapter1.InChapter2,you’llbuildyourfirstrobotandlearnabouttheNXT(oftenreferredtoastheNXTbrick).InChapter3,you’llmeetNXT-G,thesoftwareincludedintheNXT2.0roboticskit,whichyou’llusetoprogramrobots.InChapter4,you’lluseNXT-Gtomakeyourrobotmoveasyoucreateyourfirstprogramswithbasicprogrammingblocks.Finally,inChapter5,you’lllearnprogrammingtechniquessuchasrepeatingandhowtomakeyourrobotdomorethanonethingatthesametime.

partII:buildingandprogrammingrobotswithsensors

Thispartteachesyouallaboutsensors,anessentialaspectofMINDSTORMSrobots.InChapter6,you’llbeginbyaddingasensortotherobotthatyoubuiltinPartIinordertoexpanditscapabilitieswhileyoulearntheprogrammingtechniquesrequiredtousesensors.InChapter7,you’lllearnabouttheothersensorsintheNXT2.0roboticskit,andinChapter8,you’llbuildtheShot-Roller,aroboticdefensesystem,whilelearningaboutseveralnewprogrammingblocks.Chapter9willdigdeeperintosensorsasyoubuildandprogramStrider,asix-leggedcreaturethatwalksaroundandinteractswithitsenvironment.

partIII:creatingadvancedprogramsPartIIIisdevotedtoadvancedprogrammingconcepts.Hereiswhereyou’lllearnhowtomakeyourrobotsperformcomplexactions.InChapter10,you’lllearnaboutdatahubsanddatawireswhileyoubuildSmartBot,aplatformfortestingadvancedprograms.Then,inChapter11,you’llusedatawirestocontroldataprogrammingblockswhileyoulearnsomeotheradvancedprogrammingtricks.Finally,Chapter12willteachyouhowtousevariablesandconstantsandhowtocombinealloftheprogrammingtechniquesyou’velearneduptothispointtoplayagameontheNXT.

partIV:advancedrobotprojectsHavinglearnedabouttheNXT2.0roboticskit,motors,andsensors,aswellashowtoprogramyourrobots,thislastpartwillhaveyoucombineallofyournewlylearnedskillsasyoucreatethreenewrobots.InChapter13,you’llbuild

Page 29: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

andprogramtheSnatcher,anautonomousroboticarmthatcanfind,grab,andliftobjects.InChapter14,you’llbuildtheHybridBrickSorter,amachinethatsortsLEGObricksbycolorandsize.Finally,inChapter15,you’llbuildCCC,averticalclimberthatbalancesasitmoves.

gettinghelp:thecompanionwebsite

Theinstructionsandexplanationsinthisbookhavebeentestedandreviewedextensively,butyoumaystillhavequestions.Onthecompanionwebsite(http://www.discovery.laurensvalk.com/),you’llfindlinkstootherhelpfulwebsitesanddownloadableversionsofalloftheprogramsinthisbook.You’llalsofindsolutionstosomeofthediscoveriespresentedinthisbook,andyoucanevenshareyourownsolutions.

conclusionMINDSTORMScansparktheimaginationandcreativityofanyonewhousesit,whetherchildoradult.NowgrabyourNXT2.0roboticskit,startreadingChapter1,andenterthecreativeworldofLEGOMINDSTORMS.Ihopethatmyofferingtoyouwillhelpsparkyourimagination!

Page 30: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PARTI

gettingstarted

Page 31: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

1

collectingtheequipmentforyourrobot

InChapters2through5,you’llcreateaworkingrobotthatcanmovearoundaroombyitself.Butbeforeyoustartbuildingthisrobot,youneedtodeterminewhatyouneed.TherehavebeenvariousversionsofLEGOMINDSTORMSNXTsetsinthepast,butalltherobotmodelsinthisbookrequireonlyoneLEGOMINDSTORMSNXT2.0kit(LEGOcatalog#8547).Ifyouhavethiskit,showninFigure1-1,you’rereadytogo.IfyouhaveadifferentversionoftheNXTsystemandyouwouldstillliketousethisbook,visitthecompanionwebsite(http://www.discovery.laurensvalk.com/)forsuggestionsonhowtofindthepiecesthatyou’llneedinordertocompletetheprojectsinthisbook.

what’sintheboxTheLEGOMINDSTORMSNXT2.0kitcomeswithalotofTECHNICbuildingpieces,aswellassomeelectronicones(includingmotors,sensors,theNXTbrick,andcables).Figure1-2showseachtypeofNXT2.0piece.You’lllearnhowtouseeachtypeofpartasyoureadthisbook.

Page 32: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure1-1:TheLEGOMINDSTORMSNXT2.0set

Figure1-2:TheNXTkitcontainsvarioustypesofparts.

Page 33: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

NXTrobotsusemotorsformovementssuchasgrabbinganobjectordriving.Theyusesensorstotakeinputfromtheirsurroundings,suchastheintensityofalightbulb,acolor,orthedistancetoanobject.

ThecablesconnectthemotorsandsensorstotheNXTbrick.

theNXTbrickTheNXTbrick,orsimplytheNXT,isasmallcomputerthatcontrolsthemotorsandsensorssothatyourrobotcanperformactionsbyitself.Forinstance,youcouldbuildarobotthatautomaticallyturnsonalightswitchwhenitisgettingdarkoutside.Asensor(whichcanmeasurelight)tellstheNXTthatitisgettingdark,andtheNXTbrickthentriggersamotortopressthelightswitch.

Butyourrobotwon’tdoanythingwithoutaprogram.

theNXT-GprogrammingsoftwareYou’llfindtheNXT-GprogrammingsoftwareontheCDincludedintheLEGOMINDSTORMSNXT2.0kit(Figure1-3).YoucreateanNXTprogramusingacomputerandtheNXT-Gprogrammingsoftware.AnNXTprogramcontainsinstructionsforalltheactionsthatyourrobotshouldperform.Onceyou’vefinishedcreatingyourprogram,youtransferittotheNXTwithaUSBcable(suppliedinthekit).Thecombinationofmotors,sensors,theNXT,andyourprogramformyourLEGOMINDSTORMSrobot.

NOTE Ifyou’vemixedupthepartsinyourLEGOMINDSTORMSNXT2.0kitwithyourotherLEGOpieces,youcansortthemoutusingtheinventorysheetonthebackinsidecover.

Page 34: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure1-3:Theuserguide,theNXT-Gprogrammingsoftware,andtheUSBcable.TheuserguidecontainsadditionalinformationabouttheNXTset,butI’llbecoveringmuchofthatinformationinthisbook.

installingthesoftwareBeforeyoucancreateprogramstocontrolyourrobots,youneedtoinstalltheLEGOMINDSTORMSNXT2.0software.InserttheCDincludedwithyourkitintoyourCDdrive,andyou’llseeaninstallationscreen.Justfollowtheinstructionsthatappearonthecomputerscreentoinstallthesoftware.Youcaninstallthesoftwareinanylanguageyoulike,butthisbookisbasedontheEnglishversion.Ifthisbookasksyoutoenteradecimalnumbersuchas2.5,butyoutypicallyenternumberswithacommainplaceoftheperiod,justenter2,5thewayyouareusedtodoing.

thetestpadYou’llusetheTestPad(Figure1-4)forsomeofyourrobotactivities.Forexample,you’llcreatearobotthatfollowsthethickblacklineonthispadlaterinthisbook.

Page 35: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

insertingbatteriesTopowertherobot,insertsixAAbatteriesintotheNXT,asshowninFigure1-5.YoucanusestandardrechargeableornonrechargeablebatteriesortheLEGOrechargeablebattery(LEGOcatalog#9798)withthetransformer(#9833).YoumayalsousethenewLEGOrechargeablebattery(#9693)withitstransformer(#8887).

Figure1-4:TheTestPad

conclusionNowthatyou’vecollectedeverythingyouneedtobuildandprogramaworkingrobot,you’rereadytostartbuildingone.InChapter2you’lllearnmoreabout

Page 36: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

theNXT,motors,andcablesasyoubuildyourfirstrobot.

Figure1-5:YoucanpowertheNXTbrickwithsixAAbatteriesortheLEGOrechargeablebattery.

Page 37: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

2

buildingyourfirstrobot

InChapter1,youlearnedthatarobotconsistsofseveralimportantcomponents.Tomakeiteasierforyoutounderstandhoweachoftheseworks,you’llbeginbyworkingwithonlysomeofthem.Specifically,you’llfirstlearntoworkwiththeNXTmotorsandthebrickasyoubuildawheeledvehicle(theExplorer,showninFigure2-1)thatcandrivearoundyourroom.Onceyou’vebuilttheExplorer,you’lldoaquicktesttoseewhetheryou’vecorrectlyassembledtherobotandtomakeitmove!

buildingtheexplorerTobegin,selectthepiecesyou’llneedfortheExplorerbyreferencingthebillofmaterialsshowninFigure2-2.Then,assembletherobotasshowninthestep-by-stepbuildingimagesonthenextpages.

Page 38: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure2-1:TheExplorer

Figure2-2:Billofmaterials

Page 39: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

buildingtip:beamsandaxlesTheLEGOMINDSTORMSNXT2.0roboticskitcontainsalotofbeamsandaxles.Becausethesepartscomeinavarietyoflengths,it’ssometimeshardtofigureoutwhichoneyou’llneed.Tohelpyousortoutwhichoneyou’llneed,I’llindicatethelengthasshowninthelabelsonthediagraminFigure2-3.Thenumbersinboxesrefertobeams;thoseincirclesrefertoaxles.

Figure2-3:Beamsandaxlescomeindifferentlengths,somakesureyoupickthecorrectoneswhilegoingthroughthebuildinginstructions.Insteadofdeterminingthelengthofbeamsandaxlesyourself,youcanalsousethe1:1referencechartonthefrontinsidecover.

Tofindthelengthofabeam,simplycountthenumberofholes.Forinstance,thebeamshowninFigure2-3hasnineholesinit,asindicatedbythe“9”intheboxnexttoit.Thenumbersincirclestellyouthelengthofaxles.Todeterminethelengthofanaxle,placeitnexttoabeam,andcounthowmanyholesitcovers,asshowninFigure2-3.Theblackaxleshownherecoversfourholes,soitshows“4”inthecircle.

buildingtip:frictionandnonfrictionpinsTheNXTsetalsoincludespins,whichyou’llusetoconnecttwoormoreparts.Thesetcontainsfrictionpins,whichwon’tturneasilyifyouconnectthemtoabeam,andnonfrictionpins,whichdorotateeasilywhenconnectedtoabeam.

Frictionandnonfrictionpinsmaybethesameshape,butthepin’scolortellsyouwhattypeofpinitis,asshownonthefrontinsidecover.Whenyou’refollowingthebuildinginstructions,besuretopickthecorrecttypeofpinasyoubuild.Thefrontinsidecoveralsoshowshowthepincolorslookintheblack-

Page 40: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

and-whiteimagesinthebook.

Page 41: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 42: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 43: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 44: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 45: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 46: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 47: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 48: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 49: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingthecablesTousetheNXTmotors,youneedtoconnectthemtotheNXTbrickusingcables.MotorsareconnectedtooutputportscalledA,B,andC,asshowninFigure2-4.

Page 50: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure2-4:OutputportsA,B,andCareusedtoconnectmotorstotheNXT.Inthisexample,themotorisconnectedtooutputportA.

YourLEGOMINDSTORMSNXT2.0roboticskithasthreetypesofcables:ashortcable(20cm,or8inches),fourmedium-sizedones(35cm,or15inches),andtwolongcables(50cm,or20inches).FortheExplorerrobot,you’llusemedium-sizedcablestoconnectthemotorstoportsBandC,asshowninFigure2-5.

Figure2-5:Whenconnectingthemedium-sizedcablestotheExplorer,plugoneendofacableintotheNXTbrick,wrapthecablearoundtheLEGOpiecesafewtimes,andthenplugitintotheappropriatemotor.

Whenconnectingyourcables,makesuretheydonotinterferewiththemovementofthefrontwheelsorthesupportingwheelinthebackofthemodel.Tomovethecablesoutoftheway,tiethemaroundsomeoftheLEGOpiecesin

Page 51: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

therobotsothatthewheelsandthecasterwheelcanspinfreely.Forexample,youcanwirethecablesasshowninFigure2-5.

usingtheNXTbuttonstonavigateontheNXTbrick

Congratulations,you’vefinishedbuildingyourtrainingvehicle!Now,beforeyoumoveontoprogramminginChapter3,you’lllearnhowtousethebuttonsontheNXTbrick(showninFigure2-6)tonavigatearoundtheNXTbrick’smenusandtorunprogramsstoredonthebrick.

Figure2-6:TheNXTscreenandtheNXTbuttons

turningonthebrickToturnonthebrick,pressthe(orange)Enterbutton,asshowninFigure2-7.Afteryouhearthestartupsound,youshouldseethemainmenuonthebrick’sscreen,displayingacoupleofdifferenticons,asshowninthefigure.

Page 52: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure2-7:TurningontheNXTBrickwiththeEnterbuttonwillopenthemainmenu.

selectingandchoosingitemsTheselecteditemisalwaysinthemiddleofthescreen,asshowninFigure2-8.Youcanswitchtoiconsontheleftandtherightwiththelightgrayarrowbuttons.Toselectanitem(Figure2-8),presstheEnterbutton.

Figure2-8:YoupresstheEnterbuttontochooseaselecteditem.

Toreturntothepreviousmenu(Figure2-9),pressthedarkgrayExitbutton.

Page 53: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure2-9:YoucanreturntothepreviousmenubypressingtheExitbutton.

turningoffthebrickToturnoffthebrick,returntothemainmenu,andpresstheExitbutton.Whenyouseetheoptionforturningoffthebrick,eitherselectthecheckmarktoturnitofforselecttheXicontocancel(Figure2-10).

Figure2-10:TurningofftheNXTbrick

runningaprogramNXTrobotsbeginperformingtheiractionswhenyouselectandrunaprogramthathasbeentransferredtothebrick.Youhaven’ttransferredaprogramtothebrickyet,butyoucantryasampleprogramthatisalreadyonthebrick,called

Page 54: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DemoV2.TotestyourExplorer,runthisDemoV2programbynavigatingthroughthemenuontheNXTbrick,asshowninFigure2-11.

NOTE Ifforsomereasonyoucan’tfindtheDemoV2programonyourNXTbrick,justskipthisstep.

Ifyou’veputtogethereverythingproperly,yourrobotshouldmovearoundandmakesomesounds.Toaborttherunningprogram,presstheExitbutton.

Nowthatyouknowhowtostartandstopprograms,you’rereadytocreateyourownprograms!

conclusionYouhavejustlearnedtoworkwithtwoessentialrobotcomponents:theNXTbrickandmotors.WhenyourantheDemoV2program,theprogramturnedthemotors,whichmadetherobotmove.InChapters3and4,you’lllearnhowtheseprogramswork,aswellashowyoucanmakeyourownprograms.

Figure2-11:RuntheDemoV2programbynavigatingtoMyFiles▸Softwarefiles▸DemoV2▸Run.

Page 55: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

3

creatingandmodifyingprograms

Nowthatyou’vebuiltyourrobot,thenextthingtherobotneedsinordertofunctionisaprogram.Programstellyourrobotwhattodo.Forexample,aprogramcanmaketheExplorerdriveforwardandthensteer.Thischapterwillteachyouhowtocreateandeditprograms.

aquickfirstprogramYou’llfirsttakeaquicklookattheNXT-Gprogrammingsoftwarebycreatinganddownloadingasmallprogramtotherobot.Tocreatetheprogram,followthesesteps:1.ConnecttherobottothecomputerusingtheUSBcablethatcamewiththekit

(Figure3-1),andthenturnontheNXTbrickbypressingtheorangeEnterbutton.(Youhavetoconnecttherobottothecomputereachtimeyouwanttodownloadaprogramtotherobot.)IfyouwanttouseBluetoothtotransferprogramstotheNXT,seetheappendix.

2.LaunchtheLEGOMINDSTORMSNXT2.0software(alsocalledNXT-G).Onceitfinishesloading,youshouldseeascreenliketheoneshowninFigure3-2.Thisisthemainmenuoftheprogrammingsoftware.You’lluseittocreatenewprogramsortoopenprogramsyou’vemade.

Page 56: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-1:Therobotconnectedtothecomputer

3.CreateanewprogrambyenteringExplorer-1intheCreatenewprogrambox(locatedinthemiddleofthescreen),andthenclicktheGo>>button(Figure3-3).Youcanchooseanynameforyourprogram,butit’sagoodideatogiveitadescriptivenamethatwillbeeasyforyoutorecognizelater.Forexample,inthiscase,youcancallyourprogramExplorer-1becauseitisthefirstprogramfortheExplorerrobot.

Page 57: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-2:TheNXT-Gstartupscreen

Figure3-3:Creatinganewprogram

4.PickablockandplaceitonthelocationindicatedbyFigure3-4.Rememberthataprogramisbasicallyalistofinstructionsforactionsthattherobotshouldperform.Thesingleblockyouplacehereisjustsuchaninstruction—onethatmakestherobotmoveforwardforashortwhile.

Page 58: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-4:Pickingandplacingablock

5.Onceyou’vefinishedsteps1through4,clicktheDownloadandRunbutton,andwaitforyourrobottostartmoving.(Figure3-5).Eachtimeyouwanttodownloadtheprogramagain,simplyclickthisbutton.

Figure3-5:Downloadingtheprogramtotherobot

Congratulations!Ifyourrobotmovesforwardashortdistance,you’vesuccessfullycreatedyourfirstprogram.

NOTE Ifforsomereasonyourrobotdidnotmoveasdescribedorifyou

Page 59: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

gotanerrormessage,somethingmaybewrongwiththeUSBconnection.TryturningtheNXTbrickoffandthenbackonagain.Ifthatdoesn’thelp,seetheappendixformoreinstructions.

creatingabasicprogramItwascooltoseethatyoucouldmaketherobotmove,butwhatexactlydidyoudotoaccomplishthis?You’llnowlookatseveralsectionsoftheNXT-Gsoftwaretobetterunderstandhowtocreateandeditbasicprogramsbeforeyoumoveontocreatingmorecomplicatedones.

Figure3-6showswhatyourscreenshouldlooklikejustafteryoustartworkingonanewprogram.I’lldiscusseachofthemarkedsectionsinturn.

1.programmingpaletteAprogramforyourrobotconsistsofoneormoreprogrammingblocks.Eachblockinstructstherobottodosomething,suchasmoveforwardormakeasound.YoucanselectanyoftheseblocksfromtheProgrammingPalette(Figure3-7),andeachofthemwillmaketherobotdosomethingdifferent.

TherearemultipleProgrammingPalettes,butfornowyouneedonlyone.IfyourProgrammingPalettedoesn’tlookliketheoneshowninFigure3-7,clickthetabatthebottomofthepalettetoopenthecorrectone.

Page 60: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-6:TheNXT-Gsoftwarewindowhasseveralsections.Youusedeachofthelabeledoneswhenyoucreatedyourfirstprogram.

Page 61: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-7:TheProgrammingPalette(aclose-upofsection1inFigure3-6)

2.workareaOnceyou’veselectedablocktouseinyourprogram,youplacethatblockontheWorkArea,asshowninFigure3-8.TheWorkAreaiswhereyoucreate

Page 62: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

yourprogram.Programsoftenconsistofmorethanoneblock.

Figure3-8:Onceyou’vepickedablockbyclickinganiconontheProgrammingPalette,youplaceitontheWorkArea.Ifit’sthefirstblockinaprogram,youplaceitontheStartArea.

TomoveablocktotheWorkArea,simplyclickaniconontheProgrammingPalette,andthenclicktheWorkAreawhereyouwanttoplacetheblock.

movinganddeletingblocksOnceyou’veplacedablockontheWorkArea,youcanmoveitbyclickingitwiththeleftmousebuttonandkeepingthebuttonpressedasyoumovetheblockaround.TodeleteablockfromtheWorkArea,clicktoselectit,andpresstheDELETEkey.

3.startArea

Page 63: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheStartArea,showninFigure3-8,iswhereyou’llplaceyourprogram’sfirstprogrammingblock.You’llplaceallsubsequentprogrammingblockstotheright,nexttothepreviousblock.(You’lllearnaboutprogramswithmorethanoneblockinChapter4.)

4.NXTcontrollerYouusetheNXTcontroller(showninFigure3-9)todownload(transfer)yourprogramstotheNXTbrick.

Figure3-9:TheNXTcontrollerhasfivebuttons,butfornowyou’lluseonlytheDownloadandDownloadandRunbuttons.

downloadingandrunningaprogramTotransferaprogramtotheNXTbrick,makesurethatthebrickisconnectedtoyourcomputer(eitherviaUSBorviaBluetooth),andthenclicktheDownloadandRunbuttonontheNXTcontroller.Therobotshouldbeeptoindicatethattheprogramhasbeentransferredsuccessfully,andtheprogramshouldbeginrunningautomatically.Theprogramwillstopwhenitfinishesrunningeachblockoftheprogram.

OnceaprogramhasbeensenttotheNXTbrick,therobotcanruntheprogramindependentofthecomputer.Evenwhenyouunplugtherobot’sUSBcable,theprogramshouldcontinuetorun.

manuallyrunningaprogram

Page 64: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

WhenaprogramendsorwhenyouabortaprogrambypressingtheExitbuttonontheNXTbrick,youcanrestarttheprogrammanuallyusingtheNXTbuttons,asdiscussedinChapter2.YoucanfindalltheprogramsdownloadedtothebrickbynavigatingtoMyfiles▸SoftwareFiles.Yourprogramsremaininthebrick’smemoryevenwhenyouturnofftheNXT,allowingyoutorunthemwheneveryouwant,includingwhenyou’renotnearacomputer.

downloadingaprogramwithoutrunningitSometimesitisnotveryhelpfultohaveaprogramrunautomaticallyonceyou’vefinisheddownloadingittoyourrobot.Forexample,ifyouprogramyourrobottodrivearoundtheroomandyoustillhaveittoconnectedtoyourcomputerbyaUSBcable,yourrobotmightgetstuckbecauseofthatconnectedUSBcable.

Totransferaprogramtothebrickwithouthavingtheprogramrunautomatically,clicktheDownloadbuttonontheNXTcontroller.Oncetheprogramfinishesdownloading(asindicatedbythebeepingsound),youcandisconnecttheUSBcableandthenstarttheprogramyourselfusingthebuttonsonthebrick.

usingBluetoothtodownloadprogramstotheNXT

YoucantransferprogramstothebrickusingBluetoothinsteadofaUSBcable.Ifyou’dliketouseBluetooth,pleaseseetheappendix.

workingwiththeNXT-Gsoftware

You’vejustseenwhatcreatingprogramsisallabout,butyou’llhavetolookatsomemoreoptionsoftheNXT-Gsoftwarebeforeyoucancreatemorecomplexprograms.Figure3-10showsyouafewmoreimportantsectionsofthesoftware.

Page 65: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

5.configurationpanelIfyouclickaprogrammingblockontheWorkArea,theConfigurationPanelshowsupatthebottomofthesoftwarewindow(Figure3-11).

Youlearnedthateachblockmakestherobotperformacertainaction.TheblockyouseeinFigure3-10makestheExplorermove,buttheexactmovementisspecifiedwiththeConfigurationPanel.Forinstance,youcanusethepaneltoconfiguretherobottomovebackwardinsteadofforward.

Figure3-10:Thesection“WorkingwiththeNXT-GSoftware”discussestheseremainingsections.

Figure3-11:TheConfigurationPanel

Manydifferentprogrammingblocksexist,eachwithitsownConfigurationPanel.SubsequentchapterswillteachyouaboutmanyoftheseblocksandtheirConfigurationPanels.

Page 66: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ConfigurationPanels.

6.littlehelpwindowIfyoukeepyourmouseonaprogrammingblockforafewseconds,theLittleHelpWindowshowsupatthebottomrightofthescreen(Figure3-12).Thiswindowtellsyouwhatkindofblockyouselectedandgivesyoubriefinformationaboutitsfunction.

Tolearnmoreabouttheblockinquestion,clickMorehelp.We’lldiscussmanyprogrammingblocksinthisbook,butifyouare

lookingforspecificinformation,suchasthesettingsofacertainblock,tryusingtheLittleHelpWindow.

7.programnavigationbarYoucanworkonmorethanoneprogramatthetime.EachprogramhasacorrespondingtabontheProgramNavigationBaratthetopoftheWorkArea.Tonavigatetoaprogram,simplyclickthetabwiththeprogram’snameonit,asshowninFigure3-13.You’llalsofindatabherethatyoucanclicktoreturntothemainmenuand,atthetoprightoftheWorkArea,abuttontoclosetheprogramonwhichyouarecurrentlyworking.

Figure3-12:TheLittleHelpWindowgivesyoubriefinformationaboutaselectedprogrammingblock.

8.toolbarAtthetopleftofthescreenistheToolbar(seeFigure3-14).Thebuttonsonthisbarareusedtomanageandmodifyyourprograms.(TheToolbaralsohasafewdrop-downmenus,butyouwon’tbeusingthemrightnow.)

managingprograms

Page 67: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

UsethethreebuttonsontheleftoftheToolbartocreatenewprograms(NewProgram),openonesyou’vemade(OpenProgram),orsaveprogramsyouarecurrentlyworkingon(SaveProgram).

Whenyousaveanewlycreatedprogramforthefirsttime,you’llbeaskedtoenteranamefortheprogram.(Notethatyoucanalsocreateoropenprogramsinthemainmenu,asyousawwhencreatingyourfirstprogram.)

modifyingprogramsThenextthreebuttonsontheToolbararetheCut,Copy,andPastebuttons.Thesebuttonsarejustlikethecut,copy,andpastefunctionsinwordprocessors.Insteadofcopyingtext,however,you’llusethesebuttonstocopyoneormoreprogrammingblocks,asshowninFigure3-15.

Figure3-13:Youcannavigatebetweendifferentprogramsandthemainmenubyclickingthecorrespondingtab.Tocloseaprogramyou’recurrentlyworkingon,clicktheredbuttonatthetoprightoftheWorkArea.

Page 68: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-14:ThebuttonsontheToolbarareusedtomanageandmodifyprograms.

Figure3-15:Copyingaseriesofblocks.Step1:Keeptheleftmousebuttonpressedwhileyoudragaselectionaroundtheblocksyouwanttocopy;thenpresstheCopybutton.Step2:ClickthePastebutton.Step3:Usetheleftmousebuttontodragthenewblocksnexttotheblocksthatwerealreadythere.

Page 69: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure3-16:Commentsinaprogram

TheUndoandRedobuttonsareusedtoundoorredochangesyoumaketoaprogram.Forinstance,youcanundotheeventinwhichyouaccidentallydeletedablock.

usingthepointer,pan,andcommenttoolsWhencreatingprograms,youcanusethreetoolstoeditornavigatearoundprograms.ThePointerToolismostcommonlyused.WhenthePointerToolisselectedontheToolbar(Figure3-14),youcanusethemousetoplace,move,andconfigureprogrammingblocksontheWorkArea.

IfyouselectthePanTool,themouseisusedtomovetheWorkArea.Thisisespeciallyusefulwhenyoumakelargeprogramsthatdon’tfitonyourcomputerscreen.Tonavigatetoaspecificpartinyourprogram,selectthePanTool,clicksomewhereintheWorkArea,anddragthisareaaroundbymovingthemousewhileyoukeeptheleftmousebuttonpressed.

NextontheToolbaristheCommentTool.UsethistooltoplaceyourowncommentsontheWorkArea.Thesecommentsdonotaffecttheactionsofyourprogram,buttheywillhelpyourememberwhateachpartinaprogramdoeswhenyoureviewtheprogramlater.Toaddacomment,selecttheCommentToolontheToolbar,clickwhereyouwanttoplacethecommentontheWorkArea,andenterthecomment.YoucanseeanexampleofaprogramwithcommentsinFigure3-16.

9.robocenter

Page 70: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

OntherightofthesoftwarewindowistheRoboCenter,asshowninFigure3-17.ThissectioncontainsbuildingandprogrammingplansforthefourrobotsfeaturedontheLEGOMINDSTORMSNXT2.0box.Toviewtheseinstructions,clickoneoftherobots.

Whenyouarecreatingprogramsfortherobotsinthisbook,youwon’tbeusingtheRoboCenter,sogoaheadandcloseit(byclickingtheredXbutton)tofreeupspaceonyourcomputerscreentoworkonyourprogram.Youcanopenitatanytimebyclickingtheorangebeam,asshowninFigure3-17.

Figure3-17:ClosetheRobotCentertofreeupspaceontheprogrammingfield.Toreopenit,clicktheorangeLEGObeam.

controllingtherobotremotelyProgrammingarobottomoveautonomously(asyou’lllearninChapter4)is

Page 71: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

certainlyfun,butyoucanalsocontrolitremotelyfromyourcomputerkeyboardusingthearrowkeys.Todoso,makesurethattherobotisconnectedtothecomputer(eitherviatheUSBcableorviaBluetooth),andfollowtheinstructionsinFigure3-18.

Figure3-18:TocontroltheExplorerremotely,clickToolsintheToolbarandthenclickRemoteControl.Youshouldnowbeabletocontroltherobotbyclickingthearrowsonscreenorbyusingthearrowkeysonyourkeyboard.Toadjusttherobot’sspeed,clickthe+and-buttons.Toreturntoprogramming,clicktheClosebutton.

conclusionInthischapter,you’velearnedalotaboutworkingwiththeNXT-Gprogrammingsoftware.Youshouldnowknowhowtocreate,edit,andsave

Page 72: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

programs,aswellashowtotransferprogramstotheNXTbrick.Nowthatyou’vegainedthisessentialbitofinformation,you’rereadyto

takeonsomeseriousprogrammingchallengesinChapter4.

Page 73: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

4

workingwithprogrammingblocks:move,sound,anddisplay

InChapter3,youlearnedthebasicsofhowtocreateanewprogramandtransferittotheExplorerrobot.Youalsolearnedthattheprogramsyoumakearecollectionsofprogrammingblocks,whichareinstructionsthattelltherobotwhattodo.Inthischapter,you’lllearnmoreabouttheseprogrammingblocksandhowtousethemtomakeworkingprograms.

You’llbeginbylearningmoreabouthowtomaketheExplorermoveasyouexploreNXTprogramminginmoredetail.You’llalsolearnhowtomaketherobot“talk”anddisplaytextorimagesontheNXTscreen.Asyoupracticewiththesampleprogramsinthischapter,you’llbechallengedtosolvesomeprogrammingpuzzlesbyyourself!

whatdoprogrammingblocksdo?

NXTprogramsconsistofaseriesofprogrammingblocks,eachofwhichisusedtomaketherobotdosomethingspecific,suchasmoveforwardforonesecond.AlltheblocksareputontheSequenceBeam,asshowninFigure4-1.

TheNXTprogramrunstheblocksontheSequenceBeamonebyone,beginningwiththefirstblock.Oncethefirstblockfinishesrunning,theprogramcontinueswiththesecondblock,andsoon.Oncethelastblockfinishesrunning,theprogramends.

usingblockstocreateprograms

Page 74: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

AsyoulearnedinChapter3,youaddablocktoaprogrambyselectingtheblockfromtheProgrammingPaletteandplacingitontheWorkArea.Onceyou’vedonethat,youcanmodifytheblock’sactionsintheConfigurationPanel.Forexample,youcanconfigureablocktomaketherobotmovebackwardinsteadofforward.

Whenyou’vefinishedcreatingyourprogram,youdownloadittotheNXTbrickandrunit.

Figure4-1:TwoprogrammingblocksontheSequenceBeam

usingdifferentprogrammingblocksManydifferentprogrammingblocksexist,includingonesthatmaketherobotmoveormakesounds.EachblockhasitsownnameanduniquelooksoyoucaneasilytellthedifferencebetweentheblocksthatyouplaceontheWorkArea.Differentcombinationsofblocksandsettingswillmakeyourrobotbehavedifferently,andthischapterwillteachyouhowsomeoftheessentialprogrammingblockswork.

themoveblockThefirstblockyou’lllearntouseistheMoveblock,whichcontrolsthemovementofarobot’smotors.Byusingthisblockinyourprogram,youcanmaketheExplorermoveforwardandbackwardandsteerleftorright.

Forexample,youusedaMoveblockinChapter3tomakeyourExplorer

Page 75: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

moveforwardforashortwhile.

seeingthemoveblockinactionBeforeyoulearnhowtheMoveblockworks,you’llmakeasmallprogramtoseeitsfunctionalityinaction.ThisprogramwillmaketheExplorerdrivebackwardforthreesecondsandthenquicklyspintotheright.Becausethesearetwodifferentactions,you’llusetwoMoveblocks.1.CreateanewprogramcalledExplorer-Move,andthenpicktwoMove

blocksfromtheProgrammingPaletteandplacethemontheWorkArea,asshowninFigure4-2.

Figure4-2:ChooseaMoveblockfromtheProgrammingPalette,andplaceitontheStartArea.Toplacethesecondblock,chooseanotherblock,andputitnexttothefirstone.

2.Bydefault,theblocksyou’vejustplacedareconfiguredtomaketherobotgoforwardforalittlewhile.However,youwantthefirstMoveblocktomaketherobotdrivebackwardandtheotherblocktosteertherobot.To

Page 76: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

accomplishthis,you’llchangethesettingsintheConfigurationPanelofeachblock,asshowninFigure4-3.

3.Next,you’llmodifytheconfigurationsofthesecondblock,asshowninFigure4-4.ThisblockwillmaketheExplorerspinquicklytotheright.Whenbothwheelshavemadetwocompleterotations,themotorswillstopasspecifiedintheblock.(You’lllearnmoreabouteachofthesettingsinthenextsection.)

Figure4-3:TheconfigurationofthefirstblockintheExplorer-Moveprogram.Clicktheblocktoselectit,andconfigureyourblocksettingstolooklikethoseinthisfigure.TheselectedblockmakestheExplorerdrivebackwardslowlyforthreeseconds.

Page 77: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-4:TheconfigurationofthesecondblockintheExplorer-Moveprogram.Beforeapplyingthesesettings,clickthesecondMoveblocktoopenitsConfigurationPanel.

4.OnceyouhaveconfiguredbothMoveblocks,youcandownloadtheprogramtoyourrobotandrunit.TheExplorershouldgobackwardforexactlythreesecondsandthenturnaroundquickly.

understandingtheconfigurationpanelYou’llnowtakeacloserlookatthesettingsontheConfigurationPanelforeachblocktobetterunderstandhowthesampleprogramreallyworked.Thecombinationofallthesettingsdetermineswhattheblockwilldo.

Figure4-5showstheMoveblock’sConfigurationPanel.AtthetopleftofthepanelyouseethewordMoveandanimageoftwogearsindicatingthatthisisaMoveblock.Eachblockhasitsownnameandimage.(You’llalsoseeasmallsectionwithseverallettersandnumbersjustbelowthisimage,butyouwon’tusethesevaluesjustyet.Whenconfiguringblocks,youcanignorethesevalues.)

TherestoftheConfigurationPanelisdividedintolightgrayboxes,eachofwhichconfiguresonesetting.Forexample,youusethePowersettingtosettherobot’sspeed.You’llnowlookatthefunctionsofeachofthesettings.

Page 78: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

portBecausetheExplorerisdrivenbytwomotorsconnectedtooutputportsBandCwithcables,portsBandCareselectedinthisblock’spanel.Ifyoubuildarobotwithdifferentconnections(suchasportsAandB),selecttheappropriateportsinthePortsbox.

directionIntheDirectionbox,youselectwhetheryouwanttherobottomoveforwardorbackward.Inotherwords,youselectthedirectioninwhichthemotorsmustturn.Ifyouselecttheupward-pointingarrow,therobotwillgoforward;selectthedownward-pointingarrow,anditwillmovebackward.

YoucanalsousetheMoveblocktomakethemotorsstopmovingbyselectingthestopsigninthisDirectionbox.(Thisisusefulonlywhentherobotisalreadymovingbecauseofanotherblock,asyou’llseein“MoreontheMoveBlock:MovingUnlimited”onpage44.)

steeringAsyousawwiththeExplorer-Moveprogram,youcanalsouseaMoveblocktomaketherobotsteer.Toadjustyourrobot’ssteering,dragtheSteeringslidertotheleft(tomaketherobotsteertotheleft)orright.

Buthowcanavehicleturnwithoutasteeringwheel?Figure4-6showstheeffectofdifferentcombinationsofDirectionandSteeringconfigurations.NoticethattheExplorercanturnbyalteringthespeedanddirectionofbothwheels.

powerUsetheMoveblock’sPowerboxtocontrolthespeedofthemotors.Zeropowermeansthatthewheelsdonotmoveatall,while100setsthemotorstomaximumspeed.

durationIntheExplorer-Moveprogramyousawthatyoucancontrolhowlongacertainmovementwillrun.Forinstance,settingDurationto3Secondsmadethe

Page 79: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Explorermoveforthreeseconds.OtheroptionshereincludeRotationsandDegrees:*Rotationscontrolsthenumberoftimesthatthewheelsgothroughacompleterotation.Forexample,whenyousetDurationto2Rotationsinthesampleprogram,bothwheelsmadetwocompleterotations.

*DegreesworkslikeRotation,exceptthatitcontrolsthenumberofdegreesthatthewheelsturn.Forexample,youcouldsetDurationto180Degreestomakethewheelsturnone-halfrotation.

(You’lllearnabouttheUnlimitedoptioninChapter5.)

Figure4-5:TheMoveblockConfigurationPanelcontainsseveralsubsectionstochangethewaytherobotmoves.

Page 80: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-6:Tomaketherobotturn,adjusttheSteeringsettingintheMoveblock’sConfigurationPanel.Whenyoudoso,theNXTshouldcontrolthemotor’sspeedanddirectiontomaketherobotturn.Thedashedarrowsindicatethatawheelrollsforward,andthegrayarrowsmeanthatthewheelrollsbackward.Thebigblackarrowshowsthedirectioninwhichtheroboteventuallymoves.

DISCOVERY#1:ACCELERATE!Difficulty:EasyNowthatyou’velearnedsomeimportantinformationabouttheMoveblock,you’rereadytoexperimentwithit.Thegoalinthisdiscoverywillbetocreateaprogramthatmakestherobotmoveslowlyatfirstbutaccelerateastheprogramprogresses.Tobegin,place10MoveblocksontheWorkArea,andconfigurethefirstoneasshowninFigure4-7.Configurethesecondoneinthesameway,

Page 81: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

butsetthemotor’sPowersettingto20.Insubsequentblocks,setthePowersettingto30,andsoon,incrementingby10witheachblock.Whathappenswhenyourunthisprogram?

Figure4-7:TheConfigurationPanelofthefirstblockoftheprogramforDiscovery#1

NOTE Onecompletemotorrotationisequaltoa360-degreeturn.Tofindthenumberofrotations,dividethenumberofdegreesby360.Tofindthenumberofdegrees,multiplythenumberofrotationsby360.Forexample,insteadofentering180degreesintheDurationbox,youcouldalsouse0.5rotations.

nextactionTheNextActionboxcontrolswhathappensaftertheMoveblockcompletesitsmovement:*Brakestopsthemotorsimmediately.*Floatstopsthemotorsgently.

understandingtheconfigurationiconsAsyouchangeablock’ssettingsintheConfigurationPanel,theconfigurationiconsontheblockchangeaswell,asshowninFigure4-8.Bylookingattheseicons,youcanroughlydeterminewhatablockdoes.Thisisausefulwaytogetageneraloverviewofhowaprogramworks.

Forinstance,asyoucanseeinFigure4-8,thesecondMoveblockisconfiguredtoturnright.YoucanalsoseethattherobotwillturnatthemaximumspeedandthattheDurationsettingisconfiguredasRotations.Todeterminewhatanicononablockmeans,youcaneithercheckhowitchangesasyouchangetheConfigurationPanelorclickMorehelpintheLittleHelp

Page 82: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Window.

NOTE Whencreatingtheprogramsinthisbook,youdon’tneedtorememberwhateachspecificconfigurationiconstandsforbecausethefiguresshowyoutheConfigurationPanelofeachblock,makingiteasyforyoutore-createtheprogram.

Figure4-8:ConfigurationiconsontheblocksintheExplorer-Moveprogram

makingaccurateturnsWhenyouuseaMoveblocktohavetherobotmakea90-degreeturn,youmightthinkyouneedtosettheDurationsettingto90degrees,butthisisnotcorrect.TheDurationsettingspecifiesonlyhowmanydegreesthemotors(andthereforethewheels)turn.Theactualnumberofdegreesthatthemotorsshouldturninordertoenabletherobottomakea90-degreeturnisdifferentforeveryrobot.Discovery#2getsyoustartedfindingtheappropriatenumberofdegreesforyourrobot.

DISCOVERY#2:LOOKINGBACK!Difficulty:EasyCanyougetyourrobottomakea180-degreeturninplace?CreateanewprogramwithoneMoveblock,andmakesurethattheSteeringsliderinthe

Page 83: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ConfigurationPanelisshiftedallthewaytotheright.NowsettheDurationboxtoDegrees.WhatnumberdoyouneedtofillinforDegreesinordertomakeanaccurate180-degreeturn?BeginbysettingDegreesto500.Ifthisisnotenough,try550,600,ormaybeevensomethinghigher.

DISCOVERY#3:MOVETHAT’BOT!Difficulty:MediumMakeaprogramthatusesthreeMoveblockstomovetheExplorerforwardforthreesecondsat50percentpower,makea180-degreeturn,andthenreturntoitsstartingposition.WhenconfiguringtheMoveblockthatletstherobotturnaround(thesecondblock),usetheDurationvaluethatyoufoundinDiscovery#2.

thesoundblockIt’sfuntomakeprogramsthatallowtheExplorertodrivearound,butthingsbecomeevenmorefunwhenyoucanprogramtheNXTwithsoundsusingtheSoundblock.Yourrobotcanplaytwotypesofsounds:asimpletone(likeabeep)orasoundfile,suchasapplauseoraspokenwordsuchas“Yes.”WhenyouuseaSoundblockinyourprograms,therobotwillbeappeartobemoreinteractiveandlifelikebecauseitcan“talk.”

understandingthesoundblockconfigurationsEventhougheveryprogrammingblockallowstherobottodosomethingdifferent,allblocksareusedinthesameway.Inotherwords,youcansimplypickaSoundblockfromtheProgrammingPaletteandplaceitontheWorkAreaasyoudidwiththeMoveblock.Onceit’sinplace,youadjusttheblock’ssettingsintheConfigurationPanel.

BeforeyoustartcreatingbiggerprogramswithSoundblocks,you’lltakeaquicklookattheSoundblock’sConfigurationPanel.CreateanewprogramcalledExplorer-Sound,andplaceoneSoundblockontheWorkArea,asshowninFigure4-9.

Page 84: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

actionUsetheActionsettingontheblock’sConfigurationPaneltosetwhethertheblockshouldplayasoundfileoratone.

DISCOVERY#4:ROBOSPELLER!Difficulty:MediumUseMoveblockstomakeaprogramthatenablestheExplorertodriveasifitweredrawingthefirstletterofyourname.Howmanyblocksdoyouneedforyourletter?

HINTForcurvedturns,usetheSteeringslidertoadjustthetightnessofturns.

Dependingontheoptionyouselect,theConfigurationPanelchangesslightly,asexplainednext.

controlNormally,theControlboxisspecifiedasPlay.Toabortasoundthatiscurrentlyplaying,selectStop.

volumeUsetheVolumesettingtomakethesoundsofterorlouder.

functionIntheFunctionbox,youcanspecifywhethertorepeatasoundbycheckingtheRepeatcheckbox.Tostopthesoundfromrepeating,useanotherSoundblockwiththeControlsettingconfiguredtostopthesound.

fileIfyou’veconfiguredtheSoundblock’sActionsettingtoplayasoundfile,youcanselectonefromalistintheFilebox.Youcanchoosefromvarioussounds

Page 85: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

likewords(suchas“Hello”),numbers(suchas“Two”)orshortphrases(suchas“You’regood”).IfyouusemultipleSoundblocksinarow,witheachconfiguredtoplayasoundfile,youcanmakeyourrobotappeartotalk.

Youcanalsocreateyourownsoundfilesbyrecordingyourvoicewithamicrophoneorbyusinganexistingmusicfile.Todoso,selectTools▸SoundEditorontheToolbar.

Figure4-9:TheSoundblockanditsConfigurationPanel

(Tolearnmore,seepage56intheNXT’suserguide.)Onceyou’vemadeyourownsoundfile,youcanuseitinyourprogramswiththeSoundblock,justlikearegularsoundfile.

NOTE Ifyouusesoundsfilesinyourprogram,theywillbedownloadedtotherobotasyoutransferyourprogram.Ifyouusealotofdifferentsounds,youmightgetthemessagethat“theNXTdeviceisoutofmemory.”Tosolvethisproblem,seetheappendix.

Page 86: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-10:TheConfigurationPanelofaSoundblockthatisconfiguredtoplayatone

noteIfyouconfiguretheSoundblock’sActionsettingtoplayatone,adifferentboxappearsintheConfigurationPanel,asshowninFigure4-10.Insteadofselectingasoundfile,youcannowselectanotefromakeyboard,aswellasthelengthoftimethatthetoneshouldsound.

waitYou’llfindthelastsettingintheWaitbox.TheWaitforCompletioncheckboxshouldbecheckedifyouwanttheprogramtowaitforthesoundtofinishplayingbeforecontinuingwiththerestoftheprogram,asexplainedinthenextsection.

seeingthesoundblockinactionYou’llnowlearnhowtomakeaprogramthatusesSoundblockssothatyoucanseehowtheywork.Theprogramwillallowtherobottomovearoundwhilemakingsounds.

Tobegin,opentheExplorer-Soundprogram(orcreateitifyouhaven’talreadydoneso),andplacetwoSoundblocksandtwoMoveblocksinit,asshowninFigure4-11.ConfiguretheblocksasshownintheConfigurationPanels.Whenyou’vefinishedcreatingyourprogram,downloadittoyourrobot,andrunit.

Page 87: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-11:ThefourblocksoftheExplorer-Soundprogram.UsetheseimagesoftheConfigurationPanelstoconfigureeachoftheprogrammingblocks.Panel“a”showsthesettingsofblock“a.”

NOTEThelettersa,b,c,anddaretheretohelpyouunderstandwhichConfigurationPanelbelongstowhichblock.They’renotpartoftheactual

Page 88: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

program.

DISCOVERY#5:WHICHDIRECTIONDIDYOUSAY?!Difficulty:EasyCreateaprogramliketheExplorer-Soundprogramthathastherobotannouncethedirectioninwhichit’smovingasitmoves.Whilegoingforward,itshouldsay“Forward,”andwhilegoingbackward,itshouldsay“Backward.”HowdoyouconfiguretheWaitforCompletionsettingsintheSoundblocks?

DISCOVERY#6:BETHEDJ!Difficulty:MediumBymakingaprogramwithaseriesofSoundblocksconfiguredtoplaynotes,youcouldplayyourownmusicalcompositions.Canyouplayawell-knowntuneontheNXTorcreateyourowncooltune?Postyourprogramtothecompanionwebsite(http://www.discovery.laurensvalk.com/)toseewhatothersthink!

understandingtheexplorer-soundprogramNowthatyou’veruntheprogram,you’lllearnhowitworks.ThefirstSoundblockmakestheExplorersay“Hello.”TheWaitforCompletionboxinthisblockischecked,sotherobotwaitsuntiltherobotfinishessaying“Hello.”Onceithas,aMoveblockmakestherobotdriveforwardforthreeseconds.Next,anotherSoundblockcausestheNXTtoplayatone.Thisblockdoesn’twaitforthetonetocomplete,sowhilethesoundisplaying,thesecondMoveblockgetstherobottodrivebackwardforthreeseconds.Finally,therobotstopsmoving.Becausethetonewasalsoconfiguredtoplayforthreeseconds,theprogramends.

thedisplayblockInadditiontomovingaroundandplayingsounds,anNXTprogramcanalsocontrolwhatisdisplayedontheNXT’sLCDscreen.Forexample,youcould

Page 89: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

createaprogramthatmakestheNXTdisplaylooklikeFigure4-12.(TheLCDscreenis100pixelswideand64pixelstall.Pixelsarelikesmalldots.)

YouusetheDisplayblocktodisplayanimage(likeaLEGOminifigurehead),text(awordlike“Hello”),ordrawings(suchasaline)ontheNXTscreen.

NOTE TheDisplayblockcan’tputmultipleimagesortextlinesonthescreenatonce,soyou’llneedtouseaseriesofDisplayblocksinyourprograminordertocreatethedisplayshowninFigure4-12.

Figure4-12:UsingDisplayblocks,youcanshowimages,text,anddrawingsonthescreenoftheNXTbrick.

OncetheblockhasputsomethingontheNXTscreen,theprogrammovesontothenextblock,say,aMoveblock.TheNXTscreenkeepsshowingtheimageuntilanotherDisplayblockisusedtodisplaysomethingelse.So,inthisexample,theimageremainsonthescreenwhiletherobotmoves.

Whenaprogramends,theNXTautomaticallydisplaystheNXT’smenu.Therefore,whenthelastblockinyourprogramisaDisplayblock,youwon’thavetimetoseewhat’sonthedisplaybecausetheprogramhasalreadyended.Toseeit,you’dneedtoaddanotherblock,suchasaMoveblock,tokeeptheprogramfromendinginstantly.

understandingthedisplayblockconfigurationsBeforeyoucanuseDisplayblocksinyourprograms,youneedtounderstandhowtheywork.Inthissection,I’lldiscussthesettingsoftheblock’s

Page 90: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ConfigurationPanel.Createanewprogram(callitExplorer-Display),andplaceoneDisplay

blockontheWorkArea,asshowninFigure4-13.

actionUsetheActionsettingtochoosewhetherthescreenshoulddisplayanimage,sometext,oradrawing.TheConfigurationPanelwillchangeslightly,dependingontheoptionyouchoose.Resetwillmakethescreenlooklikethedisplayofaprogramthatdoesn’tuseanyDisplayblocksatall.

displayWhentheClearcheckboxintheDisplayboxischecked,theNXTremoveseverythingfromthescreenbeforedisplayingsomethingnew.Thisisusefulifyoudon’twantdifferentimagestooverlapeachother.Uncheckthisoptionwhenthescreenshouldnotbeclearedbeforedisplayingsomething,suchaswhenyouwanttodisplaymorethanonetextlineontheNXTscreen.Becausethescreenisn’tcleared,thenewtextlinewillsimplybeaddedbelowtheprevioustextlineonthescreen.(You’llpracticewiththisoptioninthesampleprogram.)

displayingimagesTheConfigurationPanelthatyouseedisplayedwilldependonwhichoptionyouselectintheactionbox.Forexample,ifyouselectImage,thepanelshouldlookliketheoneinFigure4-13.*UsetheFileboxtoselectanimagefromalistofimages.Whenyoudothis,youshouldseeapreviewofthisimageontherightsideofthepanel.

*UsethePositionboxtodefinewheretoplacetheimage.Dragtheimagearoundwithyourmouse,orentervaluesintheXbox(0isthemostleftand63isthemostright)andtheYbox(0isthelowestand99isthehighest)tosettheimage’sposition.(TheXandYcoordinateswouldsetthepositionofthebottom-leftcorneroftheimage.)

Justasyoucancreateyourownsoundfiles,youcanalsocreateyourownimagefilesusingdrawingsofsquares,lines,andcircles,oryoucansimplyuseanexistingpicture.Todoso,selectTools▸ImageEditorontheToolbar.(For

Page 91: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

moreinformation,seepage57oftheNXTuserguide.)Whenyou’redonecreatingyourimage,youcandisplayitwiththeDisplayblockasyouwouldanyotherimage.

displayingtextIfyouselectTextintheActionbox,you’llseeaConfigurationPanelasshowninFigure4-14.

EnterthetextyouwanttodisplayintheTextbox.UsethesettingsinthePositionboxtodefinewherethetextshouldbedisplayedeitherbydraggingthetextwithyourmouseorbyspecifyingtheXandYvaluesaswithdisplayingimages.

YoucanalsopositionlinesoftextbysettingtheLinenumber.Selecting1forLinewilldisplaytextatthetopofthescreen,whileselecting8forLineputstextonthebottomofthescreen.Thisconfigurationisusefulwhenyouwanttodisplayalongersentencethatdoesn’tfitononeline:Youcansplitthesentenceintomultiplepartsanddisplayeachpartononetextlinetokeepyourtextnicelyaligned.

Page 92: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-13:TheDisplayblockanditsConfigurationPanel

Figure4-14:TheConfigurationPanelofaDisplayblockconfiguredtodisplaytext

displayingdrawingsTodisplaylines,points(dots),orcircles,selectDrawingintheactionbox.YourConfigurationPanelshouldnowlooklikeFigure4-15.

IntheTypebox,selectwhethertodisplayapoint,aline,oracircle.YoucanadjustthepositionofeachbysettingtheappropriatevaluesintheXandYboxesorbydraggingtheobjectwithyourmouseinthePositionarea.Whendisplayingaline,youcanenterthecoordinatesoftheline’sstartingandendingpoints.Whendisplayingacircle,usetheRadiusboxtosetthecircle’ssize.

seeingthedisplayblockinactionNowthatyouunderstandmostoftheDisplayblock’sfeatures,you’lltestitsfunctionalitybycreatingaprogramthatputsthingsontheNXTscreenwhiletherobotmoves.

Todoso,placethreeDisplayblocksandtwoMoveblocksontheWorkArea,asshowninFigure4-16;thenconfigureeachblockasshownintheConfigurationPanels.Onceyou’veconfiguredalltheblocks,youcantransfertheprogramtoyourrobotandrunit.

understandingtheexplorer-displayprogramIntheExplorer-Displayprogram,theDisplayblockssimplyputseveralthingsonthescreen,andtheMoveblocksallowtheExplorertodrivearound.(NoticehowtheClearcheckboxesintheblocksareconfigured.)

ThefirstDisplayblock(blocka)clearsthescreenbeforeitdisplaysan

Page 93: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

image.Therobotthenstartstomove,andtheimagestaysonthescreenwhiletheMoveblock(b)isrunning.ThenextDisplayblock(c)isalsoconfiguredtoclearthescreen,soitremovestheimagebeforeitwritesalineoftextonthescreen.TheprogramthenmovesontoanotherDisplayblock(d),whichputsacircleonthescreen.Thisblockdoesn’tclearthescreeninadvance,soyou’llseeboththetextandthecircleonthescreen.Finally,aMoveblockmakestherobotturntotheright,andthentheprogramends.

Figure4-15:TheConfigurationPanelofaDisplayblockconfiguredtodisplayadrawing

Page 94: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 95: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-16:TheconfigurationoftheblocksintheExplorer-Displayprogram

furtherexplorationYou’vecompletedthebasicsofLEGOMINDSTORMSNXTprogramming.Congratulations!Youshouldnowknowhowtoprogramrobotstoperformactionssuchasmoving,makingsounds,anddisplayingtextandimagesontheNXTscreen.Chapter5willteachyoumoreaboutusingprogrammingblocks,includinghowtouseblockstopauseaprogramandhowtorepeatasetofblocks.

Butbeforeyoumoveon,trytosolvesomeofthefollowingdiscoveriestofurtherfuelyourprogrammingskills,andthenshareyoursolutionswithfellowbookreadersatthecompanionwebsite(http://www.discovery.laurensvalk.com/).

DISCOVERY#7:SUBTITLES!Difficulty:EasyCreateaprogramthatusesthreeSoundblockstosay,“Hello,sir,thankyou!”UseDisplayblockstodisplaywhattherobotsaysassubtitlesontheNXTscreenandtoclearthescreeneachtimetherobotstartssayingsomethingnew.WheredoyouplaceeachoftheDisplayblocks?

DISCOVERY#8:NAVIGATOR!Difficulty:MediumCreateaprogramwithMoveblocksthatmaketherobotdriveinthepatternshowninFigure4-17.Whilemoving,therobotshoulddisplayarrowsontheNXTscreenthatshowthedirectionofitsmovement.Whenfinished,itshoulddisplayastopsign.Inadditiontodisplayingthedirections,useSoundblockstoenabletorobottospeakthedirectionit’smovingin.HowdoyouconfiguretheWaitforCompletionboxintheSoundblocks?

HINTYoucanfindallthedirectionsignsshowninFigure4-17inthelistofimagesintheDisplayblock’sFilebox.UseSoundblockstoplaysoundslike“Forward”and“Left.”

Page 96: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure4-17:ThedrivingpatternandthenavigationimagesofDiscovery#8

DISCOVERY#9:CIRCLETIME!Difficulty:EasyCanyoumaketheExplorerdriveinacircularpatternwithadiameterofabout1meter(3feet)?You’llneedonlyoneMoveblocktoaccomplishthis.HowdoyouconfiguretheDurationandSteeringsettings?Andhowdoeschangingthemotorspeedaffectthecircle?

DISCOVERY#10:W8FORTHEEXPLORER!Difficulty:MediumProgramtheExplorertodriveinafigureeight,asshowninFigure4-18.The

Page 97: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

robotshouldshowahappyfaceonthescreenasitmoves.

Figure4-18:ThedrivetrackforDiscovery#10

DISCOVERY#11:ROBODANCER!Difficulty:HardMaketheExplorerplaymusicalbeats(usingSoundblocks)continuouslywhileitdancesinzigzaggingmovements(usingMoveblocks).Aftereachmovement,therobotshouldstartplayingadifferentsound.

HINTExperimentwiththeRepeatsettingintheSoundblocks.

BUILDINGDISCOVERY#1:EXPLORINGART!Inthisbuildingdiscoveryyou’rechallengedtoexpandtheExplorerrobotdesign.UsingLEGOpieces,createanattachmentforyourrobottoholdapen.Astherobotdrivesoverabigpieceofpaper,itwilldrawlinesandfigureswiththepenasitmoves.Asastart,youcanmakeitdrawthepatterninDiscovery#11.Advancedbuilding:Attachingafixedpeniscertainlyfunfordrawingsimplefigures,butyouwon’tbeabletouseafixedpentodrawwordssincethepenisconstantlyonthepaper.UsethethirdmotorinyourNXTkittoliftupthepen,andconnectthismotortooutputportAwithacable.YoucancontrolthismotorwithaMoveblock,withthePortsettingspecifiedtocontrolonlymotorA(notBandC).Canyoumaketherobotwriteyourname?

Page 98: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

5

waiting,repeating,andotherprogrammingtechniques

Thepreviouschaptertaughtyouhowtoprogramyourrobottoperformavarietyofactions,suchasmoving.Inthischapter,you’lllearnseveralprogrammingtechniquesthatwillallowyoutodomorewiththeblocksyouusedearlier,includinghowtopauseaprogramwithWaitblocks,howtorepeatasetofactionswithLoopblocks,howtorunmultipleblockssimultaneously,andevenhowtomakeyourownso-calledMyBlocks.

thewaitblockSofaryou’vebeenusingthreedifferentprogrammingblockstomaketherobotmove,playsounds,ordisplaysomethingonitsscreen.Nowyou’llmeetablockthatdoesnothingmorethanpausetheprogramforagivenamountoftime.ThisblockistheWaitblock,asshowninFigure5-1.

Page 99: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-1:TheWaitblockanditsConfigurationPanel

understandingthewaitblocksettingsYouusetheWaitblockjustlikeanyotherprogrammingblock.YouplaceitontheWorkAreaandthenconfigureitssettings.Theblockcanoperateintwomodes,asspecifiedintheControlboxoftheConfigurationPanel:SensororTime.You’lluseonlytheTimeoptioninthischapter.

WhensettousetheTimemode,theWaitblocksimplypausestheprogramforacertainamounttime,suchasfiveseconds.Oncethetimehaselapsed,theprogramcontinueswiththenextprogrammingblock.Toenteranamountoftimefortheblocktowait,enterthetimeintheSecondsboxaseitheraninteger(suchas14)oradecimal(suchas0.5).

seeingthewaitblockinactionWhywouldyouwanttouseablockthatdoesn’tperformanyactions?Here’sanexampleoftheWaitblockinaction.CreatetheExplorer-Waitprogram

Page 100: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

accordingtotheinstructionsshowninFigure5-2,andrunit.ThisprogramwilldisplaytwotextlinesontheNXTscreen.

Figure5-2:TheconfigurationoftheblocksintheExplorer-Waitprogram

understandingtheexplorer-waitprogramWhenyouruntheExplorer-Waitprogram,theWaitblocksgiveyoutimetoreadwhatisdisplayedontheNXTscreen.HadyounotplacedtheWaitblocksintheprogram,theprogramwouldendimmediatelyafterthetextwasdisplayedontheNXTscreen,makingitimpossibletoreadthistext.

moreonthemoveblock:movingunlimited

TheMoveblockcomesinhandywhenyouwanttomaketheExplorerdrivearound,andyou’veuseditinmanyofyourprogramssofar.However,thereisanimportantsettingonitsConfigurationPanelthatyouhavenotusedyet.

theunlimitedoption

Page 101: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheMoveblock’sDurationboxallowsyoutosethowlongtherobot’smotorswillruninseconds,degrees,orrotations.Oncetherobothasmovedforthespecifiedduration,themotorsstop,andthenextblockintheprogramruns.WhentheUnlimitedoptionisselectedintheDurationbox,themotorsaresimplyswitchedon,andtheyrunindefinitely.OnceaMoveblock(definedasDurationUnlimited)hasswitchedonthemotors(whichitselftakesalmostnotime),theprogrammovesontothenextblockintheprogramwhilethemotorsarestillturning.

DISCOVERY#12:COUNTDOWN!Difficulty:HardCreateaprogramthatmakestheNXTdisplayanexplodingbombafterthreeseconds.Theprogramshouldcountdownfrom3to0,whiledisplayingtheremainingtimeonthescreen.CreateyourprogramsothatthedisplaylookslikeFigure5-3afterthreeseconds.Formorefun,useSoundblockstomaketherobotsayhowmuchtimeisleftandhaveitshoutwhenthebombexplodes.

Figure5-3:TheappearanceoftheNXTscreeninDiscovery#12

Tostoptherobot,useanotherMoveblocksettostopthemotors(byselectingthestopsignintheDirectionbox).Therobotwillalsostopmovingoncetheprogramhasfinishedrunningallofitsblocks.YoucanusetheUnlimitedoptiontocreateprogramsthatallowyourrobottomakesoundswhileitmoves,asyou’llseeinthefollowingexampleprogram.

Page 102: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

thedurationunlimitedsettinginactionThenextprogram,namedExplorer-Unlimited,willhelpyouunderstandexactlyhowtheUnlimitedsettingworks.Thisprogramwillallowyourrobottomakeasoundwhileitdrives.CreatetheprogramasshowninFigure5-4.

NOTE Whenconfiguringblocksinaprogram,youmayfindthatyoucan’taccesssomeoftheboxesontheConfigurationPanel.Thisoccurswhenasettingisgrayedout,meaningit’snotonethatyoucanuse.Forexample,youcannotsettheSteeringinblockdinthisprogrambecausethisblockmakestherobotstop,andyoucannotsteerwhileyou’rebraking.Whenasettinginoneoftheseimagesisgrayedout,justignoreit.It’sgrayedoutforareason.

understandingtheexplorer-unlimitedprogramWhenyouruntheExplorer-Unlimitedprogram,aMoveblock(blocka)switchesonthemotors.Becauseblocka’sDurationissettoUnlimited,theprograminstantlymovesontothenextblock,theSoundblock(b).Aftertwoseconds,thesoundstops,andaWaitblock(c)makestheprogramwaitthreemoresecondsbeforemovingontothenextblock.Finally,anotherMoveblock(d)stopsthemotors,andaSoundblock(e)triggerstheNXTtoplayatone.

problemswithmovingunlimitedWhencreatingaprogramwithjustoneMoveblockwiththeDurationsettoUnlimited,youmightthinkthattherobotwouldgoforwardindefinitely,butthat’snotthecase.Thisblockonlyswitchesonthemotors,andtheprogramendsbecauseithasfinishedrunningallofitsblocks;andwhentheprogramends,themotorsstop.(You’lllearnhowtocreateprogramsthatrunindefinitelyinthenextsection.)

Page 103: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-4:TheconfigurationoftheblocksintheExplorer-Unlimitedprogram

theloopblock

Page 104: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Imagineyouarewalkingonasquare-shapedline,liketheoneshowninFigure5-5.Asyouwalk,youfollowacertainpatternoverandoveragain:Gostraight,thengoright,gostraight,goright,andsoon.

Figure5-5:TheExplorermovinginasquare

Figure5-6:TheLoopblockanditsConfigurationPanel(1).Toplaceblocks

Page 105: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

insideaLoopblock,firstplaceallrequiredblocksontheWorkArea(2).Next,selecttheblocksyouwanttomove,anddragthemintotheloop(3).TheLoopblockshouldautomaticallyenlargetocreatespacefortheblocksasyoutrytodragthemintoit.Also,whenyoudragaLoopblockaround,itscontentsshouldremaininsideit.

Tocreatethissortofbehaviorwithyourrobot,youcouldmakeyourrobotdrivearoundwithMoveblockssothatitfollowsthesamepattern.YoucouldmakeitgostraightandthenrightanduseaMoveblockforeachmovement.Tomakeyourrobottraceonecompletesquareandreturntothestartingposition,youwouldhavetouseeachofthesetwoblocksfourtimes,foratotalofeightblocks.

RatherthanuseeightMoveblockstocreatethisprogram,it’smucheasiertousetheLoopblock,whichletsyourepeatsequencesofblocksthatareplacedwithinit.Loopblocksareespeciallyusefulwhenyouwanttorepeatcertainactionsmanytimes.Forexample,tohaveyourrobotdriveinasquare,youwouldplacetheMoveblockstogoforwardandgorightinsidetheLoopblock,whichwouldthenruneachblock’sactionfourtimes.You’llcreatejustsuchaprogramin“SeeingtheLoopBlockinAction”onpage47.

usingtheloopblockFigure5-6showstheLoopblockwithitsConfigurationPanel,aswellashowtoplaceblocksinsidealoop.

Theflowofthisprogramfrombeginning(leftside)toend(rightside)isslightlydifferentwhenusingLoopblocks,asshowninFigure5-7.

understandingtheloopblocksettingsThesettingsontheLoopblock’sConfigurationPanelcontrolhowmanytimestheblocksinsidetheloopshouldberepeated.IntheControlbox,youcanconfiguretheblocktorepeatasetnumberoftimes(Count),tokeeprepeatingforacertainamountoftime(Time),ortorepeatindefinitely(Forever).*IfyouselectCount,youcanenterthenumberofrepetitionsintheCountbox.*IfyouselectTime,youcanentertheamountoftimethattheblockshouldloopintheSecondsbox.

*WhenForeverisselected,theLoopblockkeepsrepeatingtheblocksplaced

Page 106: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

insideindefinitely,unlessyouendtheprogrambypressingtheExitbuttonontheNXTbrick.TheControlboxalsoofferssettingsforSensorandLogic,whichyou’lllearnaboutlaterinthisbook.You’lllearnhowtoconfiguretheShowsettingontheConfigurationPanellateraswell.

seeingtheloopblockinactionYou’llnowcreatetheprogramthatIdiscussedearlier(Figure5-5).ThisprogramwillhavetheExplorermoveinasquare-shapedpattern.CreatetheExplorer-LoopprogramasshowninFigure5-8.

NOTE Ifyourrobotdoesn’tmake90-degreeturnswhensteering,tryadjustingthenumberofdegreesinMoveblockc,similartowhatyoudidinDiscovery#2inChapter4.

Figure5-7:AprogramwithaLoopblockthatloopsfourtimes.OncetheLoopblockhasrunthetwoblocksinsideitfourtimes(asspecifiedbyitsConfigurationPanel),theprogramcontinueswiththenextblock,aMoveblockinthiscase.

Page 107: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-8:TheconfigurationoftheblocksintheExplorer-Loopprogram

Page 108: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-9:TheExplorer-SquareprogramshowsyouhowyoucanhaveoneLoopblockinsideanotherone.TheinnerLoopblockmakestheExplorerdrivethroughashapedpattern,andtheouterlooprepeatsthisbehavior,aswellasmakingasound,fivetimes.

usingloopblockswithinloopblocksThestructureoftheLoopblockwiththetwoMoveblocksintheExplorer-Loopprogram(Figure5-8)makestheExplorerdriveinasquare.YoucanuseaLoopblocktorepeatthesquaredrivingbehaviorsothattherobotdrivesthrough,say,fivecompletesquarepatterns.You’llconfiguretheblocktoloopfivetimes,andyou’lldragtheblocksfromthepreviousprogramintoit,asshowninFigure5-9.You’llalsoaddaSoundblocktomakeExplorersaysomethingafterdrivingeachsquare.

makingyourownblocks:themyblock

Inadditiontousingready-madeblocks,youcanmakeyourownblockstomeetspecificneeds.BlocksthatyoucreatearecalledMyBlocksandconsistofasetofprogrammingblocks.MyBlocksareespeciallyusefulwhenyouwanttouseaspecificsetofblocksinyourprogrammorethanonce.Forexample,youcouldcreateaMyBlocktomaketheExplorerdriveinasquare-shapedpattern

Page 109: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

wheneveryouusethatblock.

DISCOVERY#13:GUARDTHEROOM!Difficulty:EasyCreateaprogramtoallowtheExplorertoconstantlymovebackandforthinfrontofyourbedroomdoor,asifguardingit(seeFigure5-10).UseoneLoopblockconfiguredtoloopindefinitely(settoForever),aMoveblocktomoveforward,andanotherMoveblocktoturnaround.

Figure5-10:ThepathfortheExplorerinDiscovery#13

DISCOVERY#14:TRIANGLE!Difficulty:MediumYou’vecreatedaprogramtodriveinsquare-shapedpatterns.HowcouldyoumodifytheExplorer-Loopprogramtodriveintriangle-shapedpatternsorinasix-sidedfigure?(Besuretorepeateachfigurefivetimes.)

Also,usingMyBlockscanhelpyoukeepyourprogramslookorganized,becauseyou’llseefewerblocksonthescreen.You’llseehowtocreateanduseMyBlocksasyoureadon.

creatingmyblocksTodemonstratetheMyBlockfunctionality,you’llcreateaprogramthatmakestheExplorerdriveinasquare,turnaround,makeasound,andthendriveanothersquare.BecauseExplorerdrivesthesquare-shapedfiguretwice,you’llcreateaMyBlocktoperformthisaction,asshowninFigures5-11through5-13.Onceyou’vecreatedyourMyBlock,youcanplaceitinaprogramwheneveryouwantExplorertodriveinasquare.You’llusetheExplorer-Loop

Page 110: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

programasafoundationforthisexperiment.

NOTE Ifyoudidn’tsavetheExplorer-Loopprogramearlier,createitagainbyfollowingthedirectionsinFigure5-8,ordownloaditfromthecompanionwebsite.

1.SelecttheblocksthatyouwanttoturnintoaMyBlock,andclicktheCreateMyBlockbutton,asshowninFigure5-11.

Figure5-11:SelectingtheblockstobeturnedintoaMyBlock

2.EnteranameforyourMyBlockintheBlockNamebox,suchasSquare,asshowninFigure5-12.UsetheBlockDescriptionareatodescribeyourblocksothatyou’llrememberhowitworksifyouwanttoreuseitlater,andthenclickNext.

Page 111: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-12:EnteranameanddescriptionforyourMyBlock.

3.DragiconstoyourblockfromtheIconBuildertogiveitauniquelook(asshowninFigure5-13),andthenclickFinish.

Page 112: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-13:AddingiconstoyourMyBlock

usingmyblocksinprogramsOnceyou’vefinishedcreatingyourMyBlock,itshouldappearontheWorkAreaandintheCustomPalette,whichyoucanopenasshowninFigure5-14.(ThefigurealsoshowstheExplorer-MyBlockprogram.)

Page 113: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-14:TheconfigurationoftheblocksintheExplorer-MyBlockprogram.YoucanfindMyBlocksontheCustomPalette.(TheMyBlock’sConfigurationPanelsarenotshownbecausetherearenosettingstochangeonthesepanels.)

Whenyouruntheprogram,therobotshouldfirstmoveinasquare(controlledbythesquareMyBlock)andthenturn,makeasound,anddriveanothersquare.

editingmyblocksYoucaneditMyBlocksafteryoucreatethem.Todoso,double-clickaMyBlockontheWorkAreatorevealitscontents,andthenedititasyou’dlike.Whenyou’refinished,clickSave,andreturntotheprogramthatusestheMyBlock.

Page 114: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Tochangetheiconsthatyouaddedtoyourblock,selecttheMyBlockontheWorkArea,andselectEdit▸EditMyBlockIconontheToolbar.

DISCOVERY#15:MYTRIANGLE!Difficulty:EasyCreateaprogramliketheExplorer-MyBlockprogramthatdrivesintrianglesinsteadofsquares.

HINTUsetheprogramyoumadeinDiscovery#14tomakethetriangleMyBlock.

DISCOVERY#16:MYTUNE!Difficulty:EasyRememberthetuneyoumadeusingSoundblocksinDiscovery#6inChapter4?ConvertthatsequenceofblocksintoaMyBlocksothatyoucaneasilyuseyourfavoritetuneanytimeinyourprograms.

parallelsequencesofblocksAlltheblocksthatyou’veusedsofarareexecutedlinearlyintheorderinwhichtheywereplacedontheSequenceBeam.However,theNXTcanexecutemultipleblocksatthesametime,inparallel,usingaParallelSequenceBeam,asshowninFigure5-15.

usingparallelsequencesinaprogramTolearnhowParallelSequenceswork,you’llcreatetheExplorer-Parallelprogramthatmakestherobotdriveincirclesasitmakessounds.CreatetheprogramshowninFigure5-16.

Page 115: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-15:BlocksontheMainSequenceBeamandaParallelSequenceBeamarerunatthesametime.NotethattheWaitBlockherecausesonlythesequenceofblocksitappearsintopause;theblocksontheParallelSequencearenotaffectedbytheWaitBlock.

Page 116: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure5-16:TheconfigurationoftheExplorer-Parallelprogram.PlacetheblocksrequiredforthisprogramontheWorkArea(1).Next,connectthetwoSequenceBeamsasshowninthefigure(2).

DISCOVERY#17:LET’SMULTITASK!Difficulty:EasyExpandtheExplorer-Parallelprogram(Figure5-16)tomaketherobotdriveintrianglesindefinitelywhileatthesametimeplayingatunecomposedofdifferentnotes.

Page 117: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

furtherexplorationNowthatyou’vesuccessfullygonethroughthefirstpartofthisbook,youhaveasolidknowledgeofseveralessentialprogrammingtechniques.Inthischapter,youlearnedhowtouseWaitandLoopblocksandhowtoworkwithMyBlocksaswellasparallelsequencesofblocks.

Inthenextpartofthisbook,you’llcreaterobotsthatcaninteractwiththeirenvironmentsviasensors.Butbeforeyoudo,practiceabitwithwhatyou’velearnedinthischapterbysolvingthefollowingdiscoveries.

DISCOVERY#18:COMPLEXFIGURES!Difficulty:MediumCreateaprogramthatmakestheExplorerdriveinthepatternshowninFigure5-17whilemakingdifferentsounds.

HINTIfyoulookcarefully,you’llseethatyoucandividethetrackintofourequalparts,soyouhavetoconfigureasetofMoveblocksforonlyoneoftheseparts.Next,you’llplacetheseblocksinaLoopblockconfiguredtoloopfourtimes.

Figure5-17:ThedrivetrackforDiscovery#18

BUILDINGDISCOVERY#2:MR.EXPLORER!

Page 118: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

InBuildingDiscovery#1(inChapter4),youfoundinstructionstocontrolathirdNXTmotor.ThistimeyouarechallengedtousetheextramotortocreateawavinghandforyourExplorer.UseotherLEGOpartstofurtherdecorateyourrobot,andturnitintoyourownMr.Explorer.Makehimrepeatedlywavehishandandplaysoundslike“Goodmorning!”atthesametime.

Page 119: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PARTII

buildingandprogrammingrobotswithsensors

Page 120: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

6

understandingsensors

TheLEGOMINDSTORMSNXT2.0roboticskitincludesthreetypesofsensors:Ultrasonic,Touch,andColor.YoucanusethesesensorstobuildarobotthatmakessoundswhenitseesyouortobuildavehiclethatdrivesaroundwhileavoidingwallsorthatfollowstheblacklineontheTestPad.Thissecondpartofthebookwillteachyouwhatyouneedtoknowinordertocreateworkingrobotswithsensors.

Tolearnhowtoworkwithsensors,you’llupgradetheExplorerrobotbyaddingseveralsensorattachmentstoittocreatetheDiscoveryrobotshowninFigure6-1.You’lllearntocreateprogramsforrobotswithsensorsasyouupgradeyourrobotwithanUltrasonicSensorattachment.Onceyouhaveagoodworkingknowledgeofhowtoprogramwithsensors,you’llcontinuecreatingmoresensorattachmentsforthisrobotinChapter7.

whataresensors?LEGOMINDSTORMSrobotscan’tactuallyseeorfeelthewayhumansdo,butbyaddingsensorstothem,theycancollectandreportinformationabouttheenvironmentaroundthem.Yourprogramscaninterpretsensorinformationinwaysthatwillmakeyourrobotseemtorespondtoitsenvironmentasifitisexperiencingit.Forinstance,youcouldcreateaprogramthatmakestherobotsay“Blue”whenoneofitssensorsseesapieceofbluepaper.

understandingthesensorsintheNXT2.0kitYourNXTkitcontainsthreesensors,asshowninFigure6-2.TheUltrasonicSensorreadsthedistancetoobjects,theTouchSensorsdetectbuttonpresses,andtheColorSensordetectsthecolorofasurface(amongotherthings,as

Page 121: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

you’lllearninChapter7).

Figure6-1:TheDiscoveryrobot:anenhancedversionoftheExplorerequippedwithanUltrasonicSensortomaketherobot“see”

Figure6-2:TheNXTkitcomeswithanUltrasonicSensor(left),twoTouchSensors(middle),andaColorSensor(right).

YouconnectthesensorstotheNXTviainputports,numbered1through4,asshowninFigure6-3.

Page 122: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-3:Sensorsareconnectedtoinputports.

Inthischapter,you’llexploretheUltrasonicSensor,andyou’lltakeamoredetailedlookattheothersensorsinChapter7.Theprogrammingtechniquesthatyou’lllearnfortheUltrasonicSensorcanbeusedforallthesensorsinthekit.

understandingtheultrasonicsensorTheUltrasonicSensorservesasyourrobot’seyes.To“see,”thesensormeasuresthedistancebetweenitandotherobjects(asshowninFigure6-4).TheNXTretrievestheinformationfromthesensorandusesitsmeasurementsinprograms.Forexample,usinginputfromthissensor,youcouldmakeyourrobotsay“Hello”whentheultrasonicsensorreportsanobjectinfrontofitthat’snearerthan50cm.

Page 123: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-4:TheUltrasonicSensorisusedtodetectobjectsbymeasuringthedistancetothem.Itcanseethingsupto200cm(80inches)away,butthefarthertheobjectis,theharderitisforthesensortoseeit.Whenthesensordoesn’tseeanything,itreportsavalueof255cm.

Asyou’lllearninthisandthefollowingchapters,youcanusetheUltrasonicSensorinanumberofinterestingways.Forexample,youcanuseittomakeavehicleavoidwalls(Chapter6),createanintruderalarmanddetecttargetstoshootat(Chapter8),findobjectstograb(Chapter13),andevendetectaceilingsothataverticalclimberknowstogodownagain(Chapter15).

creatingtheultrasonicsensorattachmentTobegin,addanUltrasonicSensortotheExplorerrobotasshowninthedirectionsonthefollowingpage.

NOTE Ifyouhavetroublefollowingthesesteps,trydisconnectingthemotorcablesandthenreattachingthemafteryouconnecttheUltrasonicSensor.BesuretoconnecttheUltrasonicSensortoinputport4ontheNXTusingamedium-sizedcable.

pollingsensorsWithouthavingtodoanyprogramming,youcanviewthesensorreadingsontheNXT’sViewmenu.Gatheringinformationfromasensorissometimesreferredtoaspolling.Topollasensor,followthesesteps:1.TurnonyourNXT,navigatetotheViewmenu(Figure6-5),andselectthe

sensoryouwanttopoll.2.ChooseUltrasoniccm(orUltrasonicInch).3.Selecttheinputportthesensorisconnectedto(port4),andyoushouldsee

thesensor’smeasurement,whichis37cminthiscase.

DISCOVERY#19:MINDYOURHEAD!Difficulty:EasyHowcouldyoufindouthowfaryourrobotisfromtheceilingofaroom?UsetheViewmodeandtheUltrasonicSensortofindout,makingsuretopointthesensor’s“eyes”towardtheceilingwhilemeasuring.Ifyouseeonlyquestion

Page 124: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

sensor’s“eyes”towardtheceilingwhilemeasuring.Ifyouseeonlyquestionmarksonthescreen,youmightneedtoholdthesensorupalittleclosertotheceiling.

Page 125: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-5:PollingasensorwiththeViewmenu

programmingwithsensorsYou’vejustseenhowtopollasensoryourself.Programscanalsopollasensorinordertousethesensor’sdata.Asanexample,you’llcreateaprogramthathastherobotplayasoundwhentheUltrasonicSensorseessomethingthat’scloserthan50cm(20inches),asshowninFigure6-6.

YoucanuseseveralprogrammingblockstopollsensorsincludingtheWaitandLoopblocksaswellastheSwitchblock.

Figure6-6:TheprogramthatrunsontheNXTpollsthesensorconstantly.Theprogrampausesuntilasensorreadinglessthan50cmisreported,atwhichpointitplaysasound.

sensorsandthewaitblockYoucanuseaWaitblocktopauseaprogramforseveralseconds,butalsotopauseuntilasensorreadinggoesaboveorbelowacertainvalue.Forexample,Figure6-7showsaWaitblockhaltingaprogramuntiltheUltrasonicSensordetectsasensorvaluelessthan50cm.Thisvalueof50cmiscalledthetriggervalue.Oncethistriggervalueisreached,thesensoristriggered,theWaitblock

Page 126: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

stopswaiting,andthenextblockintheprogram(i.e.,aSoundblock)runs.

usingtheconfigurationpanelYou’vejustlearnedhowaWaitblockisusedtopollasensor.Nowyou’llhavealookattheconfigurationsofthisblock.

FirstselecttheWaitblockconfiguredtopolltheUltrasonicSensorfromtheProgrammingPalette,asshowninFigure6-7.(ThisisreallyjusttheWaitblockyou’vebeenusingwiththeControlsettingsettoSensorinsteadofTime.)*YouusethePortsettingtoselecttheinputporttowhichthesensorisconnected.

*YousetthetriggervalueintheDistancesettingintheUntilboxbyenteringitsvalueorbydraggingtheslidertotheleft(closer)orright(farther).YouusetheDistancesettingtoselectwhethertheblockshouldwaituntilavalueabove(>)orbelow(<)thetriggervalueisreached.

*YouusetheShowsettingtochooseCentimetersorInches.

seeingthesensorsandthewaitblockinactionNowyou’llcreatetheDiscovery-WaitprogramthatplaysasoundwhentheUltrasonicSensorseessomethingcloserthan50cm(20inches),asshowninFigure6-8.

Beforerunningthisprogram,makesurethatthereisnothinginfrontofyourrobot.Whenyouruntheprogram,nothingshouldhappenatfirst,butasyoumoveyourhandinfrontoftheUltrasonicSensor,thesensorshoulddetectyourhandonceit’scloserthan50cm.Onceyourhandisdetected,theWaitblockshouldstopwaiting,andyourrobotshouldplayasound.

Page 127: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-7:TheWaitblockconfiguredtopollanUltrasonicSensor

Figure6-8:TheconfigurationoftheblocksintheDiscovery-Waitprogram.Experimentwiththetriggervalue(50cmhere)bychangingittomaketherobotresponddifferently.

Now,beforeyouproceedwithothersensorprogrammingtechniques,trytosolveDiscovery#20togetabetterunderstandingofhowtoworkwithsensors.

DISCOVERY#20:HELLOANDGOODBYE!Difficulty:Medium

Page 128: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Canyoucreateaprogramthathastherobotsay“Hello”whenitdetectsyourhandinfrontoftheUltrasonicSensorandthen“Goodbye”whenyoumoveyourhandaway?

HINTPlaceandconfigurethesequenceofthetwoblocksintheDiscovery-Waitprogram(Figure6-8)twice.ConfigurethefirstWaitblocktowaituntilitseessomethingcloserthan50cm,andconfigurethesecondWaitblocktowaituntilthesensorseessomethingfartherthan50cm.Onceyou’veconfirmedthatyourprogramworks,dragalltheblocksintooneLoopblocksothatyourrobotwillrepeatedlytellyouwhenitdetectsyourhand.

avoidingwallswiththeultrasonicsensorThenextprogram,Discovery-Avoid,willmaketheDiscoveryrobotdrivearoundaroomandturnaroundwhenitseessomethinginordertopreventitfrombumpingintoanobstaclesuchasawall.YoucanseeanoverviewoftheprograminFigure6-9.

Nextyou’llre-createtheprogramwithprogrammingblocks.YoucanaccomplisheachactiondescribedinFigure6-9withoneblock.You’lluseaMoveblocktoturnonthemotorswiththeDurationoptionsettoUnlimited,andthenyou’llwaitforthesensortobetriggeredwithaWaitblock.(Notethatwhiletheprogramwaits,therobotisstillmovingforward.)

Oncetherobotseessomething,youuseaMoveblocktoturnitaround(andstopitsunlimitedmovement).Forturningaround,theblock’sDurationoptionissettoaspecificnumberofrotations.Aftertherobotturnsaround,theprogramreturnstothebeginning,whichiswhyyoumustplacethethreeblocksusedinsideaLoopblockthat’sconfiguredtoloopforever.

Createtheprogramnow,asshowninFigure6-10.

sensorsandtheloopblockAsyoulearnedinChapter5,youcanconfigureaLoopblockinmanyways.YoucanconfigureLoopblockstoloopacertainnumberoftimes,loopforaspecifiedamountoftime,orloopforever.TheseconditionsindicatewhenaLoopblockshouldstoplooping.

YoucanuseasensortomakeaLoopblockstoprepeating.Forexample,youcanrepeatasequenceofMoveblocksinsideaLoopblockuntilthe

Page 129: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

UltrasonicSensorseessomethingthat’scloserthan25cm(10inches).

Figure6-9:TheprogramflowfortheDiscovery-Avoidprogram.Afterturningright,theprogramreturnstothestart,andtherobotmovesforwardagain.

Page 130: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-10:TheconfigurationoftheblocksintheDiscovery-Avoidprogram

DISCOVERY#21:AVOIDWALLSANDABADMOOD!

Page 131: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Difficulty:EasyExpandtheDiscovery-AvoidprogrambymakingitdisplayahappyfaceontheNXT’sdisplayasitmovesforwardandbymakingitdisplayasadfacewhenitisturningaroundtoavoidthewall.

HINTTodoso,tryputtingtwoDisplayblockssomewhereintheLoopblock.

DISCOVERY#22:FOLLOWME!Difficulty:MediumMaketheDiscoveryrobotfollowyouinastraightline.Whenyouplaceyourhandinfrontoftherobot,itshouldstop,butwhenyoumoveyourhandaway,itshouldmoveforwarduntilitseesyourhandagain.

TIPHaveoneblockwaitforthehandtocomeclose(andthenuseaMoveblocktostoptherobot’smovement)andanotherblockwaitforthehandtomoveaway,andthencontinuetherobot’smovement.PutalltheblocksinaLoopblock.

DISCOVERY#23:HAPPYTUNES!Difficulty:MediumUseaLoopblocktohavetherobotplayatuneuntilthesensorspotssomeonewatching,atwhichpointtherobotshouldscreamandturnitsheadtheotherway.

HINTYoucanusetheMyBlockthatyoumadeinDiscovery#16inChapter5foryourtune.Ifyouhaveyettocreateyourowntune,simplyselectasoundfilefromthelistinaSoundblock.

Touseasensortocontrolwhenaloopshouldstop,selectSensorintheControlbox,andthenselectthesensor(Ultrasonic)youwouldliketouseandtheport(4)towhichthesensorisconnected.SetthetriggervalueintheUntilboxtospecifyexactlywhentheloopshouldstop.Youcanseehowtomaketheseconfigurationsinthefollowingsampleprogram.

seeingthesensorsandtheloopblockinaction

Page 132: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

NowmaketheDiscovery-LoopprogramshowninFigure6-11.Whenyourunthisprogram,therobotshouldmovebackandforthrepeatedlyuntilthesensorspotssomethingcloserthan25cm(10inches).

Thisprogramdoesn’talwaysrespondtoobjectsvisiblewithin25cmoftherobotbecauseitpollsthesensoronlyonceperrepetition,justafteralltheblocksinsidetheloopcomplete.Forthisreason,whenyouquicklymoveyourhandinfrontoftherobotwhilethefirstblockisrunning,therobotwon’tnoticeyourhand.

Figure6-11:TheconfigurationoftheblocksintheDiscovery-Loopprogram

Page 133: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

sensorsandtheswitchblockYoucanuseSwitchblockstohavearobotmakedecisionsbasedonsensordata.Untilnow,yourrobotshavebeenpreprogrammed,meaningthateachtimeyouranaprogram,therobotwouldbehaveinthesameway.Switchblocksallowyourrobotstochoosewhattodobasedonasensorreading.Forexample,youcanmakeyourrobotmovebackwardiftheUltrasonicSensorseessomethingnearerthan50cm,oryoucanhaveitsay“Distance”ifthereisnoobjectcloserthan50cm,asshowninFigure6-12.

SimilartothequestionaskedinFigure6-12,therobotcheckswhetheragivencondition(astatement,suchas“Thesensorreadingislessthan50cm”)istrueorwhetheritisfalse,asshowninFigure6-13.

Figure6-12:ArobotcanmakedecisionsbasedontheUltrasonicSensorreading.

Page 134: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-13:TheSwitchblockcheckswhethertheconditionistrueorfalseandrunstheappropriateblocks.YouspecifytheconditioninthesettingsoftheSwitchblock.

TheSwitchblockinthisprogramcontainstwoblocksinseparatepartsoftheswitch;theswitchdecideswhichofthetwoblockstorun.Iftheconditionistrue,theblockintheupperpartoftheswitchisrun,andtherobotmovesbackward;iftheconditionisfalse,thelowerblockisrun,andyoushouldhearasound.

configuringaswitchblockFigure6-14showstheSwitchblock’sConfigurationPanel.BychangingtheSwitchblock’ssettings,youdefinethecondition(liketheoneinFigure6-13),andtheprogramwillcheckwhetherit’strue.Ifitistrue(thesensorreadingislessthan50cm),theupperblocksintheswitchshouldrun.Iftheconditionisfalse(thereadingis50orgreater),theblocksinthelowerpartoftheswitch

Page 135: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

shouldrun.YouselecttheSensoroptionintheControlboxtoindicatethatyouwantto

makeadecisionaboutasensorreading.IntheSensorbox,youselectthesensortopoll,whichistheUltrasonicSensorinthiscase.Ontherighthalfoftheblock’sConfigurationPanel,youspecifythecondition.Forexample,youcouldsettheblocktocheckwhetherthesensorseessomethingthat’sfartherawaythan25cm(10inches).

seeingtheswitchblockinactionTheDiscovery-Switchprogramthatyou’llnowcreatehastherobotdriveforwardforfourseconds.Then,iftherobotseessomethingcloserthan50cm,itgoesbackwardforashortwhile.Iftherobotdoesnotseeanobjectcloserthan50cm,Discoverywillsay“Error.”Finally,regardlessoftheSwitchblock’sdecision,therobotwillplayatone.

Figure6-14:TheConfigurationPanelofaSwitchblockconfiguredtopolltheUltrasonic

CreatetheprogramnowasshowninFigure6-15.

Page 136: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Runthisprogrammultipletimestodeterminewhenyoumustkeepyourhandinfrontofthesensortomaketherobotgobackward.DoingsoshoulddemonstratethatwhenyouusetheSwitchblockinyourprograms,therobotpollsthesensoronlyonceandcomparesthesensorvaluetothetriggervaluetoseewhethertheparticularconditionistrue.Inthisprogram,thesensorvalueismeasuredaftertherobotfinishesgoingforward(whentheMoveblockfinishes).

Page 137: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-15:TheDiscovery-Switchprogramhastherobotdecidewhatdobasedonasensorreading.

DISCOVERY#24:SEETHEDISTANCE!Difficulty:EasyLet’spracticewiththeSwitchblock!TrytocreateaprogramtoimplementthedecisiontreeshowninFigure6-16.HowdoyouconfiguretheSwitchblock,andwhydoyouhavetoputaWaitblockattheendoftheprogram?

Page 138: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-16:TheprogramflowforDiscovery#24

Wheneitherblockcordfinishesrunning,theprogramcontinues,andthenextSoundblockisactivatedtoplayatone.

addingblockstoaswitchblockThere’snolimittothenumberofblocksyoucanplaceinsideaSwitchblock.Ifonepartofaswitchhasmultipleblocks,they’resimplyrunonebyone,asshowninFigure6-17.YoucanalsoleaveoneofthetwopartsofaSwitchblockempty,asshowninthefigure.

Runthismodifiedprogramtoseewhathappens.Iftheconditionistrue(therobotseesyou),therobotshouldmovebackwardandsay“Error,”andtheprogramshouldcontinuebyplayingthetone.Iftheconditionisfalse(therobotdoesnotseeyou),theprogramshouldfindnoblocksinthelowerpartofthe

Page 139: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

switchandinstantlymoveontotheSoundblockaftertheswitch(blocke),whichplaysthetone.

usingtheflatviewoptionTheSwitchblock’sFlatViewoptionintheConfigurationPaneldisplaysthecompleteSwitchblockontheWorkArea.WhenyoumakelargeprogramscontainingSwitchblocks,it’seasytolosetrackofhowyourprogramactuallyworks.Insuchcases,unchecktheFlatViewcheckboxtodecreasethesizeoftheSwitchblock,asshowninFigure6-18.Bothpartsoftheswitcharestillintheprogram,butthey’reonseparatetabs,whichyoucanopenbyclickingthem.

Youwon’tneedtouseFlatViewoftenwithsmallerprograms,butasyoucontinuecreatingprogramsforyourrobotinthenextchapter,you’lllearnthatitcanbeusefultodisableFlatView,especiallywhenpartofaswitchcontainsnoprogrammingblocks.

Figure6-17:AmodifiedversionoftheDiscovery-Switchprogram.YoumoveSoundblockdformerlyinthelowerpartoftheswitch(whichrunswhentheconditionspecifiedintheSwitchblockisfalse)totheupperpartoftheswitch(whichrunswhentheconditionistrue).

Page 140: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-18:DecreasethesizeofaSwitchblockbydeselectingtheFlatViewoptioninitsConfigurationPanel.Thisoptionschangesyourviewoftheblockonly;itwon’taffectthewaytheprogramworks.

DISCOVERY#25:STOPORTURN?Difficulty:MediumInthisdiscovery,you’llcontinueworkingontheprogramthatyoumadeinDiscovery#24.Modifytheprogramtomakeitdonothingiftheconditionistrue(thesensorreadingisgreaterthan60cm),andiftheconditionisfalse,havetherobotturnaroundandthendrivebacktowhereitwaswhenyoustartedtheprogram.

repeatingswitchesSwitchblockspolltheUltrasonicSensoronceandcomparethemeasuredvaluetothetriggervalue.Then,dependingonhowaconditionisconfigured,blocksinthetrueorfalsepartoftheswitcharerun.

Tohavearobotmakedecisionsmorethanonce,youcandragaSwitchblockintoaLoopblock.Forexample,youcouldprogramarobottosay“Yes”whenitseessomethingcloserthan100cm(40inches)andsay“No”otherwise.IfyouplaceaSwitchblockwiththisconfigurationinaLoopblock,therobotwillcontinuetosay“Yes”and“No”basedonthesensorreading.

Page 141: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

willcontinuetosay“Yes”and“No”basedonthesensorreading.CreatetheDiscovery-RepeatprogramshowninFigure6-19now.

Page 142: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 143: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure6-19:TheconfigurationoftheblocksintheDiscovery-Repeatprogram

furtherexplorationRobotsusesensorstogatherinputfromtheirenvironments,andinresponsetothisinputyoucancreateanNXT-Gprogramtomakearobotdodifferentthings.Tomakeaprogramforarobotthatusessensors,youuseWait,Loop,andSwitchblocks,eachconfiguredtocontrolasensor.Yourchoiceswillbebasedonwhatyourprogramshoulddo.

You’vebeenusingonlytheUltrasonicSensorsofar,butyoucanusealltheprogrammingtechniquesyou’velearnedinthischapterwhenworkingwitheachoftheothersensors.InChapter7,you’llplaywiththeTouchSensorsandtheColorSensorandusethemintheDiscoveryrobot.

DISCOVERY#26:INTRUDERALARM!Difficulty:EasyCreateaprogramthatmakesabeepingalarmsoundwhensomeoneentersyourroom.UseaWaitblock(configuredasanUltrasonicSensor)tosenseanopeningdoor,andthenfollowitwithSoundblocksinaLoopblocktocreatethealarm.WhattriggervaluedoyouneedintheWaitblock?

DISCOVERY#27:ULTRASOUND!Difficulty:HardUseSwitchblockstodeterminethemeasureddistanceoftheUltrasonicSensor.Ifthedistanceis0cmto10cm,alowtoneshouldbeplayedwithaSoundblock.Ifthedistanceisbetween11cmand20cm,thetoneshouldbehigher,andsoon.HowdoyouconfiguretheSwitchblocks,andwheredoyouputeachoftheminyourprogram?

BUILDINGDISCOVERY#3:RAILROADCROSSING!AsinChapters4and5,attachathirdmotortotheDiscoveryrobot,andcontrolitwithaMoveblockthat’sconfiguredtocontrolthemotoronoutputportA.

Page 144: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Usethismotortomoveaself-madebarrierthatstopscarsfromcrossingtherailwayifatrainpasses.UsetheUltrasonicSensortospotwhenamodeltrainapproachesandwhenthebarriersshouldbelowered,aswellaswhentheyshouldberaisedagain.

Page 145: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

7

usingthetouch,color,androtationsensors

Chapter6showedyouhowtousetheUltrasonicSensor,togetherwiththeWait,Loop,andSwitchblocks,tomakeyourrobotinteractwithitsenvironment.Inthischapter,you’lllearnhowtousetheTouch,Color,andRotationSensors,aswellastheNXTbuttons.You’llusethesesensorstoallowtheDiscoveryrobottoavoidwallswithbumpers,followaline,playdifferentsoundsbasedonsensorreadings,andeventellyouwhichcoloritssensordetects.Onceyou’vefinishedthischapter,you’llbereadytobuildtwocoolrobotsthatusesensorsintheirownwayinChapters8and9.

You’llbeginbyupgradingDiscoverywithadualbumperattachmentthatusetwoTouchSensors,asshowninFigure7-1.

Page 146: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-1:DiscoverywithabumperattachmentthatusestwoTouchSensors

thetouchsensorTheTouchSensorcanmakeyourrobotfeelandrespondtoitsenvironmentbydetectingwhetheritsorangebuttonispressedornot(released).BycombiningthereadingsfromtheTouchSensorwith,forexample,aWaitblock,youcanmaketherobotrespondtoapressoftheTouchSensor,asshowninFigure7-2.Thesensorcanalsodetectwhetherit’sbumped,meaningthesensorwasquicklypressedandthenreleased.

YoucanuseTouchSensorsinmanydifferentways.Forexample,inthischapter,you’llusethemtocreatebumpersforyourrobotsothatitcanbackupandturnaroundwhenitstrikesanobstacle.InChapter8you’lluseTouchSensorstocreateremotecontrolbuttons,andinChapter9they’llactasantennasforananimalrobot.InChapter13you’llseehowtouseaTouchSensortoperformaspecificmechanicalfunction,suchasdetectingwhenagrabberhaslifteditsloadtothemaximumheight.

Page 147: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingthebumperattachmentwithtouchsensors

You’llnowcreateanextensionforyourDiscoveryrobotthatusestwoTouchSensorsasbumpers(Figure7-1)toallowyourrobottofeelobjectsthatitrunsinto.Onceitdetermineswhichbumperwaspushed,therobotwillbackupandturnawayfromthisobject.Createthebumpersnow,asshownintheinstructionsonthenextpages.

Figure7-2:TheTouchSensordetectsthreeactions:pressed,released,andbumped.

Page 148: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 149: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 150: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 151: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingthecablesNowconnectthecablesthatyou’vealreadyaddedtotheTouchSensorstotheNXT,asshowninFigure7-3.

FromnowonI’llrefertotheTouchSensorconnectedtoport1astheRightTouchSensorandtheTouchSensorconnectedtoport2astheLeftTouchSensor.

Page 152: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-3:ConnecttheTouchSensorstotheappropriateinputportsontheNXTwithlongcables.Topreventthecablesfromdraggingonthegroundorinterferingwiththewheels,wrapeachcablearoundamotor,asshownhere.

programmingwiththetouchsensorLet’slookattheConfigurationPanelsettingsthatarespecifictotheTouchSensor,asshowninFigure7-4.

UsethePortsettingtoselecttowhichportthesensorisconnected.UsetheActionsettingtocontrolwhichactionwilltriggerthesensor

(Pressed,Released,orBumped).Whentheactionoccurs,thisWaitblockstopspausingtheprogram.

creatingatestprogramforthetouchsensorTheDiscovery-Touchprogramyou’llcreateinthissectionwillmaketherobotplayasoundwhenyoupresstheRightTouchSensor.CreatetheprogramasshowninFigure7-5,runit,andthencreatemodifiedversionswitheachoftheothertwoActionsettings(ReleasedandBumped)soyoucanseehowtheywork.

Page 153: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-4:TheConfigurationPanelofaWaitblock,configuredtopollaTouchSensor.OntherighthalfofthepanelarethespecificsettingsfortheTouchSensor.TheConfigurationPanelsofLoopandSwitchblocksthatcontrolaTouchSensorcontainthesamesettings.

Figure7-5:ConfigurationoftheblocksintheDiscovery-Touchprogram

NOTE TheWaitblocksontheProgrammingPalettearebasicallyallthesame.ThedifferencebetweenthemisthateachblockhaspresetControlandSensorsettingstomakeprogrammingeasier.

avoidingwallswithtouchsensors

Page 154: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheDiscoveryrobotcaneasilyavoidwallswithitsUltrasonicSensor,butitcandothesamethingusingtheTouchSensors.Althoughitcan’tusetheTouchSensorstosenseobjectsfromadistance,ofcourse,itwillbeabletofeelsmallerobjectsthanitmightotherwisebeabletosensewiththeUltrasonicSensor.Anotheradvantageofthetwobumpersisthattheyallowtherobottodetermineinwhichdirectionitshouldturnafterrunningintosomething.

WhencreatingyourprogramtousetheTouchSensors,thefirstthingyouneedtodoistoswitchonthemotors.Next,youchecktoseewhetherasensorhasbeenpressed.IftheLeftTouchSensorispressed,Discoveryshouldbackup,turnright,andthencontinueitspath;iftheRightTouchSensorispressed,itshouldbackupandturnleft.Tofindoutwhichsensorispressed,you’lluseSwitchblocks.

ASwitchblockcanpollonlyonesensoratthetime,soyou’llstartbycheckingtoseewhethertheRightTouchSensorispressed.Ifitis,yougoleft.Ifit’snot,you’llseewhethertheLeftTouchSensorispressed.Ifitis,youturnright.Ifneithersensorispressed,youessentiallydonothingdifferentandkeepmovingforward.Alloftheseactionsanddecisionsrepeatcontinuously,asshownintheschematicoverviewoftheDiscovery-BumperprograminFigure7-6.

Figure7-6:AnoverviewoftheDiscovery-Bumperprogram.Iftheanswertothefirstquestionisyes,therobotturnsleft,butiftheanswerisno,anotherquestionisasked.TheprogrammingblocksthatyouusetomaketheseconddecisionareplacedinsidethelowerpartoftheSwitchblockthatyouusetomakethefirstdecision.

creatingthediscovery-bumperprogram

Page 155: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

You’llnowcreateawall-avoidanceprogram.First,createanewprogramcalledDiscovery-Bumper,andplaceandconfiguretheblocksasshowninFigure7-7andFigure7-8.

DISCOVERY#28:ONLYTWOISENOUGH!Difficulty:EasyCreateaprogramthatshowsahappyfaceonthedisplayonlyifyoupressbothbumperssimultaneously.Ifnoneoronlyonesensorispressed,asadfaceshouldbedisplayed.You’llneedtwoSwitchblockstoprogramthisbehavior.

DISCOVERY#29:SMARTDECISIONS!Difficulty:HardCanyoumakeawall-avoidanceprogramthatusesboththeTouchSensorsandtheUltrasonicSensor?ExpandtheDiscovery-BumperprogramwithanextraSwitchblocktodeterminewhethertheUltrasonicSensorseesanythingcloserthan20cm.WhereintheprogramdoyouplacethisSwitchblock?

Page 156: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-7:Step1:TheblocksshownhereturnthemotorsonandhandlethefirstdecisionwithaSwitchblock.ThecompletesequenceofblocksisplacedinsideaLoopblockconfiguredtoloopforever.

Page 157: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-8:Step2:TheblocksyouaddinthissteparerunwhentheRightTouchSensor(onport1)isnotpressed.Theblocksenabletherobottomaketheseconddecision.Ifneithersensorispressed,therobotdoesn’ttakeanyaction,anditreturnstothebeginningoftheprogramtoseewhetherasensorisbeingpressed.

Page 158: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-9:TheColorSensorcansensethecolorofsurfacessuchasthecolorofLEGObricks.Itcanidentifyblack,blue,green,yellow,red,andwhite.

thecolorsensorTheColorSensordetectsthecolorofasurface,thebrightnessofalightsource,andtheintensityoflightreflectedbyasurface.Figure7-9showstheColorSensorbeingusedtodetectthecolorofLEGObricks.Thecolorsensorcanalsoactasacoloredlamp,emittingabrightlightcoloredred,green,orblue.You’llusethecolorsensor’sabilitytoseecolorinthischapterandlearntouseitsotherfeaturesinChapters8and9.

BecausetheColorSensorhassomanyfunctions,it’susefulinmanyapplications.Forinstance,youcanuseittomakeavehiclefollowlines(Chapter7),asaColorLamptoindicatethatacertainactionistakingplace(Chapter8),asalightdetector(Chapters8and9),tosortcoloredLEGObricks(Chapter14),andevenasastabilizationsensor(Chapter15).

creatingthecolorsensorattachmentInthissection,you’llenhanceDiscoverybycreatingasubmodulewiththeColorSensor.Butbeforeyoudo,detachthebumpersbydisconnectingtheircablesandthegraypinsthatconnectthem.(Don’ttakethemapart,though;you’llneedthemforsomeofthediscoveriesattheendofthischapter.)

Onceyou’vecompletedtheColorSensorattachment,connectittoinputport3ontheNXTusingtheshortcable,asshowninFigure7-10.

Page 159: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 160: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-10:ConnectingtheColorSensortotheDiscoveryrobotusingtheshortcable

Figure7-11:TheplacementoftheDiscoveryrobotandtheColorSensorontheTestPad

usingtheviewmodetopollthecolorsensorTopolltheColorSensor,selectView▸Color▸Port3onyourNXT,placeyour

Page 161: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

robotontheTestPad,andpointthesensoratthecoloredline,asshowninFigure7-11.NoticehowthecolornamedisplayedontheNXTscreenchangesasyoumovethesensorovertheline.Thesensorcanrecognizesixcolorsthisway:black,blue,green,yellow,red,andwhite.

Figure7-12:TheConfigurationPanelofaWaitblockthatpollstheColorSensor

programmingwiththecolorsensorInthissection,you’llcreateprogramsfortheDiscoveryrobotthatusetheColorSensorwithWaitandSwitchblocks,justasyoudidwiththeUltrasonicandTouchSensors.Figure7-12showsaWaitblockthatpollstheColorSensoranditsConfigurationPanel.

InthePortarea,selecttheinputportthesensorisconnectedto(port3).IntheActionbox,chooseColorSensor.IntheUntilbox,specifywhatthesensorshouldseeinorderfortheWaitblocktostopwaiting,byselectingarangeofcolors,suchasgreenandyellowasshown.WithInsideRangeselected,the

Page 162: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

robotwillwaituntilthesensorreportsacolorthatiseithergreenoryellow.IfyouweretoselectOutsideRange,theblockwouldwaituntilthesensorspotssomethingthat’snotgreenoryellow.

stayinginsideacoloredlineYournextprogram,Discovery-Circle,willdemonstratehowyoucanusetheColorSensorasalinedetector.Onceyourprogramisloaded,you’llplacetheDiscoveryrobotinthecircleontheTestPadandhaveitdrivearoundwithoutleavingthecircle.Figure7-13showstheprogramflowforthisbehavior;Figure7-14showshowtocreatetheprogram.

Figure7-13:TheprogramflowoftheDiscovery-Circleprogram

Page 163: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-14:TheconfigurationoftheblocksintheDiscovery-Circleprogram.TheWaitblockisconfiguredtowaituntilthesensorseessomethingthatisblackasspecifiedintheUntilsetting(usingtheslidingbars).

BUILDINGDISCOVERY#4:CLEANTHATTESTPAD!WiththeDiscovery-Circleprogramtherobotconstantlymovesthroughthecircle.IfyouputsomeLEGOpiecesinthecircle(Figure7-15),yourrobotwill

Page 164: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

eventuallypushthemout,althoughbeforeitcandothat,youneedtogiveDiscoveryabulldozerblade.CanyoubuildsuchabladewithyourLEGOpieces?

Figure7-15:ThesetupforBuildingDiscovery#4:Usingabulldozerblade,Discoverycansweepthemessoutofthecircle.Canyoubuildit?

TIP ConnectthebulldozerbladetotheColorSensorattachment,andusetheDiscovery-Circleprogram.

DISCOVERY#30:TELLMEWHATYOUSEE!Difficulty:HardYoulearnedearlierthatyoucanusemultipleSwitchblocksinaprogramandthatthecolorsensorcandetectuptosixdifferentcolors.Canyoucreateaprogramthatwillmaketherobotsaythenameofthecoloritsees,usingsoundfiles?Tobegin,lookattheprogramflowschemeshowninFigure7-16,andthentestyourprogramusingthecoloredbarontheTestPad.Whenyou’reready,turntheentireseriesofblocks(exceptfortheLoopblock)intoaMyBlockcalledSayColor.

Page 165: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-16:Amodelforaprogramtomaketherobotsaywhichcoloritsees

followingalineInyournextproject,you’llusetheColorSensortocreatealine-followingrobot,whichmeanstherobotwillfollowacoloredtrackonamat,suchastheblacklineontheTestPad.Let’slookatthestrategybehindthisprogram.

Whenfollowingablacklineonawhitemat,therearealwaysonlytwopossibilities:thesensormeasureseitherwhiteorblack.Therefore,whencreatingaline-followingprogramforablack-and-whiteenvironment,you’lluseaSwitchblock,whichlooksforthecolorblack.Whenthesensorseesblack,theSwitchblockwilltriggeraMoveblocktoperformonemovement;ifitseesanothercolor(white),itwillperformadifferentmovement,asshowninFigure7-17.

IfDiscoveryseeswhite,itcannotdetermineonwhichsideofthelinethecolorlies,soyouneedtomakesureitwillalwaysstayononlyonesideoftheline;otherwise,itwillstrayoffthelineintothewhitearea.YoudothisbyalwaysdrivingDiscoveryrightwhenitseesblackandleftwhenitseeswhite.Figure7-18showstheline-followingprogram.

NOTE BesurewhenconfiguringtheMoveblocksnottodragtheSteeringsliderallthewaytotheright(inblockc)ortotheleft(inblockd),ortherobotwillturninplaceratherthanmovingforward.Also,besurethatbeforeyoustarttheprogram,youplacetherobotonthematsothatthesensorispointedattheline,withtheoutsideofthecircletotherobot’sright(seeFigure7-17a).

Page 166: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-17:Discoverysteersrightifitseestheblackline(a)andsteersleftifitseesthewhitearea(b).AsDiscoverysteers,itmovesforward,soifyourepeatthisbehavior,youendupwithaline-followingrobot.

Page 167: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure7-18:TheconfigurationoftheDiscovery-Lineprogram.NotethattheDurationsettingsintheMoveblocksaresettoUnlimited.Oncetherobotstartstoturn,itinstantlygoesbacktothebeginningoftheprogramtoseewhetheradifferentcolorhasbeendetectedorwhetheritshouldkeepturninginthesamedirection.UnlimitedMoveblocksjustswitchonthemotorsandhavetheprogramcontinue.

usingtheNXTbuttonsassensorsInadditiontotheUltrasonic,Color,andTouchSensors,theNXTcontainsitsownsensors:theNXTbuttons.YoucanuseboththeEnterandRightArrowandLeftArrowbuttonsontheNXTjustlikeyouuseTouchSensors.Forexample,youcanmaketherobotturnaroundifyoupresstheRightArrowbutton.

TousetheNXTbuttons,you’llconfigureaWait,Switch,orLoopblockset

Page 168: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

tocontrolasensorandselectNXTButtonsintheSensorbox.IntheButtonbox,choosetheEnterButton,RightButton,orLeftButton.Finally,intheActionbox,youchoosewhetherthebuttonshouldbepressed,released,orbumped,justaswiththeTouchSensor.Youcanseetheseconfigurationsinthenextsampleprogram.

Let’spracticeusingthesebuttonswiththeDiscovery-Buttonprogram,asshowninFigure7-19.Createthisprogramnow.

DISCOVERY#31:EXPERTLINEFOLLOWING!Difficulty:ExpertWhenyourantheDiscovery-Lineprogram,youmayhavenoticedthatDiscoveryactuallyfollowedtheoutsideedgeoftheline.Youcanmakeitfollowtheinsideedgeofthelinebyrunningtheprogramwhentherobotisonthelinebutwiththeinsideofthecircleontherobot’sright.Asitdoesso,itwillpassfourcoloredsquaresontheTestPadeachtimeitgoesaroundthecircle.Makesurethatitstopswhenitdetectsoneandsayswhichcoloritsees,andthenmakeitcontinuefollowingtheline.Whenfollowingtheinsideedge,yourrobotmighthaveproblemsfollowingtheline.Howcanyoumodifytheprogramtoresolvethis?

DISCOVERY#32:WHICHBUTTONDIDYOUPRESS?!Difficulty:MediumCreateaprogramthatsays“Left”whentheLeftArrowbuttonontheNXTispushedand“Right”whentheRightArrowbuttonispressed.IfyoupresstheEnterbutton,theNXTscreenshouldshowahappyfaceuntilyoureleasethebutton.

HINTUseSwitchblockstodeterminewhichNXTbuttonisbeingpressed,anduseaWaitblocktowaituntiltheEnterbuttonisreleased.

DISCOVERY#33:SOUNDBOT!Difficulty:MediumCreateaprogramthatenablesyoutoplaymusiconyourDiscovery.ProgramitsothateachbumperandNXTbuttontriggersadifferenttoneusingSwitchblockstodeterminewhichbuttonsarepressed.

Page 169: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

HINTYoucanmaketheprogramevenmoreinteractiveifyouimplementtheUltrasonicSensorinyourprogram.Howcanyouuseitasasoundtrigger?

Figure7-19:TheconfigurationoftheblocksintheDiscovery-Buttonprogram.Whenyourunthisprogram,therobotshouldturnrightwhenyoupresstheRightArrowbutton.

therotationsensorsWhenyoutelltherobottomoveforwardforthreerotationswiththeMoveblock,thevehicleknowsthatitshouldstopmovingwhenthewheelshaveeachmadethreerevolutions.TherobotknowsthisbecausetheRotationSensorineachNXTmotortellstheNXThowmuchthemotorshaveturned.

Youcanusetheinformationfromthissensorinyourprograms,for

Page 170: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

exampletocreateaprogramthatrepeatedlysays“Hello”untilyouturnonewheelbyhand.Thesensortellsyouhowmuch(eitherindegreesorrotations)amotorhasturnedsinceyoustartedtheprogram,aswellasinwhichdirectionthemotorturned,asshowninFigure7-20.

Figure7-20:TheRotationSensorinsidethemotortellstheNXTprogramhowmanydegreesorrotationstheorangepartofthemotorhasturnedsinceyouactivatedaprogramandinwhichdirection.Ifaprogramisrunningandyouspinthewheelaroundtwiceintheblackdirection,thesensorwillreporttworotations(or720degrees)intheforwarddirection.Ifyouthenturnithalfarotationinthegraydirection,thesensorreportsoneandahalfrotationsintheforwarddirection.

usingtheviewmodetopolltherotationsensorYoucanusethemotor’sRotationSensorsinyourprogramslikenormalsensors,butsincetheyareinsidetheNXTmotors,theyarealwaysconnectedtooutputports.

TousetheViewmodeontheNXTtoreadthesensorvaluereportedbyaRotationSensor,turnontheNXT,selectView,chooseMotorDegrees,andthenselectportBorC.Now,asyourotatethemotorthatyouselectedbyhand,thevalueonthedisplayshouldchange.Positivedegreevaluesmeanthatyouturnedthewheelforward,andnegativeonesrepresentreverserotations.InsteadofMotorDegrees,youcanselectMotorRotationstomaketheNXTscreen

Page 171: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

showhowmanycompleterevolutionsthewheelhasmade.

DISCOVERY#34:CIRCLINGDEGREES!Difficulty:EasyDoyourememberhowyoutriedtomakeyourrobotdoanaccurate90-degreeturninChapter4?ThequestionwashowmanydegreesyouhadtoenterintheMoveblock’sDurationsettingtoaccomplishthisturn.You’vejustlearnedhowtomeasurehowmanydegreesthewheelshaveturned.NowgotoViewmode,polltheRotationSensoronportB,andmanuallyturntherobotinplacefor90degreesbyslowlyrotatingeachwheel.UsethevaluethatappearsontheNXTdisplay,andenteritinaMoveblock’sDurationsetting.Wasyourmeasurementaccurate?

makingprogramswithrotationsensorsAsyou’veseeninthischapter,youcanuseWait,Loop,andSwitchblockstocontrolaRotationSensor.Forinstance,aprogramwithaLoopblockcanrepeatedlysay“Hello”untilthemotoronportBhasturned180degreesintheforwarddirection.TheboxesintherighthalfoftheConfigurationPanelareusedtoconfigurethesensor,asshowninFigure7-21,andyouusethePortboxtoselecttowhichoutputportthemotoryouwanttopollisconnected.(You’lllearnmoreabouttheResetfunctionintheActionboxin“ResettingtheRotationSensor”onpage84.)

IntheUntilboxyouconfigurethetriggervalue(theconditionthatmakesaLoopblockstoplooping)byusingtheorangearrowstospecifywhetheritshouldlookforforwardorbackwardrotation.Selectanumberofdegreesorrotations,aswellaswhetherthesensorreadingshouldbegreater(>)orless(<)thanthisnumberinordertotriggertheblockandmaketheLoopblockstopLooping.

NowcreatethesampleprogramDiscovery-RotationshowninFigure7-21toperformthebehaviordescribed.

NOTE ThelistofsensorsintheWait,Loop,andSwitchblocksmaycontainbothRotationSensorand!RotationSensor.The!RotationSensoristhereforcompatibilitywitholderversionsoftheNXT-Gsoftware,butyou’llalwaysusetheRotationSensoroption(theonewithouttheexclamationpoint)inthisbook.

Page 172: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

resettingtherotationsensorAsaprogramruns,theRotationSensorvaluechangesasyouturnamotorbyhandorifaMoveblockmakestherobotmove.Sometimes,though,itisusefultoresetthisvaluetozero.Forexample,youmightwanttomodifytheDiscovery-Rotationprogramtoresetthesensorafteritconfirmsthatthemotorhasturned180degrees.WithaLoopblockandtheActionsettingspecifiedtoRead,theRotationSensorwillrepeattheblocksinituntilthetriggervalueisreached.WhenResetisselected,thesensorvalueisresettozeroaftereachloop.Therefore,aLoopblockwiththissettingstopsonlyifthetriggervalueisreachedduringoneloop.

Figure7-21:TheconfigurationoftheblocksintheDiscovery-Rotationprogram.ExperimentwiththissensorbychangingthesettingsintheUntilboxoftheLoopblocktoseewhateachsettingreallydoes.

Page 173: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DISCOVERY#35:ROTATIONALMUSIC!Difficulty:MediumTheprogramshowninFigure7-22playsdifferenttonesdependingonhowtheleftandrightwheelsofDiscoveryarerotated.Ifawheelisturnedforward,therobotplaysadifferenttonethanwhenitisturnedbackward.Canyoufigureouthowthisprogramworksandhowitisconfigured?

HINTThehiddentabsoftheSwitchblocksalsocontainSoundblocks.

Figure7-22:Canyoure-createtheprogramshownhere?Howdoyouthinktheblocksshouldbeconfiguredtomaketherobotplayfourdifferenttonesdependingonhowthewheelshaveturned?

NowmodifytheDiscovery-Rotationprogram.ChangetheActionsettingtoReset,andrunthemodifiedprogramtoseehowthisworks.

NOTE IfyouselectResetinaSwitchblock,thevalueisresettozeroafterthesensorvalueiscomparedtothetriggervalue.YoucannotresetthesensorvaluewithaWaitblock.

Page 174: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

furtherexplorationNowthatyou’velearnedhowtoworkwiththeNXTsensors,youshouldbeabletocreaterobotsthatinteractwiththeirenvironments.Discoveryis,ofcourse,onlyoneexample.Asyoucontinuereadingthisbook,you’llbuildseveralrobotswithsensors,eachofwhichwillusesensorsdifferently.

Bynowyou’velearnedtousethecomponentsthatareessentialtocreateaworkingrobot:theNXT,themotors,thesensors,andtheNXT-Gsoftware.Thefollowingchapterswillexploreeachofthesesubjectsinmoredetailsothatyou’llbeabletocreateincreasinglysophisticated(andfun!)robots.

Thefollowingdiscoverieswillhelpyouexploremorepossibilitieswiththesensors.Besuretopostyourideasandsolutionstothebook’scompanionwebsite(http://www.discovery.laurensvalk.com/)!

DISCOVERY#36:COLORTHEBALL!Difficulty:HardForthisdiscoveryyou’llhavetodisassembletheColorSensorattachmentsothatyoucanmountthesensorelsewhereontherobot.Connectthesensorsothatitlooksupward.TheNXT2.0roboticskitcomeswithasetofsmallcoloredballs;ifyouholdoneinfrontoftheColorSensor,thesensorshouldbeabletoidentifythecoloroftheball.CanyouprogramtheDiscoveryrobottoperformdifferentactionssuchasmovingandmakingsoundswhenitseesthesecoloredballs?

DISCOVERY#37:ULTRASONICLINEFOLLOWING!Difficulty:ExpertYouusedtheDiscovery-LineprogramtofollowtheblacklineontheTestPad,butyoucanhaveyourprogramdomorethanonethingatthetime.PlaceabookuprightsomewherealongthelineontheTestPad,andthenexpandtheprogramtofollowthelineuntiltheUltrasonicSensorspotsthebook.WhenDiscoveryspotsthebook,itshouldturnaroundandfollowthelineagain,butintheotherdirection.

HINTInsteadofaLoopblockconfiguredtoloopforever,configureittoloopuntilitseesthebook.Howdoyouturnaroundtofollowthelinein

Page 175: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

theotherdirection?

BUILDINGDISCOVERY#5:AUTOMATICHOUSE!LongbeforeyougottheLEGOMINDSTORMSNXT2.0roboticskit,youmighthavebuilthousesfromregularLEGObricks.Nowthatyouknowhowtoworkwithmotors,howtousesensors,andhowtomakeworkingprograms,howabouttryingtobuildarobotizedhousewiththeNXT?

IDEASUsemotorstoautomaticallyopenthedoorwhensomeonepressesthedoorbell(theTouchSensor),andsetanintruderalarmthatsoundswhentheUltrasonicSensorseessomeone.UseanothermotortocloseandopentheshutterswhenyouholdacoloredballinfrontoftheColorSensor.

Page 176: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

8

shot-roller:aroboticdefensesystem

Nowthatyou’velearnedhowtocontrolmotors,usesensors,andprogramtheNXT,youcanbeginmakingmorecomplexmachines.ThischapterwillshowyouhowtobuildandprogramtheShot-Roller(Figure8-1).Thisthree-wheeledconstructioncanshootballsinanydirection.

NOTE EnjoytheShot-Roller,butremembertonevershootatpeople!Aslongasyourespectthesafetyofothers,thisisnotadangerousrobot.

TheShot-Rollercanoperateineitherautonomousorremote-controlmode.Inautonomousmode,itdoeseverythingbyitself.YoucanprogramittolookaroundandshootattargetsdetectedbytheUltrasonicSensorortorespondtolightsignalsusingtheColorSensor.Inremote-controlmode,youusetwoTouchsensorstocompletelycontroltherobot’sactions.Thesensorsareusedasbuttonstoactivatetheshooter’smovements.

UnliketheExplorerandtheDiscoveryrobotsthatyoubuiltearlierinthisbook,theShot-Rollerusesthreemotors,asyoucanseeinFigure8-1.TheTurnmotorenablestherobottospinaroundinordertolookfortargets;theTurretmotormovestheturretupanddown;andtheFiringmotoristheshooter,whichcanshootballsathighspeed.Thecombinationofthesethreemotorsallowstherobottofireinanydirection!

Page 177: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-1:TheShot-Roller

InadditiontobuildingtheShot-Roller,you’lllearnsomenewprogrammingtechniques.You’llalsogettousesomenewprogrammingblockssuchastheColorLampblockandtheMotorblock.

buildingtheshot-rollerNowthatyou’velearnedabitaboutShot-Roller’sfunctionality,you’rereadytobuildit.Todoso,followthedirectionsonthenextpages,butfirstselectthe

Page 178: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

piecesyouneedasshowninFigure8-2.

Figure8-2:TherequiredpiecestobuildtheShot-Roller

Page 179: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 180: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 181: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 182: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 183: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 184: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 185: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 186: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 187: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 188: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 189: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 190: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 191: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 192: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 193: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 194: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingthecablesConnectthesensorsandmotorstotheNXTbrickaccordingtoTable8-1,makingsurethattheydonotinterferewiththewheels.OnewaytoaccomplishthatistowindthecablesaroundseveralLEGOpiecesontherobot.

Makesurethatyourrobotcanturnaroundsmoothlyandmovetheturretupanddowneasily,withouthavingthecablesblockingthesemovements.Checkthisbymovingtheturretandthewheelswithyourhands.

table8-1:cableplacementfortheshot-roller

Page 195: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Frommotor/sensor

ToNXTbrickport

Cablelength

Turretmotor OutputportA Medium(35cm/15inches)

Turnmotor OutputportB Medium

Firingmotor OutputportC Medium

ColorSensor Inputport3 Medium

UltrasonicSensor

Inputport4 Short(20cm/8inches)

Figure8-3:TheCompletePalette.Toopenthispalette,selecttheappropriatetabatthebottomofit.Hoveryourmousepointeroverthecolorediconstoseetheprogrammingblocksineachcategory.

programmingtheshot-rollerBeforeyouprogramyourrobot,let’slookatsomenewprogrammingblocks

Page 196: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Beforeyouprogramyourrobot,let’slookatsomenewprogrammingblocksthatyou’llneedforyourprograms.

thecompletepaletteTheNXTsoftwarehasthreedifferentProgrammingPalettes.Sofar,you’veusedonlytheCommonPalette(formostblockssofar)andtheCustomPalette(fortheMyBlocks).Nowyou’llusetheCompletePalette,asshowninFigure8-3.ThispalettecontainsallblocksthatcanbeusedinanNXTprogram,exceptfortheMyBlocksthatyoucreateyourself.

EachcolorediconontheCompletePaletterepresentsacertaintypeofblockinthecategoriesCommon,Action,Sensor,Flow,Data,andAdvancedblocks.*CommonblocksaretheblocksfromtheCommonPalette.TheCommonblocksarejustacollectionoffrequentlyusedblocks.SinceblockssuchastheDisplayblockandtheSoundblockareActionblocks,you’llalsofindthemamongthiscategory;thereisnodifferencebetweentheSoundblockintheCommoncategoryandtheSoundblockintheActioncategory.

*Actionblocksareblockstomaketherobotperformanaction,suchasturningmotors,playingasound,ordisplayingalineoftextontheNXTscreen.

*Sensorblocks(coloredyellow)areblockstoreadvaluesfromsensorsforuseinyourprograms.Theseblocksdifferfromtheblocksthatyou’veusedsofartopollsensors,suchastheorangeWaitblock.(I’llshowyouhowtousetheyellowSensorblocksinChapter10.)

*Flowblocks(liketheWaitblock)aretypicallyusedtochangeaprogram’sflow.Forinstance,someblocksmayneedtoberepeated(withaLoopblock),oradecisionmayneedtobemade(withaSwitchblock).

I’lldiscusssomeoftheDataandAdvancedblockslaterinthisbook.

thecolorlampblockInChapter7youlearnedthatyoucanusetheColorSensortodeterminethecolorofasurface,butyoucanalsouseitasared,green,orbluelamp.Touseitasalamp,youusetheColorLampblockintheActionblocks.

TousetheColorLampblock,opentheConfigurationPanel,selecttheportit’sconnectedto,thenchoosewhethertoturnthelamponoroff(intheActionbox),andfinallysetthecolorofthelamp.

Page 197: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Let’screateaprogramthatturnsthesensorintoadiscolampthatquicklyflashesdifferentcolors.StartanewprogramcalledTestColorLamp,andplaceandconfigurefourblocksinitasshowninFigure8-4.

Page 198: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-4:TheconfigurationoftheblocksintheTestColorLampprogram

WhenyourunTestColorLamp,youshouldseecoloredflashescomingfromthesensor.Youseethiseffectbecauseyoudon’tuseaWaitblocktotelltheprogramtopause.ImmediatelyafterthefirstColorLampblockinstructsthesensortodisplayaredlight,thesecondblockrequestsabluelightandthenagreenlight.ThissequenceisrepeatedoverandoverwiththeLoopblock.

DISCOVERY#38:ACOLOREDVOICE!Difficulty:EasyCanyoumaketherobotsaywhichlampcoloristurnedon?ExpandtheTestColorLampprogramwiththreeSoundblocks.HowdoyouconfiguretheWaitforCompletionoptionintheSoundblocks?

themotorblockLiketheMoveblock,theMotorblockintheActionblockscontrolsamotor.TheimportantdifferencebetweenthetwoisthattheMotorblockhasextrafeaturesforcontrollingindividualmotors,whiletheMoveblockisperfectforvehicleswithtwowheelsliketheDiscoveryweusedinearlierchapters.BecausetheShot-Rollerusesthreemotors,eachforadifferentfunctionintherobot,you’lluseMotorblockstocontrolthemindividually.

SomeoftheconfigurationsinaMotorblockarethesameasthoseinaMoveblock.Forinstance,youcanusetheMotorblock’sConfigurationPaneltoselecttowhichoutputportthemotorisconnected,inwhichdirectionthemotorshouldturn,themotorpower,andthetimeofrotation(Duration);youcanalsotelltherobotwhattodowhenthemotorfinishesrotating(NextAction).

usingthecontrolmotorpoweroptionOneuniquesettingintheMotorblockistheControlMotorPoweroption.Normally,whenyousetamotortomoveatacertainpowerlevel(suchas50),

Page 199: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

themotorturnsmoreslowlywhenyoutrytostopitwithyourhandsbecausethepowertothemotorstaysconstant.However,whenyouusetheControlMotorPoweroption,theNXTwillautomaticallyapplymorepowertothemotorwhenthere’saloadonitsothatthemotorcontinuesturningataconstantspeed.YoucanseeaMotorblockwithitsConfigurationPanelinthefollowingsampleprogram.

ToillustratetheControlMotorPowersetting,you’llshoottwoballswiththeShot-Roller’sFiringMotor.Toshootaball,themotorhastomakeonefullrotation.You’lllaunchthefirstballwithaMotorblockspecifiedtocontrolthemotorpowerandwiththesecondonewithoutthepowercontrol,asshowninFigure8-5.

Whenyouruntheprogram,thefirstballshouldbereleasedathighspeedbecausethemotorpoweriscontrolled,whilethesecondballisstuckintheballmagazine:thereisnotenoughpowertopushitout.

Page 200: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-5:TheconfigurationoftheblocksintheMotorControlTestprogram

DISCOVERY#39:AMOTORBLOCKTASK!Difficulty:EasyBeforecreatingbigprogramsforarobot,itisgoodtotesttherobot’smechanicalfunctionstogiveyouabetterunderstandingofhowtheyworkandtomakeiteasiertolocalizeproblems.Forexample,ifrunningtheTurnmotordoesn’tmaketherobotturn,someLEGOpieceswereprobablymisalignedwhileconstructingtherobot.Createaprogramthatmakeseachmotoronthe

Page 201: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Shot-Rollerrobotmoveforwardandthenbackwardforawhile.Trydifferentmotorspeeds,andtesttheControlMotorPowerfunction.NotethattheTurretmotorcannotspininfinitely,sobecarefulwhenconfiguringitsblock.

NOTE It’snotalwaysobviousinwhichdirectionamotorhastoturninordertomakeacertainmovement.Forexample,toraisetheturretinthisrobot,motorAhastoturnbackward.Thedirectiondependsonboththeorientationofthemotorsandthegearsinyourrobot.Todeterminethedirectionyourmotorsneedtoturninorderforyourrobottomakeacertainmovement,simplytrybothdirectionsusingasmalltestprogramwithoneMotorblock.

autonomousmodeNowthatyouknowhowtousetheMotorandColorLampblocks,youcanstartmakingbetterprogramsfortheShot-Roller!You’llbeginbycreatingsomeprogramsthatmaketherobotdoeverythingbyitself,withoutyourhelp.Inthisautonomousmode,theNXTcontrolsthemotorsandtherobot’sactionsbasedontherunningprogramandinputfromthesensors.

Inyournextprogram,you’llusetheColorSensorasaColorLamp,soineffect,theonlyrealsensoryou’lluseistheUltrasonicSensor.YourprogramwillinstructtheShot-Rollertoturnaroundwhilelookingfortargets.Iftherobotseesatarget,itwillraisetheturret.Ifthetargetiscloserthan25cm(10inches),itwillfiretwoballs;otherwise,itwillfirejustone.Oncetheballshavebeenfired,therobotlowersitsturret,andtherobotreturnstothebeginningoftheprogram,lookingfortargetsagain.TheColorLampindicatesthestateoftheshooter:scanningfortargets(bluelight),aimingwiththeturret(greenlight),andfiring(redlight).

NOTE Beforestartingtheprogram,makesurethattheshooterisparalleltotheground.

creatingtheprogramCreateanewprogramcalledShot-Roller-Autonomous,andthenfollowtheinstructionsinFigures8-6through8-10.

Page 202: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-6:Step1:YoumaketheTurnmotormovebyactivatingmotorBwiththeDurationoptionsettoUnlimited.AstheShot-Rollerturnsright,aWaitblockmakestheUltrasonicSensorlookfortargetsinsight.Oncetherobotseesatargetcloserthan45cm(18inches),motorBisturnedoff,andtheturretisraisedbyspinningmotorAbackward.

NOTE Inadditiontothenewlyplacedprogrammingblocks,Figure8-7

Page 203: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

alsoshowssomeoftheblocksplacedpreviously.Youdon’tneedtoconfiguretheseblocksagain;theyjusthelpyouseewheretoputthenewblock.Youmayalsoseesuchblocksfrompreviousstepsinotherfiguresinthisbook.

Figure8-7:Step2:TheWaitblockinstep1waiteduntilthesensorsawsomethingcloserthan45cm,butitcouldn’tdetermineexactlyhowcloseatargetwas.Tofindout,youuseaSwitchblock.Ifthedetectedobjectiscloser

Page 204: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

than25cm(10inches),youshoottwoballs,andjustoneotherwise.

NOTE WhenyoupickaWaitblockfromtheProgrammingPalette(amongtheFlowblocks),itisbydefaultconfiguredtopolltheTouchSensor.Tomakeitwaitforacertainnumberofseconds,settheControlboxtoTime(Figure8-8).

Figure8-8:Step3:Aftertherobotshootstheballs,itwaitsforhalfasecond,lowerstheturret,turnsslightly,andthenstartsthewholeprogramoveragain—alltokeepitfromshootingatthesametargetrepeatedly.

Figure8-9:Step4:YouuseaLoopblocktorepeatthesequenceofblocksbyplacingaLoopblockatthestartofyourprogram(beforeblock1a)andthenselectingtherestoftheblocksanddraggingthemintotheLoopblock.Theresultistheprogramshowninthisfigure.

Page 205: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-10:Step5:Finally,youinserttheColorLampblockstoindicatethestateoftheshooterasshown,andyouconfiguretheColorsettingineachblock’sConfigurationPanelasindicated.Thisfigureshowsthefinalprogram.

Congratulations!You’vefinishedcreatingtheprogram.NowyoucandownloadittotheShot-Rollerandrunit!

DISCOVERY#40:DANGEROUSINTRUDERALARM!Difficulty:MediumCreateaprogramtoturntheShot-Rollerintoanintruderalarm.UsetheUltrasonicSensortosensewhenthedooropens.Oncethedooropens,thealarmshouldnotgooffjustyet,becausetheintruderwouldstillbetoofarawaytobehitbyoneoftheShot-Rollersballs.AfteraWaitblockpausestheprogramforafewseconds,theShot-Rollershouldfireballsquickly,whilemakingloudsoundsusingSoundblocksonaParallelSequenceBeam.

lightsensormodeInadditiontousingtheColorSensorasacolordetectorandacoloredlamp,youcanuseittomeasurethelightintensityinaparticulararea.Forexample,itcanmeasurethedifferencebetweenbrightareascoveredinsunlightandadarkcloset.Thesensorvaluesrangefrom0to100.Asensorvalueof0saysthatthesensorseesnolight,whileavalueof100indicatesthatitseesverybrightlight.YoucanseethesettingsofaWaitblockconfiguredtopolltheColorSensorinLightSensormodeinFigure8-11.

UsetheUntilboxtospecifywhichvaluethesensorshouldmeasureinorderfortheWaitblocktostopwaiting.Theblockthatyouseeherewaitsuntilthesensorreportsalightvaluebrighter(greater)than50.

Whenmeasuringlightintensity,youcanchoosetoturnontheColorLampbyselectingtheLightcheckboxintheFunctionboxandspecifyingthecolor

Page 206: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

youwanttosee.

Figure8-11:TheconfigurationofaWaitblockpollingtheLightSensor.Toconfigureit,pickaWaitblockfromtheProgrammingPalette,selectColorSensorfromthelistofsensors,andthenselectLightSensorintheActionbox.

defendingaterritorywiththeshot-rollerThenextprogramneedsadarkroom,suchasawindowlessbathroomwiththelightsturnedoff.Onceyou’veprogrammedtheShot-Roller,putitinthisroom,andyou’llhave30secondstoleavetheroomandtocarefullyclosethedoor.Aloneinitsdarkenedroom,theColorSensor’smeasureoflightintensityshouldbeatorcloseto0.Nowifyouopenthedoor,andoncethemeasuredvalueexceeds5(thetriggervalue),theShot-Rollerrobotnoticesthatsomeonehasopenedthedoorandwilldefenditsterritoryusingitsshooter.(Don’tforgettoclosethetoiletlid!)

StartanewprogramcalledShot-Roller-Light,andthenplaceandconfiguretheblocksasshowninFigure8-12.

NOTE WhenIrefertotheLightSensor,ortheLightSensorvalue,I’mactuallyreferringtotheColorSensorfunctioninginLightSensormode.WhenusingaprogrammingblocktocontroltheLightSensor,firstselectColorSensorfromthelistofsensors,andthenspecifythatyouwanttousetheLightSensorfunctionintheActionparameteroftheConfigurationPanel.Inotherwords,don’tselectLightSensorinthesensorlist,becausethat’sanoldersensorthat’snotincludedinthe2.0kit.

Page 207: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-12:TheconfigurationoftheblocksintheShot-Roller-Lightprogram

troubleshootingyourprogramIfyourrobotdoesn’truntheprogramasexpected,thetriggervalueof5inWaitblockemaybetoolow;theroommaynotbecompletelydark.Tryahighertriggervalue,suchas10.(You’lllearnaboutamoresolidsolutiontothisprobleminChapter9.)

remote-controlmodeInautonomousmode,therobothandlesalltheactionsitself,butitisalsofuntocontrolamachineliketheShot-Rollerremotely.InChapter3,yousawthatNXT-Ghasabuilt-infunctiontocontrolrobotsremotely,butit’ssuitableonlyforvehiclesliketheExplorer.Therefore,you’llcreateaprogramthatrespondstotheremotethatyou’lluse:twoTouchSensorsconnectedtoinputports1and2ontheNXTwithlongcables,asshowninFigure8-13.

Page 208: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

You’llusetheTouchSensoronport1tocontroltheTurnmotorandthesensoronport2tocontroltheTurretmotor.Whenyoupressbothbuttonsatthesametime,you’llmaketheShot-Rollerfireaball.EachofthesethreecontrolactionsareplacedonaseparateSequenceBeam.ButhowdoyoucontroltheTurnmotorandtheTurretmotorwithjustonebuttoneach?

DISCOVERY#41:COMBININGSENSORPOWER!Difficulty:HardNowthatyou’vemasteredthetechniquestocontroltheShot-Roller,itisyourturntobecreative.MakeaprogramthatusesboththeLightSensorandtheUltrasonicSensortodetectintruders,andusemultipleSwitchblockstodeterminewhichsensorhasbeentriggered.Forinstance,youcouldmakeaShot-Rollerthatshootsonlywhenthereisanintruderatnight:TheLightSensordetectsdarkness,andtheUltrasonicSensordetectstheintrusion.UseSoundandDisplayblockstodescribethesensorvalues.Forexample,youcouldmakeyourrobotsay“Dark”astheLightSensorvaluedropsbelow20.Postyourprogramtothecompanionwebsitetoshowotherswhatyou’vemade!

Page 209: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-13:TwoTouchSensorsareusedtocontroltheShot-Rollerremotely.

Youcansolvethisproblemasfollows:ThefirsttimeyoupressaTouchSensor,thecontrolledmotormovesforwarduntilyoureleasethebutton.Then,whenyoupressthebuttonagain,themotormovesbackwarduntilyoureleasethebutton.Thenexttimeyoupressthebutton,themotorspinsforwardagain,andsoon.

BecauseyouwanttobeabletousetheTurretandTurnmotorssimultaneously,youplacetheblockstohandlethesemotorsontwoseparateSequenceBeamssothattheycanrunatthesametime.

CreatetheShot-Roller-RemoteprogramasshowninFigures8-14to8-20.

Page 210: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-14:Step1:WhenyoupresstheTouchSensoronport1,theTurnmotormovesforward,andtheShot-Rollerspinstotheright.Whenyoustoppressingthesensor,aMotorblockmakesthemotorstop.

Page 211: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-15:Step2:Theseblocksworkliketheonesplacedinstep1,exceptthattheymaketheTurnmotorspinbackward,causingtheShot-Rollertoturnleft.

Page 212: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-16:Step3:PlaceaLoopblockontheWorkArea,andthenselectalltheotherblocksanddragthemintotheloop.BecauseoftheLoopblock,theprogramwillrepeatedlywaitforbuttonpressesandthereforerepeatedlycontroltheTurnmotorbasedonthisinput.

Figure8-17:Step4:SelecttheLoopblockthatyouplacedinstep3,andthenpresstheCopybuttonandthenthePastebuttononthetoolbartoduplicatetheloopandtheblocksinit.Dragthenewlooptothepositionshowninthefigure,andthenconnectthenewblockstothemainprogramasshownhere.

Page 213: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-18:Step4(continued):TheblocksyoujustcopiedwillbeusedtocontroltheTurretmotor(outputportA)withtheTouchSensoroninputport2.Therefore,youchangetheConfigurationPanelsoftheWaitblockstowaitforbuttonpressesoftheTouchSensoronport2,andyouchangetheMotorblockstocontroltheTurretmotor(portA).YourWorkAreashouldlookliketheoneshownhere.

Finally,youneedtoprogramtherobottoshootwhenbothTouchSensorsarepressedsimultaneously.Todoso,you’llusetwoSwitchblocks,eachconfiguredtocheckwhetherasensorispressed.Whenbothsensorsarepressed,theTurretandTurnmotorsareswitchedoff,andtheFiringmotorshootsuntilyoureleasetheTouchSensors.

TheSwitchblocksaredisplayedincompactmode(FlatViewisnotcheckedintheConfigurationPanels)tomaketheprogramsmorereadable.TherearenoblockshiddeninthefalseconditiontabsoftheswitchesbecauseinthispartoftheprogramnoactionistakenwhenoneoftheTouchSensorsisnotpressed.

ThetwoswitchesareplacedinsideaLoopblocksothattherobotcontinuouslycheckstoseewhetherbothsensorsarepressed.Becausetherobotneedstoperformthischeckconstantly,youplacetheblocksthatcontroltheFiringMotoronaParallelSequenceBeam.

Page 214: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure8-19:Step5:PlaceandconfigureaLoopblockandtwoSwitchblocks

Page 215: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

asshown,andthenconnecttheblockstothemainprogrambyconnectingtheSequenceBeams,asyoudidinstep4.BecausethisisthesecondParallelBeam,holdtheSHIFTkeywhilemakingtheconnection.

Figure8-20:Step6:PlaceandconfigurethreeMotorblocksasshown.TheseblocksarerunwhentheconditionofbothSwitchblocksistrue;inotherwords,whenbothTouchSensorsarepressed.TheTurnandTurretmotorsareturnedoff,andtheFiringmotorstartstofireballs.

Congratulations,youfinishedcreatingtheremote-controlprogram!DownloadtheprogramtotheShot-Roller,andhavefun!

Page 216: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

furtherexplorationInthischapter,youhadachancetobuild,program,andplaywithaprebuiltrobot.Thisis,ofcourse,alotoffun,butitisevenmorefuntocreateyourownrobotdesigns.Forexample,youcouldtaketheshooterfromthisrobotandmountitonyourself-builtcarortank,oryoucouldturnitintoadangerouscreature,suchasaball-shootinginsect.Don’tworryifyoudon’tsucceedonthefirsttry;youwillgainmoreandmorebuildingexperienceasyoucontinuetotrynewdesigns.

DISCOVERY#42:RESEARCHWITHTHENXT!Difficulty:MediumHowfarcantheShot-Rollershoot?ThedistancethataballtravelswilldependontheanglethattheTurretmotormakeswiththeground.Whichanglemakestheballgothefarthest?Canyoumakeitgoevenfartherbymodifyingtheshooter?Investigatetheeffectthattheturretangleandthemotorspeedhaveonthedistanceofthefiredball.Postyourfindingsonthebook’scompanionwebsite(http://www.discovery.laurensvalk.com/)!

BUILDINGDISCOVERY#6:LOOKBEFOREYOUSHOOT!

CanyoumodifytheShot-RollerdesigntomounttheUltrasonicSensorontheturret,justbelowtheballmagazine?Thisway,notonlycanyoushootinanydirection,butyoucanalsolookinanydirectionsothattheShot-Rollerhasabetterviewofitstargets.

BUILDINGDISCOVERY#7:CATAPULT!TheShot-Roller’sshootingmechanismmakesiteasytolaunchtheballsintheNXTroboticskit,butitwon’tletyoufireotherLEGOparts.CanyoumakeaconstructionlikeacatapultthatfiresLEGOpieceswhenitseesyou?

HINTThinkofhowyouwouldmakeacatapultoutofsomethingotherthanLEGO.Youmightuserubberbandstolaunchsomethingoraplasticspoonthatyoubendwithyourhands.Buildsuchamechanismwiththe

Page 217: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

MINDSTORMSsystem,anduseanNXTmotorto,forexample,releasetherubberbandorthespooninordertolaunchsomethingwhentherobotseesyou.Whenusingrubberbands,useonesotherthanthosefoundintheNXT2.0kit,oryou’lllikelybreakthem.

Page 218: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

9

strider:thesix-leggedwalkingcreature

Youcanmakeinterestingmodelsthatmoveonwheels,butitisalsopossibletomakerobotsthatwalk.Suchcreationsareslightlymorechallengingtomake,butinthischapteryou’llfindinstructionstobuildStrider,asix-leggedwalkingcreature,asshowninFigure9-1.Onceyoufinishbuildingit,you’llprogramittowalkaroundandrespondtohumaninteraction.

Figure9-1:Strider

Page 219: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheStriderrobotusesthreeidenticalmotorassembliestowalk,eachofwhichcontrolsonepairoflegs.Thelegmodulesareinterconnectedwithatriangle-shapedframe,whichalsocarriestheNXTwithseveralsensorsattached.TwoTouchSensorsontheStrideractlikeantennas,detectingtouchesfromobjectsorpeopleinStrider’senvironment(theyarenotusedasbumperstopreventtherobotfromwalkingintosomething).TheUltrasonicSensorallowsthewalkertomeasurethedistanceofnearbyobjects,whiletheColorSensorinLightSensormodecandetectwhetheritisdarkorlightoutside.

buildingstriderWe’llnowmoveontobuildingtherobotbyfollowingtheinstructionsonthesubsequentpages.Beforeyoustartbuilding,selectthepiecesyou’llneedtocompletetherobotasshowninFigure9-2.

Page 220: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-2:TherequiredpiecestobuildtheStrider

Page 221: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 222: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 223: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 224: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 225: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 226: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 227: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 228: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 229: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 230: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 231: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingthesensorcablesYouconnectedthemotorcablesonpages132and133.Table9-1andFigure9-3willshowyouhowtoconnectthesensors.Whenconnectingthecables,guidethemthroughthespaceundertheNXTsothattheydon’tstickout.

table9-1:thecableplacementforstrider

Frommotor/sensor

ToNXTbrickport

Cablelength

RightTouch Inputport1

Page 232: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

RightTouchSensor(1)

Inputport1 Long(50cm/20inches)

LeftTouchSensor(2)

Inputport2 Long

ColorSensor Inputport3 Medium(35cm/15inches)

UltrasonicSensor Inputport4 Short(20cm/8inches)

Figure9-3:Connectthecablesasshown.

understandingstrider’swalkingtechnique

BeforeyoucanprogramStrider,youneedtounderstandhowitwalks.Figure9-4showshowthreeminifigurescanmoveaheavyobjectforward.

Page 233: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-4:Twominifigurespulltheheavyobject(dashedarrows),andonepushes(whitearrow).Asaresult,theobjectmovesforward(solidblackarrow).

TheminifiguresinFigure9-4representeachofStrider’smotorcompartments,andtheheavyobjectrepresentstheNXT,asshowninFigure9-5.

EachoftheStrider’sthreelegpairsfunctionsabitlikeyourownlegs.Asamotorrotates,itsattachedlegpairwalksbyrepeatedlyputtingoneleginfrontoftheother.Whetheralegpairpushesorpullstherobotinacertaindirectiondependsonwhetherthemotorisconfiguredtoturnforwardorbackward(Figure9-6).

Whenaleg’smotorspinsbackward,ithasthesameeffectontheStriderastheminifigurepullinganobject.Whentheleg’smotorrotatesforward,itactsliketheminifigurepushinganobject.ThecombinationofmotordirectionsmakesupthedirectionthatStridereventuallywalksin.

Page 234: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-5:MotorsAandCpulltherobotforward(dashedarrows),andmotorBpushes(grayarrow).Asaresult,theStriderwalksforward(solidblackarrow).(Thesensorshavebeenremovedheretomakethemotorsmorevisible.)

Page 235: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-6:WhenNXTmotorsarespecifiedtoturnforward,thecorrespondinglegpairmovesintheblackdirection.Thegraydenotesbackwardmovementofthemotor.

NOTE TheStridercanonlywalkonareallysmoothsurface,suchastiles,adesk,orasmoothwoodenfloor.Ifyouputitoncarpetoraroughfloor,thelegswillprobablybreak!

programmingstriderNowthatyouunderstandthebasicsofmakingStriderwalk,you’llcreatethreeMyBlockstomakeitwalk.Followingthat,you’llusetheseblockstocreatelargerprograms.

Page 236: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingthewalk-forwardmyblockYou’llbeginbycreatingtheWalk-ForwardMyBlock.BecausemotorsAandCwillpulltherobot,thosemotorswillrotatebackward.MotorBwillbeconfiguredtoturnforwardsinceitslegcompartmentpushestherobot.TheDurationsettingsareallsettoUnlimitedsothattheMyBlockwilljustswitchonthemotors.You’lluseotherblocks(likeWaitblocks)tocontrolhowlongtheStriderwalksinaspecificdirection.

Tobegin,createanewprogram,pickthreemotorblocksfromtheProgrammingPalette,andconfigurethemasshowninFigure9-7.MotorBspinsslightlyfasterthantheothertwobecausethecorrespondinglegpairpushestherobotalonginthedirectionit’swalking(Figure9-5);thismakestherobotmorestableasitwalks.

NOTE ForarefresheronhowtocreateMyBlocks,seeChapter5forstep-by-stepinstructions.

SelectthesethreeMotorblocks,turnthemintoaMyBlockcalledWalk-Forward,andthenaddaWaitBlocktotheprogram(Figure9-8).Runtheprogram,andtheStridershouldwalkforwardfor10secondsandthenstopwhentheprogramends.

creatingthewalk-leftandwalk-rightmyblocksNowyou’llcreatetwomoreMyBlockstomakeStriderwalkleftandright.Theblocksareessentiallythesameastheoneyoujustmade,exceptthattheDirectionandPowersettingsnowmaketherobotmoveinadifferentdirection,asshowninFigure9-9.CreatethesetwoMyBlocksjustliketheoneyoumadeintheprevioussection,andseeTable9-2fortheirnamesandmotorDirectionandPowersettings.

Page 237: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-7:TheconfigurationoftheblocksintheWalk-ForwardMyBlock

Figure9-8:AquicktestprogramtomaketheStriderwalkforward

Page 238: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-9:Bychangingthedirectioninwhichitsmotorsturn,theStridercanwalkforward,left,orright.Ineachcase,twomotorspulltherobotinonedirection(dashedarrows),andthethirdmotorpushestherobot(grayarrow).Theresultingdirectionisindicatedwithasolidblackarrow.

table9-2:themotordirectionandpowersettingsforthemotorblocks

MyBlockname

MotorA MotorB MotorC

Walk-Forward Backward,50

Forward,60 Backward,50

Walk-Left Forward,60 Backward,50

Backward,50

Walk-Right Backward,50

Backward,50

Forward,60

DISCOVERY#43:TRIANGLETIME,AGAIN!Difficulty:EasyYouknowhowtodriveinatrianglepatternusingtheExplorerrobot,buthowdoyoudoitwiththeStriderrobot?UsethethreeMyBlocksyou’vejustmade,andsetthreeWaitBlockstowaitforfiveseconds(putoneWaitBlockaftereachMyBlock).Formorefun,putalloftheseblocksinaLoopBlockandadd

Page 239: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

someColorLampeffectsorsounds.

NOTE Ifyou’reexperiencingthattheStriderhastroublewalkingorifitslegscomeoff,trymakingitwalkonasmoothersurface.

usingthemyblocksinaninteractiveprogramNowthatyouknowbasicallyhowtocontroltheStrider,youcancreatebiggerprograms.AsyounoticedinDiscovery#43,theStridercannotturnaround,whichmeansitwillalwayslookinthesamedirectionwiththeUltrasonicSensor.However,itisstillcapableofgoingeverywherewhenyoucombinetheWalk-Forward,Walk-Left,andWalk-RightMyBlocksproperly.

Thenextprogramyou’llcreatewillhavetheStriderwalkforwarduntilyoupressoneofitsantennas,atwhichpointitwillwalkleftorright,dependingonwhichsensoryoupress(programmingsteps1and2).You’llusesoundsandtheNXTscreentogivefeedbackaboutthesensorreadings(steps3,4,and5).YoucanseeanoverviewoftheprograminFigure9-10.

Figure9-10:TheprogramflowfortheStrider-Touchprogram.Whilewalkingsidewaysforfiveseconds,therobotalsomakessoundsanddisplaystextontheNXTscreentosaywhichdirectionitisgoing(leftorright).

creatingtheprogramStartanewprogram,andsaveitasStrider-Touch.ThenfollowtheinstructionsinFigure9-11andFigure9-12tocreatetheprogram.

Page 240: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-11:Step1:Theseblocksformtheprogram’smainstructure.Theprogramshouldkeeprunninguntilyoumanuallyabortit,soyouuseaLoopBlock.Insidetheloop,youplacetwoSwitchBlockstotellwhetherasensorispressed.

Figure9-12:Step2:Youconfiguretherobot’smovementsbyplacingyourMyBlocksintheSwitchBlocks.Forexample,whenyoupresstheTouchSensorconnectedtoport1,theStriderrobotshouldstarttowalktotherightand(becauseoftheWaitBlock)keepgoinginthisdirectionforfiveseconds.Next,itshouldgobacktothebeginningoftheprogramtoseewhetherasensorispressed.Ifnosensorispressedatthatpoint,theStridershouldcontinuetowalkforward.

Theblocksyouconfiguredinsteps1and2formthebasisofthisprogram.Atthispoint,downloadtheprogramtotheStridertotestit.Tomaketheprogrammorefunandinteractive,you’lladdDisplay,Sound,andColorLamp

Page 241: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Blocksinsteps3,4,and5(Figures9-13,9-14,and9-15).

Figure9-13:Step3:HereyouaddtheblocksthatshouldberunwhentherightTouchSensorispressed.Whenthesensorispressed,abluelightshouldbeswitchedon,therobotshouldstopwalking,anditshouldsay“Right”anddisplay“Youpressedtherightsensor!”ontheNXTscreen.Next,theStriderrobotshouldwalktotherightbecauseoftheWalk-RightMyBlockthatyouplacedearlier.

Page 242: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-14:Step4:Theblocksyouplaceherearesimilartothoseinstep3,exceptthattheyarerunwhentheleftTouchSensorispressed.Consequently,theSoundandDisplayBlocksareconfiguredtotellthattherobotiswalkingtotheleft.

Page 243: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-15:Step5:Theblockshererunwhennoantennasaretouched,sotheNXTscreenwilldisplay“Youpressednosensors!”AfterconfiguringtheStridertowalkforwardwiththeWalk-ForwardMyBlock,theprogramgoesbacktoseewhetheranysensorsarepressed,soyoudon’tneedaWaitBlockhere.

Congratulations,youcannowdownloadandruntheprogramtomakeStriderwalk!

DISCOVERY#44:WALKINGINSIXDIRECTIONS!Difficulty:EasyTakealookattheWalk-ForwardMyBlock.CanyoucreateanewMyBlockthatusesthesameMotorBlocksbutthatflipsallmotordirections?WhichwaydoesStriderwalknow?DothesamethingfortheothertwoMyBlockssothatStridercanwalkinsixdifferentdirections.Onceyou’vecreatedtheextraMyBlocks,buildaprogramthatuseseachofthem.

Page 244: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingthescaredstriderprogramInthenextprogram,you’llhaveStriderwalkforwarduntilsomeoneturnsonalight,atwhichpointitwillshoutandimmediatelysitstilluntilthelightisswitchedoff.Butbeforeyoucreatethisprogram,youneedtolearntwonewprogrammingtricks:FeedbackBoxesandthresholds.

pollingsensorswithfeedbackboxesTheConfigurationPanelsofcertainblockscontainasectionwithafixedvaluecalledFeedbackBoxes.FeedbackBoxes(asshowninFigure9-16)displaysensorvalueswhentherobotisconnectedtothecomputer,eitherthroughUSBorthroughBluetooth.

Figure9-16:AFeedbackBoxreportssensorvalues.TheWaitBlockConfigurationPanelshownhereisconfiguredtopollthevalueoftheUltrasonicSensor.

Page 245: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-17:Youuseathreshold(triggervalue)tosettheedgebetweenlightanddark.YousetthisvalueintheConfigurationPanelofablocksettoworkwithasensor,suchastheWaitBlockshownhere.Inthiscase,anyvaluegreaterthan30willbeconsideredlight,andvalues30andlesswillbedark.Asaresult,thisblockmakestherobotwaituntiltheLightSensorreportsavaluegreaterthan30beforetheprogramcontinues.

settingthresholdsIt’seasytotellwhetheraTouchSensorispressedornotbecauseit’seitherpressedorreleased,buthowcanyouuseaLightSensortotellwhenitisdarkorlight?Unlikeamechanicalsensorthatiseitherswitchedonorswitchedoff,lightcanhavemanymeasuredvalues.OntheNXT,thevaluesfromtheColorSensorinLightSensormoderangefrom0(darkest)to100(brightest).Totellyourrobotwhatyouconsidertobelightordark,you’lldefinelightanddarkinyourprogramusingatriggervalue,alsoknownasthethreshold(Figure9-17).You’llconsiderameasuredlightsensorvaluegreaterthanthisthresholdaslightandameasurementlowerthanthethresholdasdark.

Thresholdvaluesareuniquetoeverysituationandwilllikelyvarydependingonthelightconditionsintheroom.Tosetthethresholdvalue,you

Page 246: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

beginbydecidinghowyouwanttodefinethelightconditionsinyourprogram(aroomwiththelightsonandthesameroomwiththelightsoff),andnextyoumeasurethelightvalueineachcase.

BecausetheNXT’sViewmenuwon’tletyoupolltheLightSensor,you’lluseaWaitBlock’sFeedbackBoxconfiguredasaColorSensorinLightSensormode(Figure9-18)topollit.Fordarkconditions,Imeasureavalueof4,andforbrightconditionsImeasureavalueof30withtheFeedbackBoxmethod.Yourmeasurementsmayvary.

Onceyouhavethetwomeasuredvalues(oneforthedarkroomandoneforthelightone),youcalculatetheaverageofthetwo,asshowninFigure9-19.Yourmeasuredvaluesmaydiffer;besuretocalculateyourownthresholdsusingyourownmeasurements.

Figure9-19:ThethresholdistheaverageoftheLightSensorvaluefoundinthedarkroom(alownumber)andtheonefoundintheroomwiththelightson(abiggernumber).Tocalculatetheaverage,addbothvalues,anddividethetotalby2.

Page 247: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-18:UsingtheFeedbackBoxtopolltheLightSensorvalue

creatingtheprogramYou’llnowcreatetheprogramthathastheStriderrobotmoveforward,shoutwhenalightcomeson,andstopmovinguntilthelightturnsoff.Createanewprogram,storeitonyourcomputerasStrider-Scared,andfollowtheinstructionsshowninFigure9-20.

Page 248: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-20:AftermakingtheStridermoveforward,theprogramwaitsuntilthemeasuredlightintensityexceedsthethreshold(setto17here).Oncethethresholdisexceeded,allmotorsstop,andtherobotmakesaloudsound.Thelastblockwaitsuntilthesensorseesthatitisdarkagain,atwhichpointthelooprestartsandStriderstartswalkingagain.

Page 249: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DISCOVERY#45:WALKINGATTHESPEEDOFLIGHT!

Difficulty:HardWithyourMyBlocks,StriderwalksatthespeedspecifiedintheMotorBlocks,butyoucanmakeitwalkfasterorslowerbyconfiguringtheseblocksdifferently.Createaprogramthatmakestherobotwalkfaster,basedonitsLightSensorreadings.IftheLightSensorvalueislessthan33,makeStridergoslow;ifthisvalueisbetween34and66,makeitwalkfaster(around50percentmotorpower);andifthevalueisgreaterthan66,makeitrunasfastaspossiblewithoutbreakingitslegs!UseSwitchBlockstodeterminetheLightSensorvalue.Youcouldpointaflashlightatthesensorfromadistancetomaketherobotgofaster.

furtherexplorationIt’snoteasytodesignwalkingrobots,soifyouwanttocreateyourownwalker,trybuildinganotheroneaccordingtoasetofdirectionsfirsttogetabettersenseofhowwalkersaredesigned.OnthebackoftheLEGOMINDSTORMSNXT2.0box,you’llfindasmallpictureofManty,anothersix-leggedcreatureofmine.Thisrobot’swalkingtechniqueisverydifferentfromStrider’sbecauseMantyhastwosetsofthreelegsandbecauseitcanturninplace.YoucandownloadbuildingandprogramminginstructionsforthisNXT2.0robotfromhttp://www.discovery.laurensvalk.com/.

Now,beforeyoumoveontoyournextrobot,takethetimetoimproveyourbuildingandprogrammingskillsinBuildingDiscoveries#8and#9andDiscovery#46.

BUILDINGDISCOVERY#8:TIREDOFWALKING?!YoumayhavenoticedthatStrider’sbasestructureisasolidtriangle,anuncommonconstructionforaLEGOMINDSTORMSrobot.Whathappensifyouputthistriangleonwheels?Removethelegsfromthemotor

Page 250: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

compartments,andattachwheels(withouttherubbertires)tothem,asshowninFigure9-21.TrytoruntheprogramsyoumadefortheStriderrobot.Dotheystillwork?Whathappensifyouattachtherubbertires?

DISCOVERY#46:REMOTECONTROL!Difficulty:MediumDoyouremembertheremotecontrolyoumadefortheShot-Roller?Inthisdiscovery,you’lldosomethingsimilarwiththeStrider.RemovetheantennasfromtheStriderrobot,andusetheTouchSensorswithlongcablesasremotebuttons.HowdoyouprogramStridertowalkinmultipledirections?

BUILDINGDISCOVERY#9:APAIROFEYESINTHEBACK!

WhenyoubuilttheDiscoveryrobotwiththetwobumpersinChapter7,italmostnevergotstuckbecauseitcouldalwaysturnawayfromthewallsitraninto.ThisisnotthecaseforStriderbecauseitcannotturnaround.Tomakesuretherobotnevergetsstuck,Striderneedstobeabletosensethewallsfromanydirection.ItcanalreadyseethingsaheadofitwiththeUltrasonicSensor.Now,removetheantennasfromtheStrider,andcreatespecialbumpersonthetwoothersidesofStrider.CanyouuseTouchSensorstobuildbumperssothatthisrobotwillnotcrashintoobjects?

Page 251: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure9-21:Strideronthreewheels

Page 252: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PARTIII

creatingadvancedprograms

Page 253: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

10

usingdatahubsanddatawires

Inthisthirdpartofthebook,you’lllearnhowtousedatahubsanddatawirestocreatemoreadvancedprogramsforyourrobots.Forexample,you’llusedatahubsanddatawirestocreateprogramsthatdisplaysensorreadingsonthescreen(Chapter10),domathematicswiththeNXT(Chapter11),orrememberthingssuchashighscoresofgames(Chapter12).

InearlierchaptersyouconfiguredeachprogrammingblockbyenteringthedesiredsettingsintheConfigurationPanel.Oneofthefundamentalconceptsinthischapteristhatblockscanconfigureeachother.Forexample,oneblockcaninstructaMotorblocktorunamotoratacertainpowerlevel.Blockstransferinformationsuchasthepowerlevelusingdatahubsanddatawires.Tomakethisabitmoretangible,thinkofthisaslikeapersonwhousesa(wired)phonetoasksomeonetosettheradiotohalfofitsmaximumvolume,asshowninFigure10-1.Thetwopeoplehererepresentprogrammingblocks.Theactualphoneisthedatahub,andthephonewireisthedatawire.

Figure10-1:Youusedatahubs(thephones)andadatawire(thephonewire)tocarryavalue(theradiovolume)fromoneprogrammingblock(thepersonontheleft)totheother(thepersonontheright).Thesecondblockusesthevalueto

Page 254: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

turnontheradioattherequestedvolumelevel.

The“block”ontheleftbasicallypassesthedesiredradiovolumetothe“block”ontheright,whichcanthensettheradiototheappropriatevolume.Forthevolumevaluetomovefromthefirsttothesecondprogrammingblock,itgoesfromtheblockthroughadatahub(thephoneontheleft),throughadatawire(thephonewire),andthroughanotherdatahub(thephoneontheright);whenitreachesthesecondblock,itspecifiesits(volume)setting.

Tosummarizethisconcept,datawirescarryvaluesfromoneblocktoanothertoconfigureoneofthisblock’ssettings.Adatahub,whichispartofaprogrammingblock,allowsablocktopassvaluesintothewire(thedatahubontheleftofFigure10-1)andretrievevaluesfromit(thedatahubontherightofFigure10-1).

Thischapterteachesyouhowtomakeprogramsthatusedatahubsanddatawires.Youmayfindthisabitdifficultatfirst,butasyougothroughthesampleprogramsandthediscoveries,you’llmasteralloftheseprogrammingtechniques!

buildingSmartBotTomakeiteasiertolearnallthesenewfeatures,you’llbuildasmallplatformwithtwomotors,somesensors,andtheNXT,calledSmartBot,asshowninFigure10-2.Thisrobotwillhelpyoubetterunderstandhowtheadvancedprogramsthatyou’llmakereallywork.

NowbuildSmartBotbyfollowingtheinstructionsonthenextfewpages,butfirstselecttherequiredpieces,asshowninFigure10-3.

Page 255: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-2:You’llusetheSmartBotrobottolearnmanynewprogrammingtechniques.I’llrefertothemotorwiththeColorSensorastheHandmotorandtheonewiththewheelastheWheelmotor.

Figure10-3:TherequiredpiecestobuildSmartBot

Page 256: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 257: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 258: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 259: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 260: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

aprogramtogetstartedwithdatawires

Toseehowdatahubsanddatawireswork,you’llcreateasmallprogramthat

Page 261: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

willmaketheSmartBotplayasoundandthenmaketheHandmotorrotateforthreeseconds.Themotor’spowerlevel(andthusitsspeed)willrespondtowhattheUltrasonicSensorsees:Ifthesensorseessomething43cmaway,themotor’spowerlevelwillbe43forthreeseconds;ifthesensorreads15cm,themotorpowerwillbe15;andsoon.Forexample,ifyoukeepabookclosetothesensorandruntheprogram,thehandshouldgoupanddownslowly,butmovefasterifyouruntheprogramagainwiththebookfartheraway.

Toaccomplishtheseactions,you’llusetheUltrasonicSensorblock.You’lllearnmoreaboutthisblocklater,butfornowjustknowthatyouuseittopollthesensor.CreatetheSmart-IntroprogramasshowninFigures10-4through10-6,andthenruntheprogramtoseehowitworks.

Page 262: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-4:Step1:PlaceallthenecessaryblocksfortheSmart-IntroprogramontheWorkArea,andconfigurethemasshownhere.

Page 263: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-5:Step2:Opentheblocks’datahubsbyclickingthetabsatthelower-leftedgeoftheblock.YoushouldalreadyseeasmalldatahubjustbelowtheUltrasonicSensorblock,butyoucanopenthecompletedatahubbyclickingthesametab.

Figure10-6:Step3:Createandconnecttheyellowwireasshownhere.Theyellowlineisthedatawire.

Page 264: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DownloadtheprogramtoSmartBot,andrunitwhilekeepingabookabout20cm(8inches)awayfromtheUltrasonicSensor.Next,runtheprogramagainwiththebookabouttwiceasfarfromtherobot.Youshouldnoticethateachtimeyouruntheprogram,theHandmotorturnsatadifferentspeed.

understandingthesampleprogramCongratulations!You’vejustcreatedyourfirstprogramwithdatawires.Nowyou’lllearnexactlyhowyourprogramworksbyanalyzingthefunctionofeachblock.

ThefirstSoundblocksimplyplaysasound.Oncethesoundfinishesplaying,theUltrasonicSensorblockpollsthesensoronce,resultinginareadingof,say,35cm.TheyellowdatawirethencarriesthesensormeasurementtotheotherendofthewiretotheMotorblock,whichthenmakestheHandmotorturnforthreeseconds,asspecifiedinitsConfigurationPanel.Themotorpower(andthusitsspeed)dependsonthevaluecarriedbythedatawire;it’s35inthiscase.Figure10-7showsanoverviewofwhathappens.

Page 265: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-7:AnoverviewoftheSmart-Introprogram.TheUltrasonicSensorblockpollsthesensorandsendsthesensorvaluethroughadatawiretotheMotorblock,whichusesthisvaluetosetthemotorspeed.

howdodatahubsanddatawireswork?

You’llnowanalyzesomeofthenewfeaturesthatyouusedintheprogramyoujustmade.Asyoucansee,youuseadatawiretocarryinformationbetweenblocks.Intheexampleprogram,theyellowdatawirecarriesthesensorvaluetotheMotorblocktosetthemotor’spowerlevel.

Youcreatedthedatawirebyfirstclickingoneofthedataplugsonthedata

Page 266: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

huboftheUltrasonicSensorblock.Eachdataplugcarriesoutadifferentvalue,butyouconnectedyourdatawiretotheDistancedataplug,becauseyouwantedtoknowthemeasureddistance.Next,youconnectedtheotherendofthewiretothePowerdataplugonthehuboftheMotorblock.Asaresult,youactuallyreconfiguredthePowersettingofthisblock,andthemotormovedataspeedbasedonthesensorreading.

You’llnowtakeamoredetailedlookatthedatahub.Openanewprogram,pickaMotorblockfromtheProgrammingPalette,andplaceitontheWorkArea.Then,opentheblock’sdatahub,asshowninFigure10-8.

Figure10-8:Toopenablock’sdatahub,clickthetabatthelower-leftedgeoftheblock.Toclosethehub,clickthetabagain.Moveyourmousepointeroverthedataplugstofigureoutwhateachplugstandsfor.(I’veshownonlyafewexampleshere.)

Asyoumouseoverthevariousplugsonthedatahub,youshouldseewhichsettingisreconfiguredwhenyouconnectawiretothisplug.Forexample,asshowninFigure10-8,you’llseeplugsforDirection,Power,andDuration.You’llalsofindthesetermsontheblock’sConfigurationPanel.Inotherwords,whenwiringdatawiresintoablock’sdatahub,you’reactuallyreconfiguringtheblock’ssettingsasifmodifyingthesettingsintheConfigurationPanel.

Page 267: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingasecondexampleprogramwithdatawiresanddatahubs

Nowyou’llcreateaprogramtomaketheSmartBot’smotoraccelerate.Itwillstartoutslowlyandincreaseitsspeeduntilitreachesthemaximumpowerlevel.

Tomakethisprogram,youplaceaMotorblockthatmakesthemotorturnforhalfasecondinsideaLoopblock.BecausetheMotorblockisinsidetheloop,themotorkeepsspinning.You’llalsouseanewfeatureoftheLoopblockthatmakesitcountthenumberoftimesithasrepeatedtheMotorblockinsideit,calledtheloopcount.

BecausetheMotorblockkeepslooping,theloopcountincreasesovertime,andyouusethisvalueasaninputforthemotorpower.Whenyoustarttheprogram,theloopcountis0,whichmakesthemotorrunatzerospeed(itstandsstill)forhalfasecond(asspecifiedbytheDurationsetting).WhentheLoopblockreturnstothebeginning,itrepeatstheMotorblock;theloopcountincreasesto1,andthereforethemotor’spowerlevelis1.Whenitrepeats,themotorspeedis2,andsoon.FollowtheinstructionsinFigures10-9and10-10tocreatetheSmart-Accelerateprogram.

Downloadthisprogramtoyourrobot,andrunit.Ifyouconfiguredeverythingcorrectly,theSmartBot’shandshouldstartmovingslowly,andastimepasses,theHandmotor’sspeedshouldincrease.Thehandshouldstopacceleratingwhentheloopcountexceeds100,because100isthemotor’smaximumpowerlevel.

Page 268: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-9:Step1:Placeandconfigurethetwoblocksasshownhere.NotethattheCountersettingischeckedintheLoopblock,whichopensalittleplugontheleftsideoftheLoopblock.

Page 269: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-10:Step2:OpentheMotorblock’sdatahub,andconnectthedatawiretotheplugsasshownhere.

usingdataplugs:inputandoutputAsyousawearlier,youconnectdatawirestodataplugsondatahubs.Thehubscontaintwotypesofplugs,asshowninFigure10-11:outputplugs(ontherightside)andinputplugs(ontheleftside).Outputplugscarryoutavalueandpassittoadatawire.Forexample,theDistanceplugontheUltrasonicSensorblockcarriesoutthemeasureddistancevalue.Inputplugsretrievethevaluefromthedatawireandpassittotheblockitconnectstosothatthevaluecanbeusedtoreconfigureoneoftheblock’ssettings.Forexample,youusedthePowerplugasaninputplug.

Generally,adatawirecarriesinformationfromanoutputplugofoneblocktoaninputplugofanotherblock.

NOTE TheComparesettingintheUltrasonicSensorblock’sConfigurationPanelcontrolshowtheYes/Nooutputplugworks.However,

Page 270: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

whenusingtheUltrasonicSensorblockjusttopollthesensorasyoudidpreviously,you’reonlyusingtheDistanceplugofthisblock,meaningthatyoudon’thavetoconfiguretheComparesetting.(You’lllearnhowtousethissettingin“TheLogicDataWire”onpage163.)

Figure10-11:Inputandoutputplugsonadatahub.Thedatawirecarriesinformationfromanoutputplugtoaninputplugofanotherblock.

blockconfigurationswhenusingdatawiresWhenusingblockswithdatawires,whathappenstothesettingsyouconfiguredintheConfigurationPanel?Inthetwosampleprograms,youhadtheMotorblockrunamotoratapowerlevelspecifiedbyadatawire,eventhoughtheMotorblock’sPowerwassetto75(Figure10-12).

Asageneralrule,thedatawireinputoverridesthesettingspecifiedintheConfigurationPanel,andthesettingintheConfigurationPanelisignored,asillustratedinFigure10-12.Allothersettingsthatdonotconflictwithadatawireareineffect,asspecifiedintheConfigurationPanel.Forexample,theblockherewillmakethemotorturnforwardbecausetheConfigurationPanelsaysso.

Page 271: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-12:AConfigurationblock’ssettingisignoredwhenadatawiredefinesthesamesetting;theblockwillusethedatawire’svalue.

deletingdatawiresTodeleteadatawire,followtheinstructionsshowninFigure10-13.

Page 272: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-13:Todeleteadatawirethatconnectstwoblocks,clickthedataplugontherightendofthewire.Ifthisdoesn’twork,youshouldbeabletoremoveitbyclickingthewireandthenpressingtheDELETEkey.Beforeyoupressthiskey,though,makesurethatnoblockisselected,oryou’lldeleteitwiththedatawire.

DISCOVERY#47:GROWINGCIRCLES!Difficulty:EasyCreatetheprogramshowninFigure10-14.TheDisplayblockshowninthefigurewilldisplayacircleinthemiddleoftheNXTscreen.Youwantthecircletogrowbiggerasyouwait,sotheRadiussettingshouldincreaseovertime.Theprogramhereisincomplete,becauseadatahubandadatawirearemissing.Canyouopenthedatahubandconnectthedatawiretofinishthisprogram?

HINTLookfortheRadiusinputplug.

Page 273: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-14:TheincompleteprogramforDiscovery#47.Canyoucompleteitbyconnectingadatawireappropriately?

DISCOVERY#48:DYNAMICSPEED!Difficulty:MediumTheSmart-IntroprogrampolledtheUltrasonicSensoronceandusedthesensorvaluetosetthespeedoftheHandmotor.Youcanmodifythisprogramsothatthemotorspeediscontinuouslyupdatedwithanewsensorreadingasfollows:1.RemovetheSoundblock.

Page 274: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

2.SettheMotorblock’sDurationsettingtoUnlimited.3.PlacethetworemainingblocksinaLoopblockconfiguredtoloopforever.

Ifthedatawirebreaksasyoudoso,reconnectit.Nowastheprogramruns,movetheSmartBotbackandforthnearawallso

thattheUltrasonicSensorconstantlymeasuresadifferentdistance.Whathappenstothemotorspeed?Canyoufigureoutwhythishappens?

sensorblocksInChapters6and7youlearnedtoworkwithsensorsbycreatingprogramswiththeWait,Loop,andSwitchblocks.ThefinalwaytopollsensorsiswithSensorblocks,asshowninFigure10-15.Theseblocksareusefulifyouwanttoretrieveasensorvalueandtransferittoanotherblockwithadatawire,asyousawwiththeSmart-Introprogram.

There’saSensorblockforeachsensor,includingsomesensorsnotfoundintheLEGOMINDSTORMSNXT2.0roboticskit.Intheexampleprogramssofar,you’veusedtheUltrasonicSensorblock.Sensorblocksareofnouseontheirown;theymustbeconnectedtoanotherblockwithadatawireinordertofunction.

configuringasensorblockConfiguringaSensorblockisverymuchlikeconfiguringaWait,Loop,orSwitchblock,exceptthattheSensorblocksdonothingwithsensormeasurementsthemselves.Sensorblockssimplytransmitsensorreadingstootherblockswithdatawires.Inadditiontopollingsensors,Sensorblockscanalsocompareameasuredsensorvaluewithatriggervalue.Generally,theseblockshavetwooutputplugs.Oneplugoutputsthesensormeasurement(liketheDistanceplugintheUltrasonicSensorblock);theother,theYes/Noplug,outputstheresultofthecomparison,asyou’lllearnin“SeeingaLogicDataWireinAction”onpage164.

configuringatouchsensorblockTheTouchSensorblockoutputsitssensorvaluewiththeLogicalNumberplug,

Page 275: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

whereavalueof1representspressed,and0meansreleased.However,whenyouusethisblock,you’llmorefrequentlyuseitsYes/Nooutputplug,discussedin“SeeingaLogicDataWireinAction”onpage164.

configuringacolorsensorblockAsmentionedpreviously,theColorSensorcanidentifysixdifferentcolors.TheDetectedColorplugontheColorSensorblockoutputsanumberbetween1and6,witheachnumberrepresentingaparticularcolor:black=1,blue=2,green=3,yellow=4,red=5,andwhite=6.(InChapter11you’llcreatesomeprogramsthatusethisfeature.)

RecallthattheColorSensorcanfunctionasaLightSensor.Notsurprisingly,youcanusetheLightSensor’svalueinaprogrambyselectingLightSensorintheActionboxontheColorSensorblock’sConfigurationPanel.Onceconfiguredinthisway,whenyousubsequentlyconnectadatawiretotheDetectedColorplug,itshouldcarryoutavaluefrom0to100,basedonthebrightnessofthedetectedlight(100isbrightest).

Page 276: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-15:YoucanfindaSensorblockforeachsensorontheCompletePalette.

DISCOVERY#49:MOTORINPUT!Difficulty:MediumInthisdiscovery,you’lledittheprogramfromDiscovery#48tosetthemotorspeedoftheHandmotor,basedonthenumberofdegreesyouturnedtheWheelmotor.Whenyou’reready,edittheprogramsothatthemotorspeeddependsontheamountoflightdetectedbytheLightSensor.

configuringarotationsensorblockInChapter7youlearnedthateachmotorcontainsaRotationSensor,whichtellsyouhowmanydegreesamotorhasturnedsinceyoustartedtheprogram.TheDegreesplugontheRotationSensorblock’sdatahuboutputsthisnumberofdegrees.Ifyourotatethemotorbackward(seeFigure7-20),theoutputvaluewillbenegative.

datawiretypesDatawirescarryinformationbetweenblocks.Sofaryou’veuseddatawirestotransfernumericalvaluesonly,buttherearethreetypesofdatawires:Number,Logic,andTextdatawires.Eachtypeofdatawirecarriesaspecifictypeofinformation(numerical,logic,ortextvalues),andeachtypehasitsowncolor,asshowninFigure10-16.

thenumberdatawireTheNumberdatawire(yellow)carriesnumericinformationthatmayincludewholenumbers(suchas0,15,or1427),numberswithdecimals(suchas0.1or73.14),andnegativenumbers(suchas-14or-31.47).

ExamplesofinformationcarriedbyNumberdatawiresareUltrasonicSensorreadingsandloopcounts.

Page 277: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

thelogicdatawireTheLogicdatawire(green)cancarryonlytwovalues:trueorfalse.Thesewiresareoftenusedtodefinesettingsofablockthatcanhaveonlytwovalues,suchastheturndirectionofanNXTmotor.Forexample,amotorwillspinforwardwhenaLogicdatawirewiththevaluetrueisconnectedtotheDirectionplugofaMotorblock.Consequently,itspinsbackwardwhentheLogicdatawirevalueisfalse.

Figure10-16:Examplesofthreetypesofvalues.Eachvaluetypeiscarriedbyitsowndatawire,asyou’lllearninamoment.Thelastdatawirehereisn’tfunctional,anditcarriesnoinformation:Therobot’slastquestionrequiresanumericalanswer,butMikerepliedwithasentence,whichwouldrequireaTextdatawire.Thismismatchresultsinabrokendatawire,becausethegiveninformationcannotbeused.

seeingalogicdatawireinactionYou’llnowcreateaprogramtoseethefunctionalityoftheLogicdatawireandtheComparefunctionoftheUltrasonicSensorblockinaction.Thisprogram

Page 278: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

willmakeSmartBot’sWheelmotorspinforwardaslongastheUltrasonicSensorseessomethingcloserthan40cmandspinbackwardwhenthisisnotthecase.Therequiredinputforthemotor’sDirectionsettingisaLogicdatawire(trueisforward,andfalseisbackward).Therefore,you’llmakeaconnectiontoadataplugontheUltrasonicSensorblockthatsendsoutalogicvalueusingtheYes/Nooutputplug.Thisplugwilloutputalogicvalue(eithertrueorfalse),basedontheresultoftheCompareboxintheConfigurationpanel.TheUltrasonicSensorblockwillchecktoseewhetherthesensorreadingissmallerthanthetriggervalue(40cm).Ifitis,theresultistrue;ifnot,theoutputvalueisfalse.

NowcreatetheSmart-LogicWireprogramasshowninFigure10-17.

NOTE Becauseyou’renotspecifyingthemotorspeedwithadatawire,themotorpoweris75nomatterwhichdirectionthemotorspins,assetintheConfigurationPanel.

Onceyou’vefinishedcreatingthisprogram,downloadittoyourrobot,andnoticehowthemotordirectionflipsasyoumoveyourhandclosertoorfartherfromthesensor.

thetextdatawireTheTextdatawire(orange)carriestextbetweenblocksto,forexample,thedatahubofaDisplayblocksothatitappearsontheNXTscreen.Thistextcanbeaword,likeHello,aswellassentenceslikeMynameisMike.

displayingvalueswiththenumbertotextblockByenteringatextlineintheConfigurationPanel,youcanuseDisplayblockstoshowatextlineontheNXTscreen.YoucanalsouseaTextdatawiretosubmittexttoablock.

DISCOVERY#50:TOUCHSENSORWIRES!Difficulty:MediumInthisdiscoveryyou’llseetheTouchSensorblockinaction.TheYes/NoplugonthisblockoutputsaLogicdatawire.ItsvalueistrueiftheactionspecifiedintheActionsetting(suchasPressed)takesplace,andisfalseotherwise.

Page 279: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

CreateaprogramthatswitchesontheColorLampiftheTouchSensorispressedandswitchesitoffwhenitisnotpressed.Todoso,wiretheLogicdatawirefromtheTouchSensorblocktotheActionplugoftheColorLampblock.WhatvalueshouldtheColorLampblock’sActionplugreceiveforthelamptobeswitchedon?

Figure10-17:TheconfigurationoftheSmart-LogicWireprogram.ThegreenLogicdatawireconnectstheresultofthecomparisonoftheUltrasonicSensorblocktotheDirectionplugontheMotorblock.Inthisparticularsetup,theSensorblockcheckstoseewhetherthesensorreadingissmallerthanthetriggervalue,butyoucouldalsomakeitlookforavaluebiggerthanthetriggerpoint.Ifyoudo,theresultwillbetrueifthesensorreadingisgreaterthan40.

You’llnowmakeaprogramthatcontinuouslydisplaystheUltrasonicSensorreadingontheNXTscreen.Todoso,youusetheUltrasonicSensorblocktofindthesensorvalue.Youhaveaproblemnow,though,becauseyoucannotusetheDisplayblocktodisplayvaluesfromNumberdatawires.Therefore,you’llhavetoconvertthenumericsensorreadingintosomethingthattheDisplayblockdoesaccept:text.

TheNumbertoTextblockcandothisforyou.Onthedatahub’sleftside,ittakesinputfromaNumberdatawire,suchasawirecarryingasensorvalue.Ontherightside,itoutputsaTextdatawire,whichcontainsthesamenumber,exceptinaformatthattheDisplayblockcanhandle.YoucanseetheNumberto

Page 280: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TextblockinFigure10-18,whichalsoshowsyouhowtomaketheSmart-TextWireprogram.

Figure10-18:TheconfigurationsoftheblocksintheSmart-TextWireprogram.YoucanfindtheNumbertoTextblockbetweentheAdvancedprogrammingblocks.NoticethattheDisplayblock(e)isconfiguredtodisplaytheMindstormsNXTtextline.However,theprogramignoresthissetting,becauseyoualsouseaTextdatawiretospecifywhatshouldbedisplayed.

DISCOVERY#51:READTHESENSORREADINGS!Difficulty:HardExpandtheSmart-TextWireprogramtomakeitdisplaytheRotationSensor

Page 281: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ExpandtheSmart-TextWireprogramtomakeitdisplaytheRotationSensorreadingbyaddingextrablocksinsidetheLoopblock.

HINTPayattentiontothelinenumbersintheDisplayblocks,aswellastheClearcheckbox.

NOTE WhenusingaSensorblockonlytoperformasensormeasurement,youdon’tneedtoconfiguretheblock’sComparesettingsinceyouwon’tbeusingtheresultofthiscomparison.

Figure10-19:Ifyoutrytoconnectadatawireofacertaintype(likeaNumberdatawire)toaninputplugonanotherblockthatdoesn’tacceptthistype,abrokendatawireisdisplayed.Theexampleshownheretellsyouthatyoucan’tconnecttheUltrasonicSensorreading(anumbervalue)totheDirectionplug(alogicvalue)ofaMotorblock.

thebrokendatawireThebrokendatawire(gray)carriesnoinformation.Whensuchawireshowsup,youknowthatyou’vemadeamistakewhenmakingthedatawireconnection.Themistakecanhaveseveralcauses,asyou’lllearninthisandinthe“MultipleDataWireConnections”section.You’llhavetodeletethisbrokenwireandreconnectitappropriately,oryouwon’tbeabletotransfertheprogramtotheNXT.

Whenyoubegincreatingadatawireonablock’soutputplug,theNXT-Gsoftwareautomaticallychoosesacolorforthewire,dependingontheplugyou

Page 282: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

clicked.Forexample,ifyouclickedtheUltrasonicSensorblock’sDistanceplug,you’dseeayellowwirebecausethedistancevalueisanumber.Becausethisisanumber,youhavetoconnectittoaninputplugonanotherblockthatacceptsNumberdatawires,likethePowerplugonaMotorblock.

Ifyouconnecttheyellowdatawire(fromtheDistanceplug)toaplugthatcannothandleNumberdatawires,abrokenwireshowsup,indicatingthattheconnectionisn’tright,asshowninFigure10-19.(In“UsingHelpforDataPlugs”onpage168,you’lllearnhowtofindtherightdatawireforeachplugonadatahub.)

NOTE WhenyoutrytosendaprogramwithabrokendatawireinittotheNXT,you’llgetanerrormessage.Thesolutionistodeleteanybrokendatawireandreconnectitproperly,asdiscussedin“TheBrokenDataWire”and“MultipleDataWireConnections.”

multipledatawireconnectionsSofar,you’veusedonlyonedatawireconnectionperblock,butyoucanusemoredataplugsonasingleblock.Youcanconnectmorethanonedatawiretoasingleblockinseveralways,butnoteverywaytoconnectthemresultsinaworkingprogram,asyou’lllearninthissection.

connectingmultiplewirestodifferentplugsYoucanusemultipleinputplugsonasingleblocktoreconfiguremorethanjustonesettingofablockwithadatawire.Forinstance,youcancontrolboththePowerandDirectionsettingsofaMotorblockwithdatawires(usingonewireforeachsetting).

Inthesameway,youcanusemultipleoutputplugsonasingleblock.Forexample,youcanusetheUltrasonicSensorblocktopollasensor(adatawirecarriesthesensorvalue)andcompareittothetriggervalue(anotherdatawirecarriesatrueorfalsevalue).

Toillustratethisfunctionality,you’llexpandtheSmart-LogicWireprogram(Figure10-17)byaddingaNumberdatawire,asshowninFigure10-20.

Page 283: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-20:Youcanconnectmultipledatawirestoablock.Here,SmartBot’sWheelmotorrotatesforwardwhenthesensorreadingislessthan40cm,andbackwardotherwise.Theactualsensormeasurementdefinesthespeedatwhichthemotorturns.

connectingmultiplewirestoonedataplugYoucanuseasingleoutputplugtosendinformationtomorethanoneblock,asshownontheleftofFigure10-21,butnotthereverse:Youcannotconnectmorethanonewiretoasingleinputplugsincethentheblockwouldnotknowwhichwiretotakeastheinput.Ifyoutrytomakesuchaconnection,abrokendatawirewillshowup,asshownontherightofFigure10-21.Youcandeletebrokenwiresjustlikeotherdatawires(Figure10-13).

DISCOVERY#52:MULTIFUNCTIONALWIRES!Difficulty:MediumCreateaprogramliketheSmart-Accelerateprogramyoumadeearlierinwhich

Page 284: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

theloopcountcontrolsthemotorspeed.HavethevaluethatcontrolsthespeedpassedontoaNumbertoTextblocktoenablethevaluetobedisplayedontheNXTscreen.

usingsettingswithbothinputandoutputplugsSomeitemsonadatahubhavebothinputandoutputplugs,asshownontheleftofFigure10-22.Asyou’velearned,theinputplugusesadatawire’svaluetoreconfigureoneoftheblock’ssettings.Forexample,youcanuseadatawiretosettheActionsettingoftheColorLampblock.

ThisActionsettingalsohasanoutputplugontherightside,whichwilloutputthesamevalueastheinputvalueontheleftside.Basically,theColorLampblockontheleftofFigure10-22takesinputfromthewireontheleftsideandpassesthatvaluetothenextblocksothattheinformationcanbeusedagain.If,however,thereisnoinputontheleft,thereisnoinformationtopassthrough,sothewirewillshowupasabrokendatawire(ontherightofFigure10-22).

Figure10-21:Asingleoutputplugcantransferinformationtoinputsonmultipleblocks(shownontheleft).WhenyourunthisprogramwhiletheTouchSensorispressed,theColorLampisswitchedon,andthemotorrotatesforward.Itisimpossibletoconnectmultipledatawirestooneinputplug(shownontheright).

Page 285: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-22:Whenaninputplughasacorrespondingoutputplug,thevaluereceivedbytheinputispassedontothenextblockwithnochange(shownontheleft).Ifthereisnovaluetopasson,abrokenwireisdisplayed(shownontheright).

usinghelpfordataplugsWhencreatingprograms,youmaywanttouseablock’sdataplugthatisn’tdiscussedinthisbook.Ifyoudo,youcanfindinformationaboutdataplugsspecifictoeachprogrammingblockinthehelpsectionofthesoftware.(Toaccessit,clickmorehelpintheLittleHelpWindowatthebottomrightofthesoftwarescreen,andafteritopens,usethemenuonthelefttofindinformationonaprogrammingblock.)

Forexample,whenyouopenthehelpfilefortheMotorblockbyclickingtheblock’snameinthemenuontheleft,you’llfirstseesomegeneralinformationabouttheblockanditsfunctions.Asyouscrolldownonthepage,you’llseeatablewiththedatahubcharacteristics,aportionofwhichisshowninFigure10-23.Bylookingatthistable,you’lllearnhowtoproperlyusethefunctionsofeachprogrammingblockanditsdataplugs.

Page 286: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-23:AfewdatahubcharacteristicsoftheMotorblock

ThetableshowninFigure10-23containsspecificinformationabouteachdataplug,includingthedatawiretype(“DataType”)thatshouldbeconnectedtotheplug,therangeofpossiblevaluesfortheplugfortheblocktofunctionasexpected(“PossibleRange”),whateachvaluemeans(“WhattheValuesMean”),andwhenadatawireisignoredbyablock(“ThisPlugIsIgnoredWhen...”).

You’llnowlookattheDirectionplug.Asyou’velearned(andasyoucanseeinFigure10-23),youcanonlyconnectagreenLogicdatawiretotheDirectionplug.Youalsoseethatavalueoftruewillmakethemotorspinforward,whilefalsewillmakethemotorrotatebackward.Finally,youcanseethatwhenadatawireisconnectedtothisplug,itisneverignored.Usingthismethod,you’llbeabletofindinformationabouteachblock’sdatahub.

DISCOVERY#53:LOOKINGFORHELP!Difficulty:EasyCreatetheprogramshowninFigure10-24.Yourgoalistofinishtheprogramtodisplayanimagesomewhereonthescreen(aimintheFilelist),dependingonthereadingfromtheWheelmotor’sRotationSensor.Themorethemotorhasturned,thefarthertheimageshouldmovetotheright.UsetheDisplayblock’shelpfiletofindoutwhichdataplugyoumustuseinordertosetthehorizontalpositionoftheimage.Nowconnectadatawirethatwillmaketheprogram

Page 287: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

workasdescribed.

Figure10-24:AstartingpointfortheprograminDiscovery#53

tipsformanagingdatawiresNowthatyou’velearnedhowdatahubsanddatawireswork,youcanusetheminyourprograms.But,asyoumakelargerprograms,itcangetdifficulttokeepyourprogramsorganizedandunderstandable,especiallywhenyouusealotofdatawires.Thefollowingtipswillhelpyoutokeepyourprogramscleanandreadable.

hidingunuseddataplugsYoucanhideunuseddataplugsonthedatahubbyclickingthetabatthelower-leftedgeofablock,asshowninFigure10-25.Toredisplaythem,clickthetabagain.Whencreatingprograms,you’llfirstopenthecompletedatahub,andthenonceyou’veconnectedthedesireddatawires,youcanhidetheotherplugs.

NOTE Fromnowoninthisbook,I’llhideunuseddataplugsinprogramstomaketheprogramsmorereadable.

Page 288: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure10-25:Hidingunuseddataplugswillmakeprogramsmorecompactandunderstandable.

usingdatawiresacrossyourprogramWhenconfiguringprogramswithdatawires,youdon’thavetoconnectablocktotheonerightnexttoit;youcanconnectblockswhenthereareotherblocksinbetween,asshowninFigure10-26.

Figure10-26:Datawiresallowyoutoconnectblocksspreadoveryourprogram,asshownhere.Theconnectedblocksdonothavetoberightnexttoeachother.

furtherexploration

Page 289: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Inthischapter,youlearnedhowtocreateprogramsusingthefeaturesofdatawires.Mostoftheprogramsyou’vemadesofarwithdatawiresarefairlysmall,anddatawiresmaynotseemveryusefulyet.However,datawiresareessentialtomakingadvancedprogramsforyourNXTrobots.InChapter11,you’lllearnafewnewwaystousedatawiresbeyondsimplycontrollingmotorspeedsanddisplayingsensorreadingsontherobot’sscreen.

Thefollowingdiscoverieswillletyoupracticetheprogrammingskillsyougainedinthischapter.Postyoursolutiontothesediscoveriestothecompanionwebsiteathttp://www.discovery.laurensvalk.com/sothatyourfellowbookreaderscanseewhatyou’vemade!

DISCOVERY#54:TURNUPTHEVOLUME!Difficulty:EasyCreateaprogramthatrepeatedlysays“Goodmorning”atavolumebasedontheUltrasonicSensorreading.UsetheSoundblock’sdatahubtowireinavaluetochangethevolume.LookattheSoundblock’shelpsectiontodeterminewhichdataplugtouse,andthenputtheblocksinaLoopblockconfiguredtoloopforever.

DISCOVERY#55:CONTROLTHETHROTTLE!Difficulty:MediumCreateaprogramwithonlythreeprogrammingblocksandtwodatawiresthatwillmaketheHandmotorturn.ThespeedanddirectionoftheHandMotorshouldbecontrolledbyhowmuchandinwhichdirectionyouturnedtheWheelmotor,meaningthatyou’llusetheWheelmotorasaRotationSensor.Whichdataplugsdoyouneedtouseinordertocreatethisprogram?

DISCOVERY#56:SMARTBOTISWATCHINGYOU!Difficulty:ExpertCreateaprogramthatcountsthenumberofpeoplewalkingbyyourrobot.PlaceyourrobotinsuchwaythattheUltrasonicSensorcansensepeopleinfrontofit.PlacetwoWaitblocksinsideaLoopblock,andconfigurethefirstblocktowaituntilthesensorseessomeonepassingby;usethesecondonetowaituntilthepersonisoutofsight.Ultimately,theloopshouldgoaroundonce

Page 290: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

eachtimeitsensessomeonepassingby.Now,whenyoudisplaytheloopcountontheNXTscreen,you’redisplayinghowmanypeoplehavewalkedby!Toensurethatyourprogramworksproperly,placeaSoundblockinsidetheloopsothatyou’llhearasoundeachtimesomeonepassesby.

BUILDINGDISCOVERY#10:APOLITESMARTBOT!Inthisdiscovery,you’llgivetheSmartBotahatthatitcantakeoffwhenitnoticesthatsomeoneispassingby.Todothis,you’llexpandtherobotdesignwithanextramotorwhichyou’llcontrolwithaMotorblock.Forthearmmechanism,lookattherobot’sHandmotor.Whenyoufinishcreatingthenewrobotdesign,createaprogramthatmakestherobotinteractwithpeoplebymakingittakeitshatoffandtalkifitseessomeone.CanyouturntheSmartBotintoapoliterobot?

Page 291: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

11

usingdatablocksandusingdatawireswithloopsandswitches

Nowthatyouknowhowdatawireswork,youcandosomereallyinterestingthingswithmoreoftheprogrammingblocks.YoucanusesomeofthesenewblockstomaketheNXTcombineandprocesssensorvaluessothattheycanbeusedasinputvaluesforotheractions.Forexample,withthetrickslearnedinthischapter,you’llbeabletoprogramyourrobottodosomethingonlywhentwosensorsaretriggeredatthesametimeortodothingsrandomly,ratherthanperformingaseriesofpreprogrammedactions.

InthischapterI’llshowyouhowtodomathontheNXTwiththeMathblocksothatyou’llbeabletohaveyourrobotscalculate,forexample,thedistancetotravelbasedonasensorreading.I’llalsointroduceyoutoafewnewdataprogrammingblockssuchastheRandom,Compare,andLogicblocksaswellasafewnewtechniquestousewiththeSwitchandLoopblocks,byprovidingsampleprogramsandnewdiscoveries.

Thesetechniquesandprogrammingblocksareessentialtoadvancedrobotprogramsliketheonesyou’llcreateinPartIV,aswellasforadvancedprogramsthatyou’llcreateforyourownrobots.AsinChapter10,you’llusetheSmartBottotestyournewprograms.

Thediscoveriesinthischaptermightnotseemsointerestingatfirst,butonceyou’vemasteredmanyoftheessentialprogrammingskillsbysolvingthem,you’llbeabletocreatemuchmoreinterestingprogramsforyourrobotsandbuildsomereallysmartrobots!

datablocksTheCompletePalettecontainsaseriesofblocksthatyouhavenotusedyet:

Page 292: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

datablocks.Datablocks(Figure11-1)includetheMathblock,theRandomblock,theCompareblock,andtheLogicblock.Eachblockhasitsownfunction,buttheyallprocessvaluescarriedbydatawiresandgeneratenewvaluesbasedontheinputvalues.Thissectionwillexplainhowtousetheseblocksinyourprograms.

themathblockTheMathblockallowstheNXTtodoarithmeticoperationssuchasaddition,subtraction,multiplication,anddivision.InitsConfigurationPanel,youcanfillinplaceholdersfortwonumbers(AandB),andchoosewhichoperationshouldbeappliedtothem,suchasmultiplication(AwillbemultipliedbyB).Theresultisoutputwithadatawire.WhenyouusetheMathblock,you’lloftentransferoneorbothnumberstotheMathblockwithadatawireinsteadofenteringthemyourself,asyou’llseeinthesecondsampleprograminthischapter.

TheSmart-MathprograminFigure11-1showstheMathblockperformingamultiplication.TheNumbertoTextandDisplayblocksareusedtodisplaytheresultontheNXTscreen.

Nowyou’lllearnhowtousetheMathblockinprogramsforyourrobotstodomorethanjustdisplayavalue.

Figure11-1:TheMathblockintheSmart-Mathprogrammultiplies50by3anddisplaystheresult(150)ontheNXTscreen.(I’vehiddentheunuseddataplugstomaketheprogrameasiertounderstand.)

Page 293: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingthemathblockinamoreadvancedprogram

TheSoundblockcanplaytonesatspecificfrequencies:Thehigherthefrequency,thehigherthepitchyou’llhear.You’llusetheSoundblocktocreateaprogramthatplaystonesthatchangebasedonreadingsfromtheColorSensor.Yourrobotwillrepeatedlyplayshortbeeps,dependingonwhichcoloredball(fromyourroboticskit)isheldinfrontofthesensor.

Tomakethisprogramwork,you’llhavetheColorSensorblocksendsensorvaluestotheSoundblockwithadatawireconnectedtotheDetectedColorplug(whichoutputsavaluebetween1and6dependingonthedetectedcolor).TohavetheSoundblockplaytonesatafrequencythatyouspecify,youtransferthesensorvaluestotheblock’sToneFrequencyplug.Iftheblockreceivessmallvalues(around250)fromthedatawire,itplayslowbuzzes.Largenumbers(around4,000)maketheblockplayhighpitches.

Asyoucansee,thisdataplugrequiresfairlylargeinputvalues.However,sincetheDetectedColorvaluerangesbetween1and6(not250and4,000),youneedtoprocessthereadingsomehowsoitcanbeusedasinputtotheSoundblock.Toaccomplishthis,you’llusetheMathblocktomultiplythecolorvalueby250.Forexample,iftheColorSensorseesblue,thesensorvalueis2,andtheMathblockwillmultiplyitby250.Theresultisafrequencyof500,whichwillmaketheSoundblockplayalowtone.You’llhearahighersoundwhenthesensorseesaredball(frequency=1250).CreatetheSmart-SoundprogramshowninFigure11-2now.

Page 294: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-2:TheSmart-Soundprogram.InsteadoffillingintwonumbersintheMathblock’sConfigurationPanelasinthepreviousprogram,youfeedonevaluetotheblockwithadatawire.

DISCOVERY#57:MATHPRACTICE!Difficulty:MediumCreateaprogramthatcontinuouslydisplaystheLightSensorandUltrasonicSensorreadings,aswellasthesumofthetwo,ontheNXTscreen,asshowninFigure11-3.UseaMathblocktoaddthetworeadings,andaddaWaitblockconfiguredtowaitfor0.5seconds(intheLoopblock)sothatyou’llhaveenoughtimetoreadthedisplay.

Page 295: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-3:TheNXTscreeninDiscovery#57

therandomblockYouusetheRandomblocktogeneratearandomnumberforuseinyourprogram.Usetheblock’sConfigurationPaneltoselectarangefortherandomnumber,suchas35to47.TheRandomblockwilloutputtherandomvaluethroughaNumberdatawire,whichinthiscasewillbe35,47,orsomevaluewithinthisrange.

TheRandomblockisusefulwhenyouwantyourrobottodosomethingunexpected.Forexample,youcoulduseaRandomblocktomaketheSmartBot’sWheelmotorturnatarandommotorspeed,asshownintheSmart-RandomprograminFigure11-4.

Page 296: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-4:TheconfigurationoftheSmart-Randomprogram.TheRandomblockgeneratesarandomvaluebetween0and100,whichiscarriedtothePowerplugontheMotorblock,switchingonamotor.NexttheprogramwaitsuntilyoubumptheTouchSensor,atwhichpointtheloopreturnstothebeginning,andthemotorspeedchangestoanewrandomspeed.

DISCOVERY#58:RANDOMSOUND!

Page 297: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Difficulty:HardCombinetheSmart-SoundprogramwiththeSmart-RandomprogramtomaketheNXTplayarandomtone.UseaMathblocktoincreasethesizeoftherandomvaluegeneratedbytheRandomblock,andwirethenewvalueintotheToneFrequencyplugoftheSoundblock.Havetherobotplaytonesforonesecond,andthenwaituntilyoubumptheTouchSensor.Repeatthissequencecontinuously.Finally,expandtheprogramtoalsodisplaythefrequencyontheNXTscreen.

thecompareblockTheCompareblockcheckstoseewhetheravalueisgreaterthan(>),lessthan(<),orequalto(=)anothervalue.Youcanenterthevaluesyou’dliketocompareintheConfigurationPanel,oryoucansupplythevaluestotheblockwithdatawires(plugAandplugB).

TheCompareblockoutputsoneLogicdatawire(trueorfalse),basedontheresultofcomparingvalueAtovalueB.Forinstance,ifyousetOperationtoEquals,theblockoutputstrueifvalueAisequaltoB.

TheSmart-CompareprograminFigure11-5showstheCompareblockinaction.Inthisprogram,theRandomblocksendsarandomvalue(0,100,orsomewhereinbetween)totheCompareblock,whichcheckstoseewhetherthisvalueislessthan50.Ifitis,theWheelmotoronSmartBotspinsforwardforonerotation;ifnot,itturnsbackward.Thisbehaviorrepeats,andthemotorcontinuestorevolveinrandomdirectionsastherandomvalueschange.

thelogicblockInsomeofyourprogramsyou’veusedSensorblockstodeterminewhethertheTouchSensorwaspressedorwhethertheUltrasonicSensorvaluewasbiggerthantheconfiguredtriggervalue.TheresultswerecarriedawayfromtheblockswithLogicdatawires.

YoucanusetheLogicblocktocomparetwoLogicdatawires.Dependingonhowyouconfiguretheblock,itcanseewhetherbothwirescarrythevaluetrue.Ifso,itwilloutputavaluetrue.Ifnoneorjustoneofthetwoinputvaluesaretrue,itsoutputvaluewillbefalse.

YoucanuseaLogicblocktocreateaprogramthatturnsontheColorLampifboththeTouchSensorispressedandtheUltrasonicSensorsees

Page 298: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

somethingfartherawaythan100cm.Ifeitherorbothconditionsdonotoccur,theColorLampisswitchedoff,becausetheLogicblock’soutputisfalse.Figure11-6showstheSmart-Logicprogram.

Figure11-5:TheSmart-Compareprogram.TheCompareblockinthisprogramcheckstoseewhethertheRandomblock’soutput(between0and100)islessthan50.Ifitis,theCompareblock’soutputvalueistrue,andtheWheelmotorontheSmartBotturnsforward.Ifnot,theoutputvalueisfalse,andthemotorturnsbackward.

Page 299: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-6:TheSmart-Logicprogram.IftheTouchSensorispressedandtheUltrasonicSensorseessomethingthatisfartherawaythan100cm,thelampontheColorSensorisswitchedon.BecauseyouusetheresultsofthecompareandactionfunctionswithintheSensorblocks,youconnecttheLogicdatawirestotheYes/Nooutputplugsonthedatahubs.(I’vehiddentheotherdataplugs,suchastheDistanceplugontheUltrasonicSensorblock.)

logicoperationsWhenconfiguringtheSmart-Logicprogram,youcanselectfromfouroperationsintheLogicblock’sConfigurationPanel:And,Or,XOr,andNot.Eachoptionwillmaketheblockcomparethetwologicinputvaluesdifferently,asyou’lllearninamoment.Theoptionyouchoosewilldependonwhatyouwantyourprogramtodo.

Table11-1liststheavailableoperations,aswellastheinputvaluesthatwouldleadtoanoutputvalueoftruewitheachoftheoperations.(TheSmart-LogicprogramusestheAndoperation.)

table11-1:theoperationsofthelogicblockandtheiroutputvalues

Operation Outputvalueistruewhen...

And Bothinputsaretrue

Page 300: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Or Oneortwoinputsaretrue

XOr Oneinputistrueandtheotherisfalse

Withtheseoperations,youwirethetwoLogicdatawirestobecomparedtotheAandBinputplugsoftheblock,butitdoesn’tmatterwhichwireyouconnecttowhichplug.

notoperationWhenyouselecttheNotoperation,theLogicblockdoesn’tcomparetwoLogicdatawires;itonlydoessomethingwiththelogicvaluewiredintoplugAonthedatahub.Thisoperationjustinvertstheinputsignal:IftheinputAvalueistrue,theoutputwillbefalse;iftheinputAvalueisfalse,theoutputwillbetrue.

DISCOVERY#59:AND,OR,XOR,ORNOT?Difficulty:MediumInChapter7,youlearnedthatyoucouldusetheNXTbuttonsasTouchSensors.LiketheTouchSensorblock,theYes/NodataplugontheNXTButtonsblockoutputsavaluethatiseithertrueorfalse,dependingonwhethertheActionsettingspecifiedintheConfigurationPaneltakesplace.CreateaprogramwheretheColorLampisswitchedonwheneithertheEnterbuttonortheTouchSensorispressed(butnotboth).ThelampisswitchedonifadatawirewiththevaluetrueiswiredintotheActionplugontheColorLampblock.You’llhavetousetheLogicblocktoseewhetheronlyoneofthesensorsispressed,butwhichoperationdoyouuse?

switchblocksanddatawiresYou’veusedtheSwitchblocktoenableaprogramtomakedecisions,suchastodeterminewhetheraTouchSensorispressed.Asaquickreminder,seeFigure11-7,whichshowsaSwitchblockinaction.Recallthataconditionisastatementlike“TheTouchSensorispressed.”WhentheSwitchblockdeterminesthataTouchSensorisbeingpressed,theconditionistrue,andthe

Page 301: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

blocksontheupperhalfoftheSwitchblockarerun.Iftheconditionisfalse,meaningtheTouchSensorisnotpressed,theblocksonthelowerhalfoftheSwitchblockareruninstead.(SeeChapter6tolearnmoreaboutthebasicsofSwitchblocks.)

Figure11-7:TheSmart-TouchprogramcontinuouslycheckswhethertheTouchSensorisbeingpressed.Ifitis,theColorLampblinks(it’sswitchedonandoff).Ifnot,therobotsays“No.”

configuringswitchblockswithdatawiresInadditiontoworkingwithsensorreadings,aSwitchblockcanalsomakedecisionsaboutvalueswhenadatawireisconnectedtotheSwitchblock.

Forexample,youcouldconfigureaSwitchblocksothattheblocksinitsupperpartrunwhentheinputvaluesignalistrueandsotheblocksonthelowerpartrunwhentheinputsignalisfalse.Todothis,youconnectaLogicdatawiretotheSwitchblock.

TobeabletoconnectadatawiretoaSwitchblock,you’llselectaSwitchblockfromtheProgrammingPalette,placeitontheWorkArea,thensetthe

Page 302: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ControlparameteronitsConfigurationPaneltoValue,asyou’llseeintheSmart-Switchsampleprogramthatfollows.

Smart-Switchdisplaysarandomnumberbetween0and100ontheNXTscreenandalsodisplayswhetherthatnumberisgreaterorlessthan40.Theprogramfirstgeneratesarandomnumberbetween0and100.Next,withtheaidofaCompareblock,itcheckstoseewhetherthatnumberisgreaterorlessthan40.Ifgreater,theCompareblock’soutputvaluewillbetrue;otherwise,itwillbefalse.ALogicdatawiretransfersthisvaluetoaSwitchblock.IftheSwitchblockreceivesavalueoftrue,theupperpartsintheswitcharerun;ifthevalueisfalse,thelowerblocksarerun.

You’llfindtheSmart-SwitchprograminFigure11-8andFigure11-9.

DISCOVERY#60:TOTALORELSE!Difficulty:MediumCreateaprogramthataddstogethertheUltrasonicSensor(measuredincentimeters)andLightSensorvalues.UseaCompareblocktodeterminewhetherthetotalvalueisgreaterthan300,andwiretheoutputvalueofthisblockintoaSwitchblock.AddSoundblockstotheSwitchblockthatwillsay“Yes”whentheswitchreceivesavalueoftrueandwillsay“No”whenthedatawirecarriesavalueoffalse.PutalltherequiredblocksinaLoopblock.

Page 303: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-8:Step1:Becausethecompleteprogramrepeatscontinuously,youplacealloftheprogrammingblocksinsideaLoopblock.TheotherblocksshownhereallowtherobottodisplaytherandomnumberontheNXTscreen.ThatsamerandomnumberisalsosenttoaCompareblock,whichcheckstoseewhetheritisgreaterthan40.

Page 304: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-9:Step2:Ifthevalueisgreaterthan40,atruesignalissentfromtheCompareblocktotheSwitchblock,causingtheDisplayblockintheupperpart(inV)oftheswitchtoberun.Ifthesignalisfalse,thelowerblock(inX)isrun.ThenextDisplayblock(2d)inthisstepcompletesthelinethatiseventuallydisplayedontheNXTscreen.Everytwosecondsyourscreenwillshowanewlinelike26islessthan40.TheWaitblockgivesyouenoughtimetoreadthedisplaybeforethelooprepeats.

usingnumberandtextdatawiresandswitchblocks

RatherthanwiringaLogicdatawireintoaSwitchblock,youcanuseNumberorTextdatawires.WhenusingNumberdatawires,youcouldhaveblocksontheupperpartoftheswitchrunwhenthedatawirevalueis,say,5,andhavethelowerpartrunwhenthevalueis3.TheprocessisthesameforTextdatawires,exceptthatwhenusingthem,you’llusetextinsteadofnumbers.Youwon’tusethisfeatureinthisbook,butifyouwanttolearnmoreaboutit,youcanrefertotheNXT-GhelpsectionfortheSwitchblock.

connectingdatawirestoinsideswitchblocksInsomecasesitcanbeusefultoconnectdatawiresfromoutsideaSwitchblocktoblocksinsidetheswitch,asshowninFigure11-10.Forexample,youcandosowhenyouwanttouseanUltrasonicSensorvalueoutsidetheswitchthatyoualsowanttousewithablockinsidetheswitch,withouthavingtopollthesensoragain.Todoso,uncheckFlatView,andthenconnectthedatawires.WithFlatViewturnedoff,clicktheconditioniconstoswapbetweentheswitch’stwoSequenceBeams.

Page 305: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-10:YoucanconnectdatawiresfromoutsideaSwitchblocktoblocksinsideitonlywhenFlatViewisturnedoff.TheprogramshownherepollstheUltrasonicSensortocompareitsreadingtoatriggervalue.Iftheresultofthecomparisonistrue,themotorisswitchedon,atapowerlevelbasedontheUltrasonicSensorreading.Becausetherearenoblocksintheotherpartoftheswitch,whentheresultofthecomparisonisfalse,nothinghappens.

loopblocksanddatawiresPreviouslywhenyou’veusedLoopblocks,you’vetypicallyconfiguredthemtoloopforever,causingtheblocksinsidethelooptorepeatuntilyoumanuallyaborttheprogram.Youcanalsoconfigureloopblockstoloopacertainnumberoftimes,toloopacertainnumberofseconds,ortorepeattheblocksinsidetheloopuntilasensoristriggered.Youcanalsoendaloopwithadatawire.

WhenyousettheControlparameterintheLoopblock’sConfigurationPaneltoLogic,you’llseeaninputplugontherightsideoftheLoopblock,andyoucanconnectaLogicdatawiretothisplug.NowyoucanspecifywhethertheLoopblockshouldstoploopingwhenthisplugreceivesatrueorfalselogicvalue,asdemonstratedintheSmart-LoopprograminFigure11-11.While

Page 306: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

looping,theprogramcontinuouslycheckstoseewhethertheTouchSensorortheEnterbuttonontheNXTispressed.Ifoneorbotharepressed,theLogicblockoutputsatruevalue.BecausetheLoopblockisconfiguredtorepeattheblocksinsidetheloopuntilitreceivesthetruesignal,itendswhenasensorispressed,andtheSoundblockhastheNXTplayasound.

CreatetheSmart-LoopprogramnowasshowninFigure11-11.Smart-Loopisaveryusefulprogrammingconstruction,becauseithastheprogramwaitwhilecheckingtwosensors.ItactuallyfunctionslikeaWaitblock,exceptthataWaitblockcanpollonlyonesensor.

Figure11-11:TheconfigurationoftheblocksintheSmart-Loopprogram

DISCOVERY#61:PRESSANYKEYTOCONTINUE!Difficulty:EasyWiththeSmart-Loopprogramyoulearnedhowtocreateaprogramthatpausesuntiloneoftwosensorsistriggered.Byaddingsomeextrablocks,youcanevenpollthreesensors(ormore)atonetime.Createaprogramthatwillmakeasoundwhenyoupressabutton(eithertheLeftArrow,RightArrow,orEnterbutton)ontheNXT.YoucanseehowtodothisinFigure11-12,butthisprogramisn’tfinishedyet.CanyouconnectthedatawiresandselecttherightoperationintheLogicblockstomakeitwork?

Page 307: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure11-12:TheunfinishedprogramforDiscovery#61

furtherexplorationInthischapteryoulearnedaboutseveraldataprogrammingblocks,aswellassometricksforusingdatawireswiththeLoopandSwitchblocks.Thesetechniqueswillallowyourrobottoprocessandcombinesensorvaluesinordertousethemasinputsforactionssuchasmakingsoundsormoving.You’llseepracticalexamplesofthisinthenextthreechaptersofthisbook.Fornow,practiceyournewlyacquiredskillsinthefollowingdiscoveries.

DISCOVERY#62:ARITHMETICROTATIONS!Difficulty:HardForthisdiscovery,addamotortoSmartBotthatyoucanrotateeasilybyhand(connectawheeltoit).Next,createaprogramtodisplaythevaluesofthewheelmotor’sRotationSensorsontheNXTscreen,andwirebothvaluesintoaMathblock.IftheTouchSensorispressed,aMathblockshouldmultiplythetwosensorvalues;otherwise,itshouldsimplyaddthem.DisplaytheresultsontheNXT.Asyourotatethemotors,youshouldchangesumsorproductsontheNXTscreen.

BUILDINGDISCOVERY#11:BIONICHAND!TheSmartBothasprovedusefulforexperimentingwithsomeadvanced

Page 308: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

programs,butitcan’treallydomuch.Inthisdiscovery,you’llbuildaroboticclaw,attachittoyourhand,andusesensorsortheNXTbuttonstocontrolit.BesuretoaddtheUltrasonicSensorandprogramtherobotsothatthearmwillwarnyouwhenthesensorseesyouapproachawall.Usetheprogrammingtechniquesyoulearnedinthischaptertodisplayseveralsensorvaluesonthescreenortomakesoundsbasedonsensormeasurements.

NOTE YoumaywanttouseSmartBotinthenextchapter,butyoudon’thavetodoso.Ifyou’dliketoworkonBuildingDiscovery#11,taketheSmartBotapartifyoulike.

Page 309: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

12

usingvariables,constants,andplayinggamesontheNXT

Ifyou’vemadeitthisfar,you’rejustafewstepsawayfrommasteringalloftheprogrammingskillsinthisbook.Bynowyou’velearnedhowtousemanydifferentprogrammingblocks,aswellashowtoworkwithessentialtoolssuchasdatawires.ThischaptercompletestheprogrammingsectionofthisbookbyteachingyouhowtousetheNXTmemorywithvariablesaswellashowtouseconstants.

Inadditiontolearningaboutvariablesandconstants,you’llcreateaprograminthischapterthatcombinesalmostalloftheprogrammingskillsyou’velearnedsofar.ThissomewhatadvancedprogramwilldemonstrateyetanotherpossibilityoftheNXTsystem:ItwillletyouplayarealgameontheNXT!

usingvariablesThinkofavariableasakindofsuitcasethatcancarryinformation.Whenaprogramneedstorememberavalue(suchasasensorreading)forlateruse,itputsthatvalueinthesuitcaseandstowsitaway.Whentheprogramneedstousethevalue,itopensthesuitcaseandusesthestoredvalue.ThevariableisstoredintheNXT’smemoryuntilit’sneeded.

Onceinformationisstoredinavariable,youcanaccessitfromotherpartsofyourprogram.Forexample,youcouldstoreanUltrasonicSensorvalueinthesuitcaseandcompareitlatertoanewsensorreading.

Theprogramcanaccessthisstoredinformationatanytimewhilerunning,butthedataislostoncetheprogramstops.Tostoreandaccessvariableinformation,youuseaVariableblock,whichyou’llrecognizebyasuitcaseicon

Page 310: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

ontheblock.Figure12-1showsanoverviewofwhathappenswhenyouusevariables.

definingavariableEachvariablehasanameandcontainsavalue.Forexample,avariablemightbecalledReadingwithavalueof56.Likedatawires,avariablecancontaineitheranumericvalue(suchas56),alogicvalue(suchastrue),oratextvalue(suchas“hello”).

Figure12-1:Values(liketheUltrasonicSensorreadingshownhere)canbestoredinvariablesintheNXT’smemory.Onceavalueisstored,aprogramcanretrieveitfrommemoryinordertouseit.You’lllearnwhatthisprogramdoesandhowtocreateitlaterinthischapter.

Butbeforeyoucanuseavariableinyourprogram,you’llneedtodefineitintheEditVariablesdialogbox,asshowninFigure12-2.

Todeleteavariable,opentheEditVariablesdialogbox,selectthevariableyouwanttodelete,andclickDelete.

NOTE Youcanusevariablesonlyintheprograminwhichyou’vedefinedthem.

Page 311: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingthevariableblockOnceyou’vedefinedavariable,youcanuseitinaprogramwiththeVariableblock.TheVariableblockcanreadvaluesfromorwrite(store)valuestoavariableintheNXTmemory.ToconfigureaVariableblock,firstselectthevariableyouwanttoreadorwriteintheListboxontheConfigurationPanel.Next,intheActionbox,specifywhetheryouwanttowriteavaluetothevariableorreadavaluefromit.WhenyouchooseWrite,theblockstoresthevaluethatyouenterintheValueboxofitsConfigurationPanel.

Ifadatawireisconnectedtotheblock’sValuedataplug,thevaluecarriedbythiswireisstored.Ifavaluewasstoredinthisvariablepreviously,theoldvalueiserased,andthenewoneisstoredinstead.

Figure12-2:Definingavariableinthevariableeditingwindow.Step1:SelectEdit▸DefineVariables.Step2:ClickCreatetomakeanewvariable.Step3:Enteranameforthevariable(Reading),andselectthedatatype(Number).Onceyou’vedonethis,clickClose.

Whenconfiguredtoreadavalue,theVariableblockretrievesthe

Page 312: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

informationfromtheNXT’smemoryandoutputsitwithadatawiresothatthevaluecanbeusedintheprogramto,forexample,defineamotor’sPowersetting.

Whenreadingavariable’svalue,thevalueisn’tchanged,soifyoureaditagainwithanotherVariableblock,you’llgetthesamevalue.

creatingaprogramwithavariableTheSmart-VariableprogramshowninFigure12-3storestheUltrasonicSensorvalueinavariablecalledReading.Afterfiveseconds,itretrievesthevaluefromthevariableanddisplaysitontheNXTscreen,whichmeansthatthevalueyouseeontheNXTscreenrepresentswhatthesensormeasuredfivesecondsago.(Beforeconfiguringthisprogram,defineavariablecalledReadingtocarrynumericinformation,asshowninFigure12-2.)

Smart-Variabledemonstratestheconceptofusingvariablesinaprogram,butit’saverybasicprogram.Onceyou’vecreatedit,asshowninFigure12-3,continuepracticingwithvariablesinDiscovery#63.

Page 313: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-3:TheconfigurationoftheblocksintheSmart-Variableprogram.TheWaitblockattheendoftheprogramgivesyoutimetoseethevalueontheNXTscreenbeforetheprogramends.

DISCOVERY#63:OLDVS.NEW!Difficulty:MediumYou’llcreateanotherprogramwithvariablesthatrepeatedlycomparesnewsensorreadingstothesensorvaluestoredinavariableatthebeginningoftheprogram.Ifthenewreadingishigher,therobotshouldsay“Yes”;otherwise,itshouldsay“No.”Figure12-4showspartoftheprogram.

Page 314: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-4:AstartingpointforDiscovery#63

HINT Whatisyourfirststepwhencreatingaprogramwithdatawires?WhichVariableblocksmustreadorwriteavalue?Howdoyouconnectthedatawires?

changingvariablevaluesPrevioussectionshaveshownyouhowtowritevaluestoavariableandhowtoreadvaluesfromone.Sometimesyou’llwanttochangeavariable’svalue,forexampletoincreaseitsvaluebyone,suchaswhenyouwanttouseavariabletotrackahighscoreoratotalnumberofTouchSensorpresses.TheSmart-Countprogramyou’llnowcreatedemonstrateshowtouseavariabletotrackthenumberoftimesaTouchSensorisbumped(pressedandthenreleased).

YoubeginbydefininganewnumbervariablecalledPressCounttostorethenumberofTouchSensorbumps.TheprogramwillwaituntiltheTouchSensorisbumped,atwhichpointthePressCountvaluewillincreasebyone.Tomakethecountingongoing,you’llalsouseaLoopblockinthisprogram.

Buthowdoyouincreasethevariable’svaluebyone?AsshowninFigure12-5,youuseaVariableblocktoreadthePressCountvalue.ThenyoutransferthisvaluetoaMathblock,whichaddsonetothevalue.TheresultofthisadditioniswiredintoanotherVariableblockconfiguredtowrite(store)thenewvalueinthePressCountvariable,whichisthereforenowincreasedbyone.TheresultoftheadditionisstoredinthevariableanddisplayedontheNXTscreen.Byusingthismethod,youcanchangeanyvariable’svalue.Thissamplehasshownyouhowtoaddonetoavalue,butyoucanusethesamemethodtosubtractfromavalue.

NowcreatetheprogramasshowninFigure12-5.

Page 315: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

initializingvariablesWhenprogrammingwithvariables,it’simportanttoinitializethembygivingthemastartingvalue.YoudothisintheSmart-CountprograminFigure12-5bysettingthePressCountvalueto0atthebeginningoftheprogram.Initializingvariablesmakesaprogrammorereliablebymakingsurethateachtimeyouruntheprogram,itwillfunctionthesamewaybecauseitstartsatthesameplace.

Figure12-5:TheSmart-CountprogramcountsthenumberofTouchSensorpressesanddisplaysthetotalontheNXTscreen.

It’sagoodideatoinitializevariablesatthebeginningofaprogram,

Page 316: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

especiallywhenyou’recreatingbiggerprograms.Ifyoudon’t,youmayfindthattheinitialvariablevalueisnotequalto0,whichmaycausetheprogramtomalfunctionortoactunpredictably.Althoughusuallynotthecase,yourrobotmight,forexample,saythatyoupressedtheTouchSensorfivetimes,evenwhenyouhaven’ttoucheditall,becausethevariablecountwasleftat5.

DISCOVERY#64:SMARTERCOUNTPROGRAM!Difficulty:HardInthisdiscovery,createaprogrambasedontheSmart-Countprogramthatusesavariabletotrackthenumberoftimesthearrowbuttonsarepressed.IfyoupresstheRightArrowbutton,thevariable’svalueshouldincreasebyone;ifyoupresstheLeftArrowbutton,itshoulddecreasebyone.Displaythevariable’svalueontheNXTscreen.

HINT UseaLoopblocktowaituntilabuttonhasbeenpressed(asintheSmart-Loopprogram,asshowninFigure11-11),andthenuseaSwitchblocktodeterminewhichbuttonwaspressed.IntotheSwitchblockaddtheblocksyou’reusingtomodifythevariable’svalueandblocksthatwaituntiltheNXTbuttonisnolongerpressed.

Page 317: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-6:Todefineaconstant,selectEdit▸DefineConstants(1),andclickCreate(2).Giveyourconstantaname,selectthetypeofvalueitshouldcontain,andenterthatvalue(3).

usingconstantsAconstantisavaluethatcannotbechangedwhileaprogramisrunning.Forexample,ifyourprogramneedstoconvertadistancemeasuredininchestooneincentimeters,youwoulduseaconstanttomultiplytheinchvalueby2.54.BycreatingaconstantinanNXTprogram(let’scalltheconstantInchToCm)withthevalue2.54,eachtimeyouwanttoperformthisconversionyouwouldsimplyusetheconstantInchToCm.

Youmustdefineaconstantbeforeyoucanuseit,asshowninFigure12-6.Onceyou’vedefinedone,youcanuseitinanyofyourprograms.

Page 318: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingtheconstantblockYouuseConstantblockstointegratedefinedconstantsintoyourprograminoneoftwoways.IntheActionboxoftheConstantblock’sConfigurationPanel,youspecifywhethertoselectaconstantfromofalistofdefinedones(Choosefromlist)ortouseacustomconstant(Custom).WhenyouselectChoosefromlist,theConstantblockfunctionslikeaVariableblockconfiguredtoreadavalue:Theconstantisreadandoutputwithadatawire,whichthentransfersthevaluetoanotherblockintheprogram.WhenyouselectCustom,youusetheblocktooutputavaluethatyouenterintheConfigurationPanel.(Youdon’tneedtodefinethisconstantinadvance.)TheCustomconfigurationisusefulwhenasinglevalueneedstobetransferredtomultipleblocks,asshowninFigure12-7.

creatingaprogramwithconstantsTheSmart-Constantprogram(showninFigure12-7)usesbothconfigurationsoftheConstantblockasitconvertsinchestocentimetersanddisplaysbothvaluesontheNXTscreen.You’lluseacustomconstantforthenumberofinchestoconvertsothatwhenyouruntheprogramagaintoconvertanothervaluetocentimeters,you’llneedtoadjustonlythevalueintheConstantblock,ratherthaninboththeMathandDisplayblocks.You’llchoosetheconstantfortheconversion(2.54)fromthelistofconstantsasdefinedpreviouslyinFigure12-6.

Page 319: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-7:TheSmart-Constantprogram.ThefirstCustomblock(blockb)isacustomconstant,whilethesecondone(blocke)isaconstantyoudefinedpreviously.

Page 320: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

playingagameontheNXTYou’llnowcreateonelargeprogramthatcombinesmanyoftheprogrammingtechniquesthatyou’velearnedthroughoutthisbook.I’veintroducedeachprogrammingtechniqueandblockpreviouslywithshortexampleprograms,butnowyou’llseehowtocombinethemforuseinalargerprogram.YourgoalwillbetocreateaprogramthatletsyouplayagameontheNXT.TheNXTscreenwilldisplaythegame,andtheNXTbuttonswillbethegamecontrollers.

Whenplayingthegame,targetswillappearontheNXTdisplayrandomlyontheleftandright.Whenatargetappears,you’llpresstheleftorrightNXTbuttonquicklytodestroyit,andtheprogramwillpopupthenexttarget,asshowninFigure12-8.Themoretargetsyouhitwithin30seconds,thehigheryourscore.Ifyoumissatarget,yourscorewilldecrease.

Figure12-8:TheSmart-Gameprograminaction

NOTE Atthispointyoushouldbeabletore-createprogramswithoutviewingalltheConfigurationPanels,sofromnowonyou’llseetextcommentsontheprogrammingimagesthattellhowtoconfiguretheblocks.Ifthetextdoesn’ttellhowtosetacertainsetting,leavethedefault.

BecausetheSmart-Gameprogramismuchlargerthananyprogramyou’vecreatedsofar,takeagoodlookatexactlywhattheprogramshoulddo,asshowninFigure12-9.Theprogramconsistsofseveralsections,eachofwhich

Page 321: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

hasaspecificfunctionintheprogram.You’llcreatethesesectionsstep-by-step.Asyoucreateeachsection,you’llfinddescriptionsofhoweachsectionworksandwhyyouneeditintheprogram.

Steps1through6configuretheblocksthatdisplayatargetonthescreenandadjustthescorewhenyoutrytohitatargetbypressingabutton.YouconfiguretheLoopblockinstep7(repeatingtheseactionsfor30seconds)andaddablocktosettheinitialscoretozero.Alsoinstep7,youaddblockstodisplaythefinalscore.

definingthevariablesThisprogramhasthreevariables.TheScorevariabletracksthetotalscore,andthereforeitisdefinedtocarrynumericalvalues.ThePositionvariablestoresthetarget’sposition,andtheButtonvariablestoreswhichbuttonwaspressed.

BeforeupdatingtheScorevariable,theprogramcheckstoseewhetherPositionandButtonvariablesareequal.Tomakethiscomparisoneasier,you’llmakePositionandButtonnumbervariables.You’llindicateleftwith1andrightwith2.Forexample,iftheuserpressestheLeftArrowbutton,theprogramwillsettheButtonvariableto1.Onceyou’vedefinedtheScore,Button,andPositionvariablesasnumerical,you’rereadytobegincreatingtheprogram.

Figure12-9:AnoverviewoftheSmart-Gameprogram.Thenamesofthevariablesusedinthisprogramareitalicized.You’llre-createthisprogramwithprogrammingblocksinsevensteps.

step1:displayingatargetrandomlyTheprogramusesaSwitchblocktodecidewhethertodisplayatargetontheleftorrightsideoftheNXTscreen,asshowninFigure12-10.Tomakethisarandomdecision,youuseaRandomblocktogenerateanumberbetween0and99,andyouuseaCompareblocktoseewhetherthegeneratedvalueislessthan

Page 322: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

50(theblock’soutputisthentrue).BecausehalfofthenumbersgeneratedbytheRandomblockwillbelessthan50,halfthetimethattheprogramrunstheseblocks,theCompareblockwilloutputatruevalue,causingthetargettobedisplayedontheleft.TherestofthetimetheCompareblock’soutputwillbefalse,andthetargetwillbedisplayedontheright.Thetarget’spositionisstoredinavariable,tobecomparedlaterwiththeuserinput.Fortheleftposition,1iswrittentothePositionvariable;fortheright,2iswrittentothevariable.Figure12-10showstheblocksthatdisplaytherandomtargetandsetthePositionvariable.

Figure12-10:Theconfigurationoftheblocksplacedinstep1

step2:waitinguntilabuttonispressedOncethetargethasbeendisplayed,theprogramwaitsuntiltheuserpressesanarrowbuttonontheNXT.Youaccomplishthiswiththetechniqueofpollingtwosensorsatthesametime,asyouusedinFigure11-11.Configuretheblocksforstep2asshowninFigure12-11.

Page 323: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-11:Theconfigurationoftheblocksplacedinstep2

step3:storingwhichbuttonispressedWhenyoupressabuttoninthepreviousstep,theLoopblockstopslooping,andtheprogramjumpstotheblocksyou’llplaceinthisstep.Becauseprogrammingblocksarerunsoquickly,thenextblockwillrunbeforeyoucanreleasethepressedbutton,soyou’llassumethatthebuttonisstillpressedastheprogramrunsthroughtheblocksinthisstep.Asaresult,you’llsimplyuseaSwitchblocktoseewhethertheLeftbuttonispressed.Ifso,yousettheButtonvariableto1,andyouwaituntilthebuttonisreleased.Iftheleftbuttonisnotpressed,youknowthattherightbuttonis,andyousettheButtonvariableto2andwaituntiltherightbuttonisreleased,asshowninFigure12-12.

Page 324: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-12:Theconfigurationoftheblocksplacedinstep3

step4:comparingthepositionandbuttonvariables

Atthispointintheprogramyouknowthepositionofthetarget(asstoredinvariablePosition),aswellaswhichbuttontheuserpressed(storedinButton).Ifthesevaluesareequal(bothare1orbothare2),youknowthattheuserhasmadethecorrectchoice,andthescoreisincreasedbyone.Iftheyarenotequal,theuserclickedthewrongbutton,andthescoreisdecreasedbythree.

You’llplacetheblocksrequiredtomodifythescoreinaSwitchblock.TheSwitchblockgetsinputfromaCompareblockthatdetermineswhetherPositionisequaltoButton.Ifthetwovaluesareequal,theCompareblockoutputstrue,andtheblocksintheupperpartoftheSwitcharerun.

You’llplacetheblockstomodifythescoreinthenextstep.Inthisstep,configuretheblockstocheckwhetherButtonequalsPosition,asshowninFigure12-13.

Page 325: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-13:Theconfigurationoftheblocksplacedinstep4

step5:adjustingthescoreIfButtonandPositionwereequal,theblocksintheupperpartoftheSwitchshowninstep4arerun.Inthisstep,you’llplacetheblocksthataddonetotheScorevariable.TheNXTwilltellyouthatyou’vemadethecorrectchoicebydisplayingaVsignonthescreenandbyplayingahighnote.Theblocksinthelowerpartoftheswitchsubtractthreefromthescore,displayanXsignonthescreen,andplayalownote.Figure12-14showshowtoconfiguretheblocks.

Page 326: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-14:Theconfigurationoftheblocksplacedinstep5

step6:displayingthecurrentscoreTheblocksinstep6displaythecurrentscoreandgiveyoutimetoseethescoreaswellastheVorXsignontheNXTscreenbeforetheprogramgoesbacktodisplayanewtarget.Figure12-15showstheblocksthatdisplaythescore.

Page 327: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-15:Theconfigurationoftheblocksplacedinstep6

step7:makingtheprogramrepeatfor30seconds

Theblocksyou’veplaceduptonowdisplayatarget,waitforabuttonpress,andmodifythescorebasedonuserinput,butyoudon’tyethaveaworkinggame.Toturnyourstepsintoaworkinggame,dragalltheblocksyouplacedinsteps1to6intoaLoopblockconfiguredtoloopfor30seconds.

Finishtheprogrambyaddingablockatthebeginningtosettheinitialscoretozero,andaddblockstodisplaythefinalscore.Figure12-16showsthefinishedprogram.

Congratulations!You’vefinishedtheSmart-Gameprogram.Nowrunitandseewhichscoreyoucangetin30seconds.

NOTE Ifyou’reunabletogetthisprogramtoworkasdescribed,downloadaworkingversionfromthecompanionwebsite.

expandingtheprogramYou’venowseenhowtocombineyourprogrammingskillstocreateonelargeprogram.Butthefundoesn’thavetoendhere.Herearesomesuggestionsfor

Page 328: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

program.Butthefundoesn’thavetoendhere.Herearesomesuggestionsforcustomizingthisprogramthatwillmakeittrulyyourown:*Addmoresoundstotheprogram:Playapplausewhenthecorrectbuttonispressedandascreamifyoupressthewrongone.Also,makeyourprogramplayatuneofyourowncreationoncethegameisover.

Figure12-16:Theconfigurationoftheblocksplacedinstep7.MostoftheblocksintheLoophavebeenhiddenheretobetterfocusonthenewlyplacedblocksinthisstep.

*CreateastartupscreenthatisdisplayedontheNXTatthebeginningoftheprogram.Useimages,lines,anddrawingstocustomizeyourscreen.AddextrablockstohavetheNXTdisplayPresstheenterbuttontostartthegame!onitsscreen.

*AlthoughtheSmart-GameprogramusesonlytheNXT,thatdoesn’tmeanyoucan’tusethemotorsandsensorsconnectedtotherobot.ThinkofawaytousetheColorLampinyourprogram,orhavetheHandmotormovefasterandfasterasyoumakemoremistakes.

furtherexplorationCongratulations!You’vecompletedalloftheprogrammingchaptersinthisbook.Nowyou’rereadytolearnhowtobuildandprogramthreemorecoolrobotsinthelastpartofthisbook.

Butbeforeyoudo,takealookatthefollowingdiscoveries.Thesearemore

Page 329: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

difficultthantheotheronesyou’vedonesofar,butrememberthattherearemultiplesolutionstoeach.Givethematry.Ifyouthinkyouhaveagoodsolution,postittothecompanionwebsite(http://www.discovery.laurensvalk.com/)toseewhatotherreadersthink!

DISCOVERY#65:SMART-GAMEPROGRAMADVANCED!

Difficulty:HardExpandtheSmart-Gameprogramsothatitwilldisplaytargetsatthreelocationsinsteadofonlytwo.Displaythethirdtargetinthemiddleofthescreen,andusetheEnterbuttontohitit.

DISCOVERY#66:BRAINTRAINER!Difficulty:ExpertTrythisifyou’reupforareallycomplicateddiscovery.Createaprogramthatdisplaysrandomadditionproblems(forexample,7+6).TheuserdecideswhetherthedisplayedansweriscorrectbypressingtheLeftArrowbutton(incorrect)ortheRightArrowbutton(correct),asshowninFigure12-17.

Halfthetime,acorrectanswershouldbedisplayed.Thegameshoulddisplaynewsumsfor30seconds,afterwhichitshoulddisplaythetotalscore.Eachcorrectbuttonclickisworthonepoint,buteachmistakecostsfivepoints.

Youcancreatethisprogramusingonlytheprogrammingblocksdiscussedinthisbook,butit’sstillquitedifficulttomake.Seethecompanionwebsiteforthefullprogram,aswellasadescriptionofhowitworks.

Page 330: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure12-17:AnexampleadditionprobleminNXTBrainTrainergame

BUILDINGDISCOVERY#12:WHACK-A-MOLE!TheSmart-GameprogramisjustoneexampleofagameyoucanplayontheNXT.ThisdiscoverychallengesyoutobuildaconstructionsimilartotheWhack-a-Molegame.UseNXTmotorstorandomlymakemolespopupoutofaframeofLEGOpieces,andthenusetheNXTbuttonsorTouchSensorstowhackthemolesdown.CreateyourownadvancedprogramforthismachinetoturnitintoarealWhack-a-Molegame.YoucanmaketheNXTdisplayhighscores,playsounds,orincreasethedifficultylevelastimepasses.

Page 331: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PARTIV

advancedrobotprojects

Page 332: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

13

snatcher:theautonomousroboticarm

PreviouschapterstaughtyouagreatdealaboutprogrammingNXTrobots.Nowthatyou’vereachedanadvancedlevelofprogramming,you’rereadytobuildsomemorecomplicatedrobotsinthisandthenextchapters.ThischapterwillteachyoutobuildtheSnatcher,anautonomousroboticarmthatcanfindandpickupobjects,asshowninFigure13-1.

TheSnatcherusestwoNXTmotorstocontrolasetoftreads,allowingtherobottomoveinanydirection.YoucontrolitsmovementlikeyoucontrolledtheExplorerinChapter4byadjustingthepoweranddirectionoftheDrivingmotorstocontroltherobot’sspeedanddrivingdirection(asshowninFigure4-4).

understandingthegrabberDrivingaroundontreadsmaybeinteresting,butthereallycoolpartofthisrobotisitsmultifunctionalgrabber.Normallygrabbingandliftingobjectsrequirestwomotors:onetograbtheobjectandanothertoliftit.TheSnatcherrobotrequiresjustonemotor(whichIcalltheGrabbermotor)toaccomplishbothtasks,becauseofauniqueconstructionofLEGObeams,axles,andgears.You’lltakealookatthistechniquenow,butyouwillreallyunderstandhowitworkswhenyoubuildtherobot.

Page 333: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-1:TheSnatchercanfindandpickupobjects.

thegrabbingmechanismFigure13-2showshowtheSnatchergrabsobjects.AstheNXTmotorspinsforward,asmallgear(indicatedwithanumber1)makesabiggergear(2)rotate

Page 334: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

inthedirectionshownbythearrowinthefigure.Thisrotationstartsachainreactionofmovingbeams,whichultimatelycausesthegrabbertograspobjectspositionedbetweenitsfingers(6).Whenthemotorspinsbackward,thereverseoccurs,andthegrabberopens.Thebeamsmarked3,4,and5simplytransfertherotationalmovementofthemotortothegrabbersoitcancloseitsclaws.Construction4connectsthebeamsnumbered3and5inordertoallowsmoothmovement,evenwhenthegrabberarmispositionedasshowninthesecondimageofFigure13-1.

theliftingmechanismOncetheSnatcherhasgrabbedanobject,itcanliftit.Butbeforeyoulookathowtherobotdoesthis,you’llseeasimplifiedversionofthesituation.

AsshownonthetopofFigure13-3,asyoumovethebiggear(2)withyourhand,thebeamsnumbered7,whichrepresentthegrabberandthemotor,moveasindicatedbythegrayarrows.Nomatterwhatthemovementis,thesepartsremainparalleltotheground,andthepartslabeled8remainperpendiculartotheground.Toreallyunderstandhowthisworks,buildthestructureshownwiththepartsinyourNXTroboticskit.

Page 335: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-2:Grabbingobjectsbyturningthemotorforward

Thismechanismworksonlybecausegear2doesnotmoverelativetothebeamlabeled9,sincethey’reconnectedwithapin(10)asshowninthefigure(itmakesparts2and9formonefixedpart).So,turninggear2directlymakesthebeamlabeled9move.

ThebottomofFigure13-3showshowtheSnatcherliftsobjects.Themechanismisactuallyquitesimilartotheoneshownonthetop,exceptthattherealSnatcherdoesn’thavethispin(10),whichwouldturnparts2and9intoonefixedpart,enablingthegear(2)todirectlycontrolthebeamslabeled9.Thisrobotusesdifferentpartstolockthebeamstothegear.

OncetheSnatcherhasgrabbedanobject,thepartslabeled10(shownonthebottomofFigure13-3)nolongermoveastheydidinFigure13-2.Instead,theylockinpositionandmovejustlikethebeamsnumbered9showninthisimage.Sincethegear(2)isconnectedtothenumber10parts,itisnowindirectlyalsoconnectedtothenumber9parts(becausetheconstructionsarefixed),andtherobotcanliftobjects.

Page 336: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-3:OncetheSnatcherhasgrabbedanobject,itcanliftit.Hereisasimplifiedoverviewoftheliftingtechnique(top),withanillustrationofthe

Page 337: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

actualrobot(bottom).

buildingthesnatcherNowthatyou’vegottenasenseofhowtheSnatcher’sgrabbermechanismworks,it’stimetobuildtherobottolearnhowitreallyworks.Todoso,followthedirectionsonthenextpages,butfirstselectthepiecesyou’llneed,asshowninFigure13-4.

Figure13-4:TherequiredpiecestobuildtheSnatcher

Page 338: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 339: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 340: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 341: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 342: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 343: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 344: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 345: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 346: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 347: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 348: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 349: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 350: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 351: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 352: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 353: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 354: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 355: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 356: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 357: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 358: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 359: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 360: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 361: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 362: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 363: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 364: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 365: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 366: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 367: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

creatingobjects

Page 368: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

YoucanmodifytheSnatcher’sarmtograbalmostanythingaslongastheobjectisn’ttooheavy,buttheversionyou’vejustbuiltisdesignedtopickuppaperrings,liketheonesshowninFigure13-5.Useconstructionpapertomakeaboutfourpaperringsindifferentcolors(yellow,blue,red,andgreen)beforeyouprogramtherobot.

programmingthesnatcherHavingbuilttheSnatcherandcreatedobjectsforit,you’rereadytoprogramit.You’llcreateaprogramthatmakestheSnatcherfind,grab,lift,andmoveanobject,aswellasidentifytheobject’scolor.Eachtaskshouldrunautonomously,whichmeansthatalltasksmustbeperformedwithouthumaninteraction.

Figure13-5:TheSnatcherwillgrabtheseobjects.Insteadofgluingtheobjects,

Page 369: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

youmayalsostaplethem.Ifyoudon’thaveconstructionpaperindifferentcolors,pickthickpaperofanycolor,suchasblackorbrown,andstapleorgluelighter-weight,coloredpaperaroundit.

You’llusetheUltrasonicSensortofindtheobjectandusetheDrivingmotorstoapproachtheobjectandpositionitbetweentherobot’sfingers.TheGrabbermotorwillgrabandlifttheobject,andtheColorSensorwillidentifythecoloroftheobjectthatwaspickedup.Finally,therobotwillturnaroundandthendroptheobjectelsewhere.Figure13-6showsanoverviewoftheSnatcherprogram.

creatingthemyblocksBecausethisprogramwillrequiremanyprogrammingblocks,you’llusefiveMyBlockstomakethefinalprogrameasiertounderstandandcreate,asshowninFigure13-6.

NOTE Ifaprogrammingfigureinthischapterdoesn’tmentionchangingaparticularsettingonablock,justleavethatsettingunchanged.

Figure13-6:AnoverviewoftheSnatcherprogram.Notethattherobotsearchesfortheobjectandmovesclosertoittwice.Afterthefirstsearchandapproach,therobothasabetterviewoftheobject,whichallowsittomorepreciselyfindtheobject’spositionduringthesecondsearch.

myblock#1:grabThisblockwillmaketherobotgrabandlifttheobjectpositionedbetweentherobot’sfingers.Ifthere’snothingtograb,thisblocksimplyclosesandraisesthegrabber.

YouconfiguretheGrabbermotortoturnforwarduntiltheTouchSensorinsidetheSnatcherdetectsthatthegrabberisliftedallthewayup.ConfiguretheblocksthatdothisasshowninFigure13-7,andthenturnthemintoaMyBlockcalledGrab.(Also,selectsomeappropriateiconstomakeiteasiertoremember

Page 370: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

whattheblocksdo.)

Figure13-7:TheconfigurationsoftheblocksintheGrabMyBlock

myblock#2:releaseThisnextMyBlocklowerstherobot’sgrabberandopensitsclaws,releasingtheobject.

Youshouldusethisblockonlywhenthegrabberisalreadyliftedup(becauseoftheGrabMyBlock).Althoughonlyoneblockisrequiredtoreleaseanobject,you’llcreateaMyBlockforthisactiontomakethemainprogrameasiertounderstand.ConfiguretheblockasshowninFigure13-8,andthenturnitintoaMyBlockcalledRelease.

Figure13-8:TheconfigurationoftheblockintheReleaseMyBlock

myblock#3:findobjectFigure13-9showshowtheSnatcherfindsobjects.Whenpinpointingobjects,Snatcherlooksfortheclosestobjectinrangewhileturningtotheright.After

Page 371: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

scanning,itturnsintheoppositedirectiontothepointwhereitsawtheclosestobject.OncetheSnatcherhasrunthisblock,itshouldbefacingtheobject.

Astherobotturnsfor180degrees,theUltrasonicSensorconstantlymeasuresdistances.Thelowestvalueitrecordsisthedistancetotheobject,andyoustoreitinavariablecalledClosest.YousetClosest’sinitialvalueto256(cm)becausethesensorcannotmeasureanythingfartheraway.AnytimethesensormeasuresadistancecloserthanthevalueinClosest,theoldvalueisthrownaway,andthenewsensormeasurementisstored.Thisway,youhavetherobotforgetallbuttheclosestmeasurement.

Thevaluesofthemotors’RotationSensorschangeastherobotturns.Becausetherobotneedstorememberwhereitsawtheclosestobject,youstoretheRotationSensorvalueofmotorCinavariablecalledDirectionwhenevertheClosestvalueisupdatedwithanewvalue.Intheend,theDirectionvariableshouldcontainthevalueoftheRotationSensorasmeasuredwhentherobotsawtheclosestobject.Afterturningfor180degrees,theSnatcherturnsleftandstopswhentheRotationSensorvalueequalsthatoftheDirectionvariable.Whenitstops,therobotshouldpointstraightattheobjectandbereadytoapproachandgrabit.

Figure13-9:Findingtheclosestobjectinrange

DefinetwovariablescalledClosestandDirection(bothnumericalvariables),configuretherequiredblockstofindobjectsasshowninFigures13-10to13-12,andthenturnthemintoaMyBlockcalledFindObject.

Page 372: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-10:TheseblockspreparetheSnatchertofindobjects:therobotturnsleft,initializesthevariables,resetstherotationsensorinmotorC,andstartsturningright.

Figure13-11:Theseblockstakecareofsearchingforobjects,asdiscussedinFigure13-10.

Page 373: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-12:Oncethesearchcompletes,theseblocksmaketherobotreturntotheplacewhereitspottedtheclosestobject.

myblock#4:movecloserThisblockmakestheSnatchermoveclosertothefoundobject,basedonthepreviouslymeasureddistancetoit.Iftheobjectisfaraway,theSnatchermovesfartherthanwhenitisclosealready.Toaccomplishthis,aMathBlockmultipliesthevalueoftheClosestvariableby45andtransferstheresulttotheDurationsettingoftheMoveBlock.Forexample,aclosestrecordeddistanceof10cmwouldmaketherobotapproachtheobjectbyturningthemotors450degrees,whileameasurementof5cmwouldmakeitturnonly225degrees.

ConfiguretherequiredblockstomakethismovementasshowninFigure13-13,andturnthemintoaMyBlockcalledMoveCloser.

myblock#5:saycolorThisMyBlocksimplyplaysasoundfile(suchas“Red”)basedonthedetectedcoloroftheobject.Youmayhavealreadycreatedthisblock.Ifyouhaven’t,dosobyfollowingthedirectionsinFigure7-16,ordownloaditfromthecompanionwebsite.

Page 374: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-13:TheconfigurationsoftheblocksintheMoveCloserMyBlock.TobeabletoselectClosestintheVariableblock,youmayneedtodefinethisvariableagain.

creatingthefinalprogramNowthatyou’vecreatedyourMyBlocks,youcanusethemtocreatethemainprogram(showninFigure13-6)tomaketheSnatcherautonomouslyfind,grab,lift,andmoveanobject.Figure13-14andFigure13-15showhowtocreatethefinalprogram.

Figure13-14:Beforetherobotstartslookingforobjects,itliftsupthegrabber(usingtheGrabblock)sothattheUltrasonicSensor’ssightisn’tblockedbythegrabber.Aftersearchingandbeforegrabbinganobject,itlowersthegrabber(Release).TheMoveBlocksherepreventthegrabberfromcrushingtheobjectwhenitisbeinglowered.

Page 375: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure13-15:Thenextstepistograbtheobjects.Tomakesurethattheobjectremainspositionedbetweentherobot’sfingers,theSnatchermovesforwardasitgrabs.Nextitidentifiestheobject’scoloranddropsitelsewhere.

troubleshootingthesnatcherIftheSnatcher’sprogramisn’tfunctioningproperly,carefullyreconfiguretheblocksordownload(andexamine)afunctioningprogramfromthecompanionwebsite.

IfthegrabberarmontheSnatcherdoesn’tseemtoworkproperly,youmayhaveconnectedsomeLEGOpartstootightly.TryremovingthesmallgraypartasshowninFigure13-16tofreeupsomespacearoundthedarkgraybeamthatconnectstotheaxle.

Figure13-16:RemovethepartshownhereandthenfreeupspacearoundthehighlighteddarkgraybeamiftheSnatcher’sgrabberjamswhiletryingtograbsomething.

Page 376: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

furtherexplorationYou’vejustcompletedoneofthemostcomplexrobotsinthisbook.Congratulations!Nowthatyou’vebuiltandprogrammedit,you’reprobablylookingformorethingstodowiththeSnatcher.Thefollowingdiscoverieswillhelpyoufurtherimproveyourprogrammingandbuildingskills.

NOTE TheSnatcher’sgrabberwasspecificallydesignedtograbtheobjectsyou’veusedinthischapter,butyoucaneasilymodifyittograbanythingyoulike,aslongasitisnottooheavy.Tobegin,removetheorangeteeth-shapedpartsfromtheSnatcher’sgrabber,andextendthefingersbyaddingextraLEGObeams.

DISCOVERY#67:IDON’TLIKEBLUE!Difficulty:MediumModifytheSnatcherprogramtomakeitpickyabouttheobjectsitgrabs.Ifitpicksablueobject,itshoulddropitfarawayandthenreturntolookforanewobject.Ifitpicksanyothercolor,theprogramshouldsay“Yes”andendinstantly.

DISCOVERY#68:LIGHTINACORNER!Difficulty:HardInthischapteryoulearnedtoprogramtheSnatchertolookfortheclosestobject.Now,usingtheColorSensorinLightmode,createaprogramtolookforthebrightestlightsourceinyourroom.Trymakingaprogramthatfindslampspositionedontheground.Whenitfindsone,maketherobotstopandplayasound.

BUILDINGDISCOVERY#13:TABLETOPCLEANER!RemovetheentiregrabberarmfromtheSnatchersothatonlythedrivingbaseremains,andthenpositiontherobotonatableandcreateantennasforyourrobottodetectwhenthetableedgeisbeingapproached.Astherobotapproachesthetableedge,itshouldturnaroundandcontinueitspathuntilitreachesanothertableedge.Howdoyoucreatetheantennastodetectatable

Page 377: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

edge?Howdoyoubuildarobotsothatitwillneverfalloffthetable?Formorefun,buildasweepermodulewiththethirdNXTmotortowipeanyLEGOpartoffthetable!

Page 378: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

14

hybridbricksorter:sortbricksbycolorandsize

TheLEGOMINDSTORMSNXT2.0roboticskitcomeswithinstructionstobuildarobotthatsortsthecoloredballsintheset.Thischaptergoesabitfurtherbyshowingyouhowtobuildandprogramasorterthatsortsbybothcolorandsize.TheHybridBrickSorterrobotseparatesregularLEGObricks(2-by-4studs)fromsmallerbricks(2-by-2studs)andalsoseparatesred,yellow,green,andbluebricks,asshowninFigure14-1.Itdropseachtypeofbrickintodifferentbucketsorsimplyontodifferentplacesonthegroundasshowninthefigure.

Page 379: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-1:TheHybridBrickSortersortsLEGObricksbycolorandsize.

understandingthesortingtechnique

TheBrickSorterconsistsoftwomodules,asshowninFigure14-1:theScanningmodule,whichidentifiesthesizeandcolorofeachbrick,andtheDrivingmodule,whichmovestherobottowardtheappropriatebuckettodropthebrick.

thedrivingmoduleTheDrivingmodulenavigatestherobottodifferentbucketsbeforeitdropsthebricksbyturningtheDrivingmotorasshowninFigure14-2.Themotor’sRotationSensortellstheNXTwheretherobotispositioned.

Figure14-2:TheDrivingmotorallowstherobottomovebackandforthinastraightlinebetweendifferentbuckets.Thearrowsshowwhathappenswhenthemotorturnsforward.

Page 380: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

thescanningmoduleTheScanningmoduleidentifiesthecolorandsizeofaLEGObrickanddropsthebrickoncetherobothasmovedtothecorrectbucket.Beforethebricksaresorted,they’restackedinthechute,andthesorterwheelpreventsthebricksfromslidingdown,asshowninFigure14-3.Asthissorterwheelrotates,onebrickslidesdownthechuteuntilitisstoppedbythebricklock.Atthispoint,theColorSensoridentifiesthebrick’scolor,afterwhichthebricklockisraised,andthebrickfallsoutofthesorterintotheappropriatebucket.

Figure14-3:TheScanningmodule.Somepartshavebeenremovedhereforclarity.

identifyingabrick’ssizeYou’vejustlearnedhowthesorterreadsthecolorofabrick,buthowdoyoufinditssize?TheanswerliesinhowmuchthesorterwheelshouldturninordertoletonebrickslidedowntotheColorSensor,whereitisscanned.TestswiththesortershowthatturningtheWheelmotor(andthusthesorterwheel)by46degreesisjustenoughtoletonesmallbrick(2-by-2studs)slidedowntoward

Page 381: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

thebricklock.Abigbrick(2-by-4studs)requiresa92-degreeturninordertoreachthesensor.

Youidentifythesizeofabrickbyfirstturningthesorterwheelby46degrees.IfyoudothisandtheColorSensorthenseesabrick,youknowthatyouhaveasmallbrick;ifitdoesn’t,youhaveabigbrick.(Thesensorknowsthatitseesabrickwhenitdoesn’tseethewhitechuteinthebackground.)Ifyouhaveabigbrick,thesorterwheelshouldturnanother46degreestoallowthebricktoslidedowntothesensor,asshowninFigure14-4.Oncethesorterknowswhichbrickitisdealingwith,itmovestothecorrectbucket,andthebricklockisraisedtoreleasethebrick.

Figure14-4:Findingthesizeandcolorofabrick

buildingthehybridbricksorterBeforeyoubuildthesortingmachine,selecttherequiredpieces,aslistedinFigure14-5.Onceyouhaveallyourpieces,followthebuildinginstructionstobuildit.

Page 382: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-5:TherequiredpiecesfortheHybridBrickSorter

Page 383: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 384: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 385: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 386: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 387: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 388: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 389: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 390: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 391: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 392: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 393: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 394: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 395: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 396: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 397: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 398: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 399: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 400: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 401: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingthecablesHavingbuiltthesortingmachine,it’stimetoconnectthecables,asshowninTable14-1.MakesurenottoconnecttheColorSensorcabletootightly,oritwillmaketheColorSensorinterferewiththesorterwheel.

table14-1:cableplacementforthehybridbricksorter

From ToNXTbrick Cablelength

Page 402: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

motor/sensor port

Wheelmotor OutputportA Medium(35cm/15inches)

Drivingmotor OutputportB Medium

Lockmotor OutputportC Medium

ColorSensor Inputport3 Medium

findingbrickstousewithyoursorterYourBrickSorterrequiresahandfulofregularLEGObricksinvariouscolorsandtwosizes.Theprogramyou’llcreateisdesignedtosortgreen,blue,red,andyellowbricks,andtoseparate2-by-4studsfrom2-by-2studs,butifyoumodifyitslightly,youcanmakeitsortblackandwhitebricksaswell.(Ifyoudon’thavethesebasicbricksinanotherLEGOset,visitthecompanionwebsiteforhintsonfindingthem.)

findingbucketsSinceyoursorterwillsortbricksinfourcolorsandtwosizes,you’llneedeightbucketstostorethebricks.MakeyourownbucketsoutofpaperorotherLEGObricksorusereadymadebucketssuchassmallcups,asshowninFigure14-6.

Figure14-6:Anexampleofbucketsthemachinecanstoreitsbricksin

Page 403: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

programmingthehybridbricksorter

You’llnowprogramyourmachinetosortLEGObricks.Figure14-7showsanoverviewofthecompleteHybridBrickSorterprogram.

Page 404: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-7:AnoverviewoftheprogramfortheHybridBrickSorter

NoticethatthisoverviewisanexpandedversionoftheoneinFigure14-4.InadditiontoidentifyingthesizeofaLEGObrick,thisprogramalsocheckstoseewhetherthereareanybrickslefttosort.Ifthesorterwheelhasturned46degreestwiceandifthesensorstilldoesn’tseeabrick,therearenobrickslefttosort,orthere’sbeenanerror(thatis,abrickgotstuck).Inthiscase,thesorter

Page 405: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

willreport“Noobjectdetected!”andresetbyturningthesorterwheelintheoppositedirectionsothatbricksthatgotstuckcanbesortedagain.Ifthereisnoerrorandifthemachinecanidentifythesizeandcolorofabrick,itproceedstotheappropriatebuckettodropthebrick,afterwhichitreturnstoitsstartingpositiontosortoutthenextbrick.

creatingthemyblocksYou’llcreatetwoMyBlocksforthisprogram—ResetSorterandDropBrick—bothofwhichwillcontainaselectionofprogrammingblocksthatyou’llusetwiceinthefinalprogram.You’llalsousetheSayColorblockthatyoucreatedinDiscovery#30onpage80.

myblock#1:resetsorterTheResetSorterblockwillpreparethesortingmachinebyfirstturningthesorterwheelinthedirectionoppositefromthewaythatitnormallyturnswhilesorting,movinganypotentialerror-causingbrickbackupthechute.Itwillalsolowerthebricklockifit’sraisedandputthefirstbrickfromthechutedirectlyunderthesorterwheeltoprepareittobesorted.ConfiguretheblocksthatperformtheseactionsasshowninFigure14-8,andturnthemintoaMyBlockcalledResetSorter.

Figure14-8:TheconfigurationsoftheblocksintheResetSorterMyBlock

Page 406: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

myblock#2:dropbrickThissimpleblockraisesthebricklock,pausestheprogramtoallowthebricktoslidedowntothebucket,andthenlowersthebricklockagain.ConfiguretheblocksasshowninFigure14-9,andthenconvertthemintoaMyBlockcalledDropBrick.

Figure14-9:TheconfigurationsoftheblocksintheDropBrickMyBlock

creatingthefinalprogramBeforeyoucreateyourfinalprogram(seetheoverviewinFigure14-7),you’lldefinealogicvariablecalledBricksizeandanumericalvariablecalledBucket.

step1:gettingthebrick’ssizeYoubegintheprogramwiththeResetSorterMyBlock;youplaceallotherblocksinaLoopBlockconfiguredtoloopforeversothattherobotwillkeepsortingbricksuntilyouaborttheprogram.You’llfirstplacetheblocksthatidentifythebrick’ssize.Ifasmallbrickisdetected,therobotsays“Positive,”andtheBricksizevariableissettotrue.Ifabigbrickisdetected,therobotsays“Negative,”andthevariable’svalueissettofalse.ConfigurethispartoftheprogramasshowninFigure14-10.

step2:checkingwherethereisabricktosort

Page 407: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Continuebyconfiguringtheblocksthatchecktoseewhetherabrickisavailabletobesorted.(Therobotwillknowwhenitseesacolorotherthanthewhiteofthechute.)Ifnobrickisavailable,therobotsays“Noobjectdetected!”andtheResetSorterblockruns.

AsshowninFigure14-10,theprogramfirstrotatesthesorterwheelby46degrees.Iftherobotspotsabrickatthispoint,itknowsthatit’sasmallone.Ifitdoesn’tspotabrick,there’seitherabigbrickinthechuteornoneatall.Tofindout,thewheelrotatesanother46degrees,andtheblocksthatyouaddinthisstepchecktoseewhetherthereisabricktosort.

Itmightsoundstrangetofirstconfigureblockstocheckthesizeofabrick(step1)andtothencheckwhetherthere’sabricktosortatall(step2),ratherthanreverse.However,thereverseisimpossible:Ifyouweretochecktheavailabilityofabrickfirst,thatbrickwouldalreadyhavemovedallthewaydowntothebricklock,makingitimpossibletocheckitssize.

ConfigurethispartoftheprogramasshowninFigure14-11.

Figure14-10:Theconfigurationoftheblocksthatidentifythebrick’ssize.TheWaitblockshownheregivesasmallbricksometimetoslidedowntotheColorSensorbeforethesensordetectsit.

Page 408: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-11:Theconfigurationofboththeblocksthatcheckwhetherabrickisavailabletobesortedandtheblocksthatrunwhenthereisn’tabricklefttosort

step3:calculatingthepositionofabucketNowyou’llconfiguretheblocksthatrunwhentheColorSensorseesabrick.Figure14-1(page237)showshowthebricksendupifyourunthisprogram.Noticethatthesorterdropssmallbrickstotherightandbigbrickstotheleftofthestartingposition(inbetweenthebigandsmallbluebricks).

Forexample,whensortinglargegreenbricks,thedrivingmotormovesforwardacertainnumberofdegreestoreachtheappropriatebucket.Itmovesthesamenumberofdegreeswhensortingsmallgreenbricks,butintheoppositedirection.TheprogrammingblocksinthisstepcalculatethisnumberofdegreesbasedonthedetectedcolorandstoresthatnumberintheBucketvariable.ConfiguretheblocksinthisstepasshowninFigure14-12.

Page 409: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-12:Theconfigurationoftheblocksthatfindtherightbucketpositionbasedonthedetectedcolor

step4:droppingabrickintherightbucketOnceyouknowhowmanydegreesyouneedtomoveinordertoreachtherightbucket,youusethisnumbertogetherwiththevalueintheBricksizevariable.YoutransferthevalueinBricksizetoaSwitchblockspecifiedtoruntheblocksintheupperpartoftheswitchwhentheBricksizevariableistrue(asmallbrick)andspecifiedtoruntheblocksinthelowerpartoftheswitchwhenthevalueisfalse(abigbrick).

Theblocksintheswitchmaketherobotdrivetowardthebucket(basedonthevalueintheBucketvariable),dropthebrick,andthenreturntothestartingposition.YouuseaWaitblockinthelooptopausetheprogrambrieflyeachtimeitsortsabrick.ConfiguretheblocksinthisstepasshowninFigure14-13.

Page 410: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure14-13:Theconfigurationoftheblocksthatmaketherobotmovetotherightbucket,dropthebrick,andreturntothestartingposition

Nowit’stimetotesteverythingtomakesurethatitworks.InsertLEGObricksintothebrickchutewiththestudsfacingupward,downloadthisprogramtoyourrobot,runit,andgetreadytosortyourbricks!

furtherexplorationYou’vejustcompletedanotheradvancedNXT2.0robot.Welldone!Ofcourse,youshouldenjoythismachinebyrunningthesortingprogramacoupleoftimes,butit’sevenmorefuntomakethisrobotastartingpointforyourowncreations.Thefollowingdiscoverieswillhelpyougetstarteddoingso.Letothersknowaboutyourcreationsbysharingideasonthecompanionwebsite!

DISCOVERY#69:HIGH-SPEEDSORTING!Difficulty:EasyTheHybridBrickSortermayworkveryreliably,butyoucanprobablysortbricksfasteronyourown.Modifytheprogramtomakeitchallengingforanyonetostayaheadofthebricksorterwhensortingbricks.

Page 411: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DISCOVERY#70:QUATROBRICKSORTER!Difficulty:MediumThecurrentbricksortersortsbricksinonlytwosizesandfourcolors.Canyoumodifytheprogramtoalsosort2-by-3studdedbricks,2-by-6bricks,andevenblackandwhitebricks?Youmightneedtoenlargethebrickchute!

HINTIfyouwantyourrobottoalsosortblackbricks,lookattheMathblocksplacedinstep3ofthefinalprogram.Howdoesthecalculationwork,andhowshouldyoumodifythesettingsintheseMathblockstomakeblackbrickspartofthesortedbricks?

DISCOVERY#71:INTELLIGENTSORTING!Difficulty:HardTheprogramyou’vemadeinthischapterhadtherobotmovebacktoitsstartingpositioneverytimeitsortedabrick.Youcanavoidthisbymakingitgotothenextbucketstraightaway.Howwouldyouprogramthisbehavior?

BUILDINGDISCOVERY#14:HYBRIDBRICKSHOOTER!

Thesortercurrentlydropsbricksindifferentbuckets,buthowaboutaddingalittlemoreaction?DestroytheDrivingmodule,andcreateabrick-launchingmodulesothattherobotcanlaunchbricksslowlyorquicklydependingontheirsizeandcolor.Startbyshootingjusttwotypesofbricks,suchasonlysmallgreenandredbricks.Separatethembymakinggreenbrickslandclosetotherobotandmakingredbrickslandfartheraway.Onceyouhaveadesignthatworksreliably,expandyourshootingprogramtoseparatemoretypesofbricks.

Page 412: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

15

CCC:thecompactchimneyclimber

ManyNXTrobotsmoveonwheels,somemoveonlegs,andstillothersdosomethingwhileremaininginplace.ButtheCompactChimneyClimber(CCC)thatyou’llbuildinthischapterisdifferent:Itmovesvertically.Thisrobotclimbsbetweentwowalls,asifupachimney,asshowninFigure15-1.Whenitreachesthetopofthe“chimney,”itsafelyreturnstotheground.

NOTE Thisisthelastrobotyou’llbuild—notbecauseit’sthemostdifficultbutbecausetheCCCisthetrickiestonetogettowork.Beware!Ifdoneincorrectly,thisrobotcandamageyourLEGO.

Page 413: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure15-1:TheCompactChimneyClimbermovesverticallybetweentwosolidobjects,suchasabookcaseandawall.

understandingtheclimbingtechnique

TheCCCconsistsoftwoarmsthatextendtotouchthewallsitwillclimbsothattherobotcanmoveupanddownbyturningthewheelsonitsarms(seeFigure15-1).Thisclimbingtechniqueisn’tverycomplicatedanditworksfairlywell,butasimplerobotwiththistechniquewilleventuallylosecontactwiththewallandfalldown.Topreventtherobotfromcrashingtotheground,you’llneedtokeepitbalancedasitmoves,onboththex-andy-axes,asshowninFigure15-2.

Page 414: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

stayingbalancedonthex-axisTheCCCrobotbalancesonthex-axisautomaticallybydesign.Themainweightoftherobot,theNXTwithitsbatteries,ispositionedbelowtheaxis,causingtherobottobehaveliketheswingshowninFigure15-3.Ifyouweretotrytoturntheaxisinthisfigurewithyourhands,you’dnoticethatgravitytriestostopyou.Somethingsimilarhappenswhentheclimbertriestorotatealongthex-axis:Gravitykeepsitupright.

Figure15-2:Tobeabletoclimb,theCCChastobalanceontwoaxes.(Onlyonewallisshownhereforbettervisibility.)Ifbalanceisn’tmaintained,therobotwilleventuallytiltinoneofthedirectionsindicatedbythegrayarrowsandlosecontactwiththewalls.

Page 415: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure15-3:Asimplifiedversionoftheclimbershowshowbalanceismaintainedonthex-axis.BuildthisorasimilarconstructionwiththepiecesinyourNXTset.Ifyoutrytoturntheaxis(grayarrow),gravitywilltrytokeeptheweightbelowtheaxis(blackarrow).

balancingonthey-axisTheCCCrobotclimbsbyturningthewheelsonbothofitsarms(theWheelmotors)atthesamespeed,asiftherobotweredrivingupthewalls.Whileclimbing,thewheelsononesideoftherobotmayslip,oronemaygripthewallmorethantheother.Whenthishappens,onesideoftherobotclimbsfasterthantheother,whichcausestherobottotiltalongthey-axis,asshownontheleftofFigure15-4.

detectingbalanceerrorsItiseasyforushumanstoseewhentherobotstartstobecomeunstableonthey-axis,buttherobotcanalsocatchthiserrorbyusingtheColorSensorasa

Page 416: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

balancedetector,asshowninFigure15-4.Thesensoristightlyconnectedtotherobot,butaswinginfrontofitwithdifferentcoloredpartsmovesfreely;becauseofgravity,italwayspointsdownward.Becausethesensortiltsalongwiththerobotandtheswingdoesnot,thesensorseesdifferentcolorsdependingonhowtherobotistitled.

solvingbalanceerrorsTheroboteasilycorrectsbalanceerrorsbytemporarilystoppingtheWheelmotorofthearmpositionedhigherthantheotherone,whichallowsthelowerarmtokeepup.Forinstance,iftherobotseesblack,thewheelsontherightsideshouldstop,asshownontheleftofFigure15-4.Oncethewheelsonbotharmsareatthesamealtitude(thesensorseeswhite),theyshouldmoveatthesamespeed,allowingtherobottocontinueupthechimney(shownontherightofFigure15-4).Thissamecontroltechniqueisusedwhentherobotgoesdown,exceptthattheoppositewheelisstoppedwhenabalanceerrorisdetected.

Figure15-4:Detectingandcorrectingbalanceerrorsonthey-axis

buildingthecompactchimneyclimber

Nowbuildthisrobotbyfollowingtheinstructionsonthenextpages.Firstselecttherequiredpiecesfortherobot,asshowninFigure15-5.

Page 417: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure15-5:RequiredpiecesfortheCompactChimneyClimber

Page 418: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 419: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 420: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 421: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 422: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 423: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 424: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 425: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 426: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 427: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 428: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

preparingachimneyBeforeprogrammingthisrobot,you’llneedtofindanappropriate“chimney”fortherobottoclimb,suchasthecrevassemadebetweenawallandthesideofabookcase,asshowninFigure15-6.Whateveryourchoice,yourchimney’s

Page 429: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

wallsshouldbeasfollows:*Solidandunabletomovewhiletherobotclimbs.Perhapstrytheedgeofadeskorstrong,heavymovingboxes.

*Perfectlyparalleltoeachother.*About32cm(12.5inches)apart.Aslightlysmaller(30cm)orwider(35cm)gapisfinetoo.Adjustthewidthofthegapbymovingoneofthetwowallsifpossible.

Figure15-6:AnexampleofachimneysuitableforyourCCC

Evenifyourchimneymeetstheserequirements,beverycarefulwhenusingtheCCCrobotbecauseitmaystillfall.Whenfirsttestingyourrobot,makesuretoguideitwithyourhandssothatyoucaninstantlygrabitifitstartstobecomeunstable.Forextrasecurity,putapillowatthebottomofthechimneyjustaftertherobotliftsoffthefloor.

Theprogramyou’llcreateforthisrobotwillmakeCCCmoveupuntilitspotstheceiling.Ifoneorbothwallsdonotreachtheceiling,yourrobotwon’tbeabletoseeit.Inthatcase,keepyourhandinfrontofthesensortotelltherobottogodownagain.AndifyoudamageanyLEGOpieces,well,you’vebeenwarned!

Page 430: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

programmingthecompactchimneyclimber

Nowthatyou’vebuilttheCCCandfoundanappropriatechimneyforittoclimb,you’rereadytoprogramit.YourCCCprogramwillallowtherobottoclimbthechimneytowardtheceilingandreturntoitsstartingposition.“FurtherExploration”onpage283willgiveyousomeideastoexpandtheprogram.

step1:extendingthearmsFirst,theprogramswitchesontheWheelmotorsBandC.Next,thearmsareextendedtotouchthewallsofthechimneybyrotatingthemotoronportAinsidetheclimberbackward.Astherobotclimbs,theNXTkeepsapplyingpowertothismotorsothattherobot’swheelsarepressedagainstthewalls,givingthemmoregrip.ConfiguretheblocksthatperformtheseactionsasshowninFigure15-7.

NOTE Unlessspecifiedotherwiseinthefigures,alltheMotorblocksintheCCCprogramhavethefollowingconfigurations:MotorPower:Checked;Duration:Unlimited.Also,theblocksinsteps1and2aresettomakethemotorturnbackward,andthoseinstep3makeamotorrunforward.

step2:climbingandstayingbalancedRecallthattheCCCrobotusestheColorSensortodetectbalanceerrorsonthey-axis(seeFigure15-4).Whileclimbing,therobotrepeatedlypollsthissensorandcontrolstheWheelmotorsaccordinglytomaintainbalanceuntiltheUltrasonicSensordetectsthetopofyourchimney,asshowninFigure15-8.

NOTE WhentheColorSensorseessomethingred,it’sactuallydetectingtheorangepartsoftheswingthatbalancesinfrontofthesensor.

FollowFigure15-9toturnthisprogrammingstructureintorealprogrammingblocks.

Page 431: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure15-7:TheconfigurationoftheblocksthatswitchontheWheelmotorsandextendthearms

Figure15-8:Anoverviewofthecontroltechniqueusedtokeeptherobotbalanced.Ifthesensorreadswhite,therobotiscorrectlybalanced,sononeoftheWheelmotorsshouldbestopped.

Page 432: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Figure15-9:Theconfigurationoftheblocksthatkeeptherobotbalancedasitclimbs

step3:goingdown,stayingbalanced,andstopping

Onceatthetop,therobotstopsmoving,playsasound,andstartsgoingdown.Theblocksthatcontroltherobottogodownaresimilartotheonesyouusedtoclimbthechimney,exceptthattheMotorblocksnowmaketherobotmoveintheoppositedirection.Therefore,youcansimplycopythepreviousLoopblockanditscontents,placeitasshowninFigure15-10,andadjustthesettingsofeachblockasindicated.

Whenyouruntheprogram,you’llnoticethatwhengoingdown,themotorsspinmoreslowlyandtheoppositemotorisstoppedwhenabalanceerrorisdetected(inotherwords,blacknowstopsmotorC).TheLoopblockrepeatstheblocksinituntiltheRotationSensorinmotorCreportsvalue0,indicatingthattherobothasreacheditsstartingposition,atwhichpointtheprogramends,andthemotorsstopmoving.BecausethemotoronportAisnolongerkeepingthearmsoutstretched,theyarereleasedfromthewall.

troubleshootingtheCCCRunningtheprogramforthisrobotrequiresabitmoreattentionthantheotherprogramsyou’vemadesofar.Beforeyourunit,makesurethattherobotispositionedinthemiddleofthechimneyasshowninFigure15-6.Whenstartingtheprogramforthefirsttime,carefullyfollowtherobotonitswayupwithyourhandstomakesureitwon’tfall!Ifyou’rehavingproblemsmakingtherobot

Page 433: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

work,seethefollowingtroubleshootingtips,orvisitthecompanionwebsiteformorehelp:*Theremaybesomethingwrongwithyourchimney.Besuretochecktheguidelinesin“PreparingaChimney”onpage280.

*Iftherobotbecomesunstablebecauseitmovestoofastortooslow,youmightneedtoadjustthepowerlevelsintheMotorblocksthatcontroltheWheelmotors.Also,tryrunningtheprogramwithneworfullychargedbatteries.

*Beforestartingtheprogram,bothoftherobot’sarmsshouldpointstraighttotheground(Figure15-6).Ifonlyonearmpointsstraightdownwhile,forexample,theothersticksouttotheright,carefullyreviewbuildingsteps8and9onpage273tofixtheproblem.Youmightalsobeabletofixthissimplybyapplyingsomeforceonthearminquestion(you’llhearaclickingsound),butdon’tdothistoooften.

Figure15-10:theconfigurationoftheblocksthatarerunwhentherobotspotstheceiling.therobotpausesforasecond,playsasound,andreturnstotheground.

furtherexplorationYou’vereachedtheendofthisbook.Congratulations!IhopeyouenjoyedlearningtheinsandoutsoftheLEGOMINDSTORMSNXT2.0roboticskit,aswellasbuildingandprogrammingtherobotsinthisbook.Butthefundoesn’tendhere.You’renowreadytostartcreatingrobotsonyourownandshareyourideaswiththeworld.Whetheryourrobotsdrive,shoot,walk,grab,sort,orclimb,thepossibilitiesareendlesswithLEGOMINDSTORMSNXT!

Page 434: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Butbeforeyouclosethisbook,trysolvingthefollowingtwodiscoveriesthatwillletyoudomorewiththeCompactChimneyClimberandtheknowledgeyougainedinthischapter.

DISCOVERY#72:ALTIMETER!Difficulty:HardUsetheNXTscreentodisplaythealtitudeoftheclimberasitmoves.Eachrotationofthemotorwheelsshouldmaketherobotincreaseitsaltitudebyacertainnumberofcentimeters.But,howmanyexactly,andhowdoyoucalculatethealtitude(thetraveleddistance)?

HINTUseaseparateSequenceBeamtocalculateanddisplaythealtitudeeverysecond.

BUILDINGDISCOVERY#15:AERIALTRAM!TheCCCyoubuiltinthischapterwasanuncommonvehicle,andinthisdiscoveryyouarechallengedtobuildarobotthatdoesn’ttouchtheground.WirearopestrongenoughtocarrytheweightofyourNXTwithsomemotorsacrossyourroom.Canyoudesignarobotthattravelsthroughtheair,hangingbelowthisrope?

HINTStartbymakingaframetocarrytheNXT,andallowittomovefreelyalongtheropewithoutfalling.Forexample,youcouldcreateaframewithholesinthetopfortheropetomovethroughandthenconnectamotortothisframethatmakesawheelmoveovertherope.Asyouturnthismotor,thewholerobotshouldslidealongtheropethroughtheair.

Page 435: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

index

Numbers1:1referencechart,frontinsidecover

usingwithaxles,8

usingwithbeams,8

90-degreeturns

makingwhensteering,35

performingviaRotationSensor,83

180-degreeturn,makinginplace,35

Symbols<(lessthan)value,comparing,175=(equalto)value,comparing,175>(greaterthan)value,comparing,175

AActionblocks,usingwithCompletePalette,105Andoperation,outputvaluefor,176Aoutputport,connectingmotorsto,19arithmeticoperations,capabilitiesfor,171

Page 436: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

arrowbuttons,trackingpressesof,188autonomousmode

operatingShot-Rollerin,87

usingwithShot-Roller,108

axles

buildingtip,8

determininglengthof,8

pushingin,18

Bbatteries,inserting,5–6beams

buildingtipforExplorer,8

findinglengthof,8

usingwithgrabbingmechanism,198

usingwithliftingmechanism,198

beepingalarm,creating,66billofmaterialsforExplorer,8blocks.SeeprogrammingblocksBluetooth

troubleshootingconnections,289

usingtoconnecttoNXT,289

Page 437: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingtodownloadprogramstoNXT,27

Bluetoothdongle,finding,288Boutputport,connectingmotorsto,19brick.SeeNXTbrickbricks.SeealsoHybridBrickSorter

droppinginbuckets,263

findingbucketsfor,259

findingforHybridBrickSorter,259

findingsizesandcolorsof,238–239

gettingsizesof,261

brokendatawire,166buckets

calculatingpositionsof,262

droppingbricksin,263

findingforHybridBrickSorter,259

bulldozerblade,80Bumpedaction,detectionbyTouchSensor,68bumperattachment,creatingwithTouchSensors,68–72.SeealsoDiscovery-BumperprogramButtonvariable,usingwithSmart-Game,190,191

Ccables

attachingforTouchSensors,73

Page 438: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connecting,19

connectingforHybridBrickSorter,259

connectingforShot-Roller,105

connectingtoExplorer,19

shortversuslong,19

typesof,4,19

wiring,19

catalognumbers

forLEGOrechargeablebatteries,5

fortransformers,5

CCC(CompactChimneyClimber)

balancingonx-axis,266–267

balancingony-axis,267

building,269–279

climbingandstayingbalanced,280–281

climbingtechnique,266–267

controltechnique,281

detectingbalanceerrors,267

extendingarmsfor,280

functionof,265

goingdown,282

Page 439: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Motorblocksin,280

preparingchimneyfor,280

requiredpiecesfor,268

solvingbalanceerrors,267

spottingceiling,282

stayingbalanced,282

stopping,282

troubleshooting,282

warningabout,265

Wheelmotors,280–281

chimney,preparingforCCC,280circles,displaying,40climbingtechnique,266–267Closestvariable,usingwithSnatcher,232coloredballs,identifyingcolorsof,85coloredline,stayinginsideof,79ColorLampblock,usingwithShot-Roller,105,106,111color,sayingnameof,80ColorSensor,55,56

connectingtoDiscoveryrobot,78

creatingattachmentfor,76,78

creatingline-followingrobot,81

Discovery-Circleprogram,79

functioninLightSensormode,112

Page 440: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

InsideRangeoption,78

OutsideRangeoption,78

pollingviaViewmode,78

programmingwith,78–79

seeingblack,81

seeingwhite,81

usingwithBrickSorter,262

usingwithShot-Roller,111

ColorSensorblock

configuring,162

DetectedColorplugon,162

colorvalue,multiplyingviaMathblock,172comments,includinginprograms,29CommentTool,29Commonblocks,usingwithCompletePalette,105CompactChimneyClimber(CCC).SeeCCC(CompactChimneyClimber)companionwebsite,xx

Compareblock

Smart-Compareprogram,175

usingwithSmart-Gameprogram,191

Comparesetting,usingwithUltrasonicSensors,159CompletePalette,usingwithShot-Roller,105conditions,usingwithSwitchblocks,62,177configurationicons,35ConfigurationPanel,27,28

Page 441: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

accessingboxeson,45

displaying,27

forMoveblock,33–34

connections

listingNXTdevicesfor,286

toNXTviaBluetooth,289

toNXTwithUSB,286

settingupmanually,286

Constantblocks,188constants

Customblockfor,188–189

defining,188

Smart-Constantprogram,188–189

controller.SeeNXTcontrollerControlMotorPoweroption,usingwithShot-Roller,107Copybutton,28Coutputport,connectingmotorsto,19Cutbutton,28

Ddatablocks

Compareblock,175

Page 442: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Logicblock,175,176

Mathblock,171,173

Randomblock,174

datahubs,149

closing,158

creatingandconnectingdatawire,157

inputandoutputplugson,159

inputplugson,167

openingforblocks,158

openingforblocksinSmart-Introprogram,157

outputplugson,167

dataplugs

Directionplug,169

hidingwhenunused,169

usinghelpfor,168–169

dataplugs,inputandoutput,159datawires,149

blocksandconfigurationsfor,160

brokendatawire,166

configuringSwitchblockswith,178–179

connectingtoblocks,166–167

Page 443: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connectingtodataplugs,167

connectingtodifferentplugs,166

connectingtoinsideSwitchblocks,180

creatingandconnecting,157

deleting,160

errormessages,287–288

functionof,163

managing,169

Smart-LogicWireprogram,164

typesof,163–166

usingacrossprograms,169–170

usingtoendloops,180

decisions,repeatingforrobots,65degrees,findingnumberof,35deleting

blocks,26

datawires,160

files,287

variables,184

DemoV2program,running,21Directionplug,169directionsigns,finding,41Directionvariable,usingwithSnatcher,233

Page 444: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery-Avoidprogram,60Discovery-Bumperprogram,74–75.SeealsobumperattachmentDiscovery-Buttonprogram,82

Discovery-Circleprogram,79Discovery-Loopprogram,61Discovery-Repeatprogram,65Discoveryrobot.SeealsoExplorerrobot;robotswithbumperattachment,67

connectingColorSensorto,78

enhancementof,55

Discovery-Rotationprogram,83–85Discovery-Switchprogram,62–64Discovery-Touchprogram,73–74Discovery-Waitprogram,58–59Displayblocks,38

Actionsetting,39

Displaybox,39

displayingdrawings,40

displayingimages,39

displayingtext,39

inExplorer-Displayprogram,40–41

testing,40–41

Typebox,40

usingwithStriderrobot,140

distance

detectingviasensors,56

Page 445: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

measuringforUltrasonicSensor,66

dots,displaying,40DownloadandRunbutton,25–26Downloadbutton,27downloadingprogramstoNXT,285–288drawings,displaying,40drivetrack,42Drivingmodule,forHybridBrickSorter,238Drivingmotor,forHybridBrickSorter,238DropBrickMyBlock,creatingforBrickSorter,260DurationUnlimitedsetting,usingwithMoveblock,45–46

EEnterbutton

usingtochooseitems,20

usingtoturnonbrick,23

equalto(=)value,comparing,175errormessages

cannotdownloadneededfileforprogram,288

datawires,287–288

thefileiscurrentlyinuse,288

theNXTdeviceisnolongerconnected,287

theNXTdeviceisoutofmemory,287

theprogramisbroken...missingfiles,288

Page 446: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

troubleshooting,25

Exitbutton

usingtoabortprograms,21

usingtoaccesspreviousmenu,20

usingtoturnoffbrick,20

Explorer-Displayprogram,Displayblocksin,40–41Explorer-Loopprogram,47Explorer-Moveprogram,32Explorer-Parallelprogram,50,51Explorerrobot.SeealsoDiscoveryrobot;robotsaccelerating,34

adjustingspeedof,30

billofmaterialsfor,8

building,9–18

connectingcablesto,19

controllingremotely,30

makingdrivebackward,32–33

movingbackandforth,48

movinginsquare,46

selectingpiecesfor,7

testing,21

tipsforfrictionandnonfrictionpins,8

turning,34–35

Page 447: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Explorer-Soundprogram,36Explorer-Unlimitedprogram,45Explorer-Waitprogram,43–44

FFeedbackBoxes,usingtopollsensors,142files,removingfromNXT’smemory,287FindObjectMyBlock,creatingforSnatcher,232–233Firingmotor,functioninShot-Roller,88fixedpen,liftingup,42FlatViewoption,usingwithSwitchblocks,64Flowblocks,usingwithCompletePalette,105frictionpins,buildingtipfor,frontinsidecover,8

Ggame.SeeSmart-Gameprogramgears,usingwithSnatcher,198–199“Goodbye”and“Hello,”programmingforrobot,59Grabbermotor,usingwithSnatcher,197grabbingmechanism.SeealsoSnatcherroboticarmbeamsusedwith,198

usingwithSnatcher,198–199

GrabMyBlock,creatingforSnatcher,232greaterthan(>)value,comparing,175

H

Page 448: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

“Hello”and“Goodbye,”programmingforrobot,59HelpWindow,27house,robotizing,85HybridBrickSorter.Seealsobricksbuilding,240–258

calculatingpositionofbucket,262

checkingbricksforsorting,261

connectingcablesfor,259

Drivingmodule,238

Drivingmotor,238

DropBrickMyBlock,260

functionof,237

gettingbricksizefor,261

identifyingsizeofbricks,238

overviewof,259–260requiredpiecesfor,239

ResetSorterMyBlock,260

Scanningmodule,238

sortingtechnique,238

Iimages,displaying,39inputplugs

usingsettingswith,167–168

Page 449: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingwithSmartBot,159

inputports

selectingforColorSensor,78

usingwithsensors,56

inventorysheet,locating,4

LLCDscreen

controllingdisplayon,38–41

dimensionsof,38–41

LeftArrowbutton,pushing,82LeftTouchSensor,73LEGOrechargeablebatteries,catalognumbersfor,5lessthan(<)value,comparing,175liftingmechanism

beamsusedwith,198

usingwithSnatcher,198–199

LightSensor,determininglightnessanddarknesswith,143LightSensormode,usingwithShot-Roller,111,112LightSensorvalue,choosing,162linedetector,usingColorSensoras,79line-followingrobot,creating,81lines

displaying,40

Page 450: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

following,85

LittleHelpWindow,27,28Logicblock

logicoperations,176

Notoperation,176

Smart-Logicprogram,175–176

Logicdatawires,163,164

comparing,175,176

outputtingviaCompareblock,175

Logicsetting,usingwithLoopblocks,180Loopblock,46

ConfigurationPanel,46

Discovery-Loopprogram,61

Explorer-Loopprogram,47

placingprogrammingblocksin,46

settings,47

Smart-Loopprogram,180–181

usingLogicsettingwith,180

usingsensorswith,60–61

usingwithinLoopblocks,48

usingwithShot-Roller,110,115

loopcount,usingwithSmartBot,158

Page 451: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

loops,endingwithdatawires,180

MMantyrobot,walkingtechniqueof,145Mathblock

functionof,171–173

Smart-Mathprogram,171–172

Smart-Soundprogram,172–173

mechanicalfunctions,testing,107menus,returningto,20Motorblocks

inCCC(CompactChimneyClimber),280

datahubcharacteristicsof,168

usingwithShot-Roller,106,107,118

usingwithSmartBot,158

motorcompartment,turning,18MotorControlTestprogram,107motorrotations,findingnumberof,35motors

connectingforShot-Roller,105

connectingtobrick,19

connectingtooutputports,19

controllingmovementof,32–35

Page 452: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

turningdirectionsof,83,107,135

turningonforDiscovery-Bumperprogram,75

useof,4

Moveblock,32

configurationicons,35

ConfigurationPanel,33–34

Degreessetting,33

Directionbox,33

Durationsetting,33

DurationUnlimitedsetting,45–46

Explorer-Unlimitedprogram,45

nameandimagesetting,34

NextActionbox,35

portsettings,33

Powerbox,33

Rotationssetting,33

settings,33

Steeringslider,33

Unlimitedoption,44–45,81

usingwithColorSensor,81

MoveCloserMyBlock,creatingforSnatcher,234

Page 453: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

MyBlocks,48

addingiconsto,49

changingiconsfor,50

creating,49

creatingforHybridBrickSorter,260

creatingforSnatcher,231–234editing,50

naming,49

placinginSwitchblocks,138

usinginprograms,49–50

usingwithStriderrobot,137–141

Nnonfrictionpins,buildingtipabout,frontinsidecover,8note,selectingfromkeyboard,37Notoperation,176Numberdatawire,163

addingtoSmart-LogicWire,166–167

using,180

NumbertoTextblock,165numbervariable,PressCount,186NXTbrick.SeeNXTNXTbuttons

determiningpressedstatusof,82

Page 454: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Discovery-Buttonprogram,82

usingtonavigatebrick,19–21

NXTcontroller,26,27,285NXTdevices,listingforconnections,286NXT-Gprogrammingsoftware

accessing,4

installing,5

NXT-Gsoftwarewindow,25NXT-Gstartupscreen,24NXTkit,sortingoutpartsin,4NXTscreen

displayingUltrasonicSensorreadingon,165

andNXTbuttons,19

showingtextlineson,164

NXT’smemory,removingfilesfrom,287NXT,4

changingnameof,286

connectingviaBluetooth,289

connectingmotorsto,19

disconnectionerrormessage,287

downloadingprogramsto,285–288

findingprogramsdownloadedto,26

memorymessage,287

Page 455: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

navigating,19–21personalizing,286

refreshinglistof,286

transferringprogramsto,26–27

turningoff,20

turningon,20,23

usingBluetoothfordownloadsto,27

NXTwindow,usingtoconnectmanually,286

Oobjects

detecting,56

grabbingwithSnatcher,234

obstacles,avoiding,60Oroperation,outputvaluefor,176outputplugs

usingsettingswith,167–168

usingwithSmartBot,159,167

outputports,connectingmotorsto,19

Ppalettes,opening,25

Page 456: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PanTool,29ParallelSequenceBeam

Explorer-Parallelprogram,50,51

usinginprograms,50,51

Pastebutton,28pen,liftingup,42pins,buildingtipfor,8PointerTool,29points,displaying,40pollinginformation,56ports.SeeinputportsPositionvariable,usingwithSmart-Game,190PressCountnumbervariable,186Pressedaction,detectionbyTouchSensor,68programmingblocks

addingtoSwitchblocks,64

configuring,45

copying,29

Displayblock,38–41inExplorer-Unlimitedprogram,45

manipulating,28

Moveblock,32–35movinganddeleting,26

openingdatahubsfor,158

pickingandplacing,24

placinginWorkArea,26

repeatingsequencesof,46–48selecting,25

Page 457: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

onSequenceBeam,31

Soundblock,36–38typesof,31

usingtocreateprograms,31

ProgrammingPalettes,25ProgramNavigationBar,27,28programs

aborting,21,285

closing,28

commentsin,29

configuringblocksin,45

creating,23,25

creatingwithprogrammingblocks,31

downloadingtoNXT,25,285–288

downloadingwithoutrunning,27

findingdownloadstobrick,26

managing,28

modifying,28–29

navigatingbetween,28

navigatingtopartsof,29

pausingviaWaitblock,58–60

running,21

runningmanually,26

Page 458: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

transferringtoNXTbrick,26–27

RRandomblock

Smart-Randomprogram,174

usingwithSmart-Gameprogram,191

rechargeablebatteries,catalognumbersfor,5Redobutton,29Releasedaction,detectionbyTouchSensor,68ReleaseMyBlock,creatingforSnatcher,232RemoteControl,30remote-controlmode,operatingShot-Rollerin,87,113–114Repeatcheckbox,usingwithSoundblock,36Reset,selectinginSwitchblock,85ResetSorterMyBlock,creatingforBrickSorter,260RightArrowbutton,pushing,82RightTouchSensor,73,76RoboCenter,27,29,30robots.SeealsoDiscoveryrobot;Explorerrobotrepeatingdecisionsof,65

testingmechanicalfunctionsfor,107

!RotationSensor,84RotationSensorblock,configuring,163RotationSensors

behaviorof,83

Discovery-Rotation,83–85

makingprogramswith,83–85

Page 459: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

pollingviaViewmode,83

resetting,84–85

SSayColorMyBlock,creating,80Scanningmodule,usingwithHybridBrickSorter,238score

adjustinginSmart-Gameprogram,192

displayinginSmart-Gameprogram,193

Scorevariable,usingwithSmart-Game,190“seeing”behavior,sensorfor,56selectingitems,20Sensorblocks

configuring,162

usingtoperformsensormeasurements,166

usingtopollsensors,162

usingwithCompletePalette,105

sensorcables,connectingforStriderrobot,134sensordata,basingdecisionson,62sensorreadings,viewing,56sensors

Color,55,56

connectingforShot-Roller,105

Page 460: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Light,111

polling,56,57

pollingviaFeedbackBoxes,142

Rotation,83

Touch,55

triggering,58

typesof,55

Ultrasonic,55

usingwithLoopblock,60–61

usingwithSwitchblocks,62–65

andWaitblock,58–60

sensors,useof,4SequenceBeam,programmingblockson,31Shot-Roller

autonomousmode,108

building,88–104

ColorLampblock,105,106

CompletePalette,105

connectingcablesfor,105

ControlMotorPoweroption,107

creatingacatapultfor,119

defendingterritorywith,112

Page 461: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Firingmotor,88

LightSensormode,111

Motorblocks,106,107,118

MotorControlTestprogram,107

remote-controlmode,113–114

requiredpiecesfor,88

Shot-Roller-Lightprogram,112–113

Shot-Roller-Remoteprogram,114–118

TestColorLampprogram,106

turningintointruderalarm,111

Turnmotor,87,114–115

Turretmotor,87,116

Shot-Roller-Lightprogram,112–113Shot-Roller-Remoteprogram,114–118Smart-Accelerateprogram,158–159SmartBot

acceleratingmotorfor,158

building,150–155

requiredpiecesfor,150

Smart-Introprogram,156

usingloopcountwith,158

Smart-Compareprogram,175

Page 462: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Smart-Constantprogram,188–189Smart-Countprogram,186–187Smart-Gameprogram

adjustingscorein,192

comparingpositionandbuttonvariables,192

definingvariablesfor,190

displayingcurrentscore,193

displayingtargetrandomly,191

expanding,193–194

overviewof,190

repeatingfor30

seconds,193

storingpressedbutton,191

waitinguntilbuttonispressed,191

Smart-Introprogramblocksfor,156

opendatahubsforblocks,157

overviewof,157

Soundblocksin,157

UltrasonicSensorblockin,157

Smart-Logicprogram,175–176Smart-LogicWireprogram,164,166–167Smart-Loopprogram,180–181Smart-Mathprogram,171–173

Page 463: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Smart-Randomprogram,174Smart-Soundprogram,172–173Smart-Switchprogram,178–179Smart-TextWireprogram,165Smart-Touchprogram,177Smart-Variableprogram,185Snatcherroboticarm.Seealsograbbingmechanismbuilding,201–230

FindObjectMyBlock,232–233

functionof,231

gearsfor,198–199

Grabbermotor,197

grabbingmechanism,198

grabbingobjectswith,234

GrabMyBlock,232

liftingmechanism,198–199

MoveCloserMyBlock,234

overviewof,231

ReleaseMyBlock,232

requiredpiecesfor,200

SayColorMyBlock,234

troubleshooting,235

Soundblock

Actionsetting,36

Page 464: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

withConfigurationPanel,36

ConfigurationPanelsforblocks,37

configurations,36

Controlbox,36

creatingprogramfor,37–38

Filebox,36

Functionbox,36

functionof,172

selectingnotesfromkeyboard,37

inSmart-Introprogram,157

inSwitchblocks,84

usingwithStriderrobot,140

Volumesetting,36

Waitbox,37

SoundEditor,using,36soundfiles,creating,36sounds

aborting,36

repeating,36

typesof,36

square-shapedpatterns,drivingin,46StartArea,26

Page 465: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

straightline,following,61Striderrobot

building,122–133

connectingsensorcablesfor,134

creatingWalk-ForwardMyBlock,135

legpairs,134

minifiguresforwalkingtechnique,134

motorassemblies,122,135

motordirectionformotorblocks,137

NXTmotors,135

powersettingsformotorblocks,137

Strider-Touchprogram,137–138

onthreewheels,146

usingDisplayBlockswith,140

usingMyBlocksininteractiveprogram,137–141

usingSoundBlockwith,140

walkingtechnique,134–135

Walk-LeftMyBlock,136

Walk-RightMyBlock,136

Strider-Scaredprogram

creating,144

Page 466: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

pollingsensorswithFeedbackBoxes,142

settingthresholdvaluesfor,142–143

Switchblocks

addingblocksto,64

behaviorof,65

configuring,62–63

configuringwithdatawires,178–179

decreasingsizeof,64

Discovery-Repeatprogram,65

Discovery-Switchprogram,62–64

displayingonWorkArea,64

FlatViewoption,64

placingMyBlocksin,138

selectingResetin,85

sensorspolledby,74

Smart-Switchprogram,178–179

Smart-Touchprogram,177

Soundblocksin,84

usingconditionswith,62–65

usingNumberdatawireswith,180

usingsensorswith,62–65

Page 467: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingTextdatawireswith,180

usingtofollowlines,81

usingwithShot-Roller,109,116–117

usingwithSmart-Gameprogram,191–192

switches,repeating,65

TTestColorLampprogram,106TestPad,5Textdatawire,164

NumbertoTextblock,165

Smart-TextWireprogram,165

using,180

text,displaying,39textlines,displayingonNXTscreen,164–165thresholdvalues,settingforStrider-Scaredprogram,142–143ToneFrequencyplug,172tones,playing,36,84Toolbar

buttonsformanagingprograms,28

buttonsformodifyingprograms,28–29

buttonson,28

CommentTool,29

Page 468: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

PanTool,29

PointerTool,29

TouchSensorblock,configuring,162TouchSensors,55

actionsdetectedby,68

bumperattachmentwith,68–72

connectingcablesfor,73

detectingpressedstatusof,177

Discovery-Touchprogram,73

LeftTouchSensor,73

pollingviaWaitblock,73

programmingwith,73

RightTouchSensor,73

Smart-Countprogram,186–187

usingtoavoidwalls,74–75

usingwithStriderrobot,139–140

transformer,catalognumberfor,5triangle-shapedpatterns,drivingin,48triggervalue

configuringforRotationSensor,83

usingwithsensors,58

tunes,playing,61Turnmotor

Page 469: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Turnmotor

functioninShot-Roller,87

usingwithShot-Roller,114–115

turns

curving,36

makingaccurately,35

Turretmotor

functioninShot-Roller,87

usingwithShot-Roller,116

UUltrasonicSensor,55,56

Comparesetting,159

usinginSmart-Introprogram,157

usingtoavoidwalls,60

usingWaitblockwith,58–59

UltrasonicSensorreading,displayingonNXTscreen,165Undobutton,29Unlimitedoption,usingwithMoveblock,45

problemswith,45

Page 470: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

VVariableblock,configuring,184variables

BricksizeforHybridBrickSorter,261

BucketforHybridBrickSorter,262

ButtonforSmartBot,190

changingvaluesfor,186

ClosestforSnatcher,232

defining,183,184

definingforSmart-Gameprogram,190

deleting,184

DirectionforSnatcher,233

initializing,186–187

PositionforSmartBot,190

ScoreforSmartBot,190

Smart-Countprogram,186–187

Smart-Variableprogram,185

storingvaluesin,184

Viewmenu,viewingsensorreadingson,56,57Viewmode

usingtopollColorSensor,78

Page 471: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

usingtopollRotationSensor,83

voice,recordingwithmicrophone,36

WWaitblocks,43

ConfigurationPanel,58

creatingExplorer-Waitprogram,43–44

Discovery-Waitprogram,58–59

onProgrammingPalette,74

settings,43

usingsensorswith,58–60

usingtopollTouchSensor,73

usingwithColorSensor,79

usingwithShot-Roller,109–111

Walk-ForwardMyBlock,creatingforStriderrobot,135Walk-LeftMyBlock,creatingforStriderrobot,136Walk-RightMyBlock,creatingforStriderrobot,136walls

avoidingviaTouchSensors,74–75

avoidingviaUltrasonicSensor,60–61

website,companion,xxWheelmotors,usingwithCCC,280–281

Page 472: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

wires.SeedatawiresWorkArea

displayingSwitchblockson,64

moving,29

placingblocksin,26

XXOroperation,outputvaluefor,176

YYes/Nooutputplug,controlling,159

Page 473: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

troubleshootingandsolvingconnectionproblems

Whenbuildingandprogrammingtherobotsinthisbook,it’susuallynotverydifficulttomakeyourrobotworkbyfollowingtheinstructions.However,sometimesyoumayrunintoproblemstransferringyourprogramstotheNXT.Whenyoudo,thisappendixwillhelpyoufindsolutionstoyourproblemssothatyou’llbeabletomakeyourrobotworksuccessfully!

NOTE Ifthisappendixdoesn’tansweryourquestions,visithttp://discovery.laurensvalk.com/formoreinformation.Bythesametoken,ifyoucandownloadaprogramtotheNXTbutyourrobotdoesn’tworkthewayyouwantitto,theremaybeamistakeinyourprogram.Visitthebook’scompanionwebsitetodownloadtheready-madeprogramsandcomparethemtoyourown.

usingtheNXTcontrollertodownloadprogramstotheNXT

Onceyou’vefinishedcreatingaprogram,youtransferittotheNXTbypressingDownloadorbypressingDownloadandRunontheNXTcontrollerinyourNXT-Gsoftware,asshowninFigureA-1.Forthetransfertowork,yourrobothastobeconnectedtothecomputerwiththeUSBcable.(FortransfersviaBluetooth,see“ConnectingtotheNXTwithBluetooth”onpage289.)

Inadditiontothesetwooptions,youcanalsoclickDownloadandRunSelectedtotransferonlyselectedblockstoyourNXT.Forexample,ifyourprogramconsistsoftwoSoundblocksandtwoMoveblocksandyouselectonlytheMoveblocks,pressingDownloadandRunSelectedwilltransferonlytheselectedMoveblockstotheNXT.

Toabortarunningprogram,presstheStopbuttonontheNXTcontroller.

Page 474: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

FigureA-1:ButtonsontheNXTcontrolleratthebottomrightoftheNXT-GprogrammingsoftwareallowyoutotransferprogramstoanNXTrobotthatisconnectedtoyourcomputer.

usingtheNXTwindowWhenyouuseoneoftheNXTcontrollerbuttonsasdiscussedintheprevioussection,yourcomputershouldattempttoconnecttoyourrobotbeforedownloadingtheprogramautomatically.Ifthecomputerfailstoconnect,youcantrysettinguptheconnectionmanuallyusingtheNXTwindow(FigureA-2).Toopenthiswindow,clicktheNXTWindowbuttonontheNXTcontroller(FigureA-1).

ToconnecttoanNXTwithUSB,selectitfromthelist(theStatuscolumnshouldreadAvailable),andclickConnect.TorefreshthelistofavailableNXTs,clickScan.OnceconnectedtoanNXT,theNXTwindowshouldshowthepowerleftintheNXT’sbatteries,andtheStatuscolumnshouldreadConnected.

changingthenameofanNXTOnceconnectedtothecomputer,youcanpersonalizeyourNXTbychangingitsname(itsnameis“NXT”bydefault)usingtheNXTwindow(FigureA-2).Todothis,enteranameintheNameboxatthetoprightofthewindow,andclickthearrowtotherightofittoconfirm.ThenameyouentershouldappearatthetopoftheNXT’sscreen.ThenexttimeyouusetheNXTwindowtoconnecttoanNXT,thelistofNXTdevicesshouldshowyourNXT’spersonalizedname.

Page 475: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

problemsconnectingtoanNXTwithUSBIfyou’reunabletoconnectanNXTtoacomputerusingthemethoddiscussedin“UsingtheNXTWindow,”followthesedirectionsandthentryconnectingagain:1.MakesuretheNXTisturnedon.2.MakesuretheNXTisconnectedtothecomputerwiththeUSBcable(be

suretocheckbothendsofthecable).TheconnectionismadeproperlyiftheNXTdisplaysthelettersUSBonthetopleftofitsscreen.Ifthisdoesn’thelp,followthesesteps:

1.TurntheNXToffandbackon.2.CloseandrestarttheNXT-Gsoftware.

Ifyoustillcan’tsolveyourproblem,visitthecompanionwebsite(http://www.discovery.laurensvalk.com/)formoreinformation.

NOTE WhenyoutrytoconnectanNXTtoyourcomputerforthefirsttime,youmayneedadministrativerightsonyourcomputerinordertosucceed.Ifyouencounterthisproblem,askyoursystemadministratortologin,launchtheNXT-Gsoftware,andmaketheconnectiontotherobot.Whenyou’redone,youshouldbeabletoconnecttotheNXTevenusingyourownaccount.ThisshouldbetrueforbothUSBandBluetoothconnections.

FigureA-2:TheNXTwindowliststheNXTdevicesthatthecomputercan

Page 476: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

connecttoandthoseithasbeenconnectedtopreviously.TheConnectionTypecolumntellsyouwhetherthefoundNXTcanbeconnectedtoUSBorBluetooth.

problemsdownloadingprogramstotheNXTIfyoucan’ttransferaprogramtotheNXT,theremaybeseveralcauses.Beforeyouproceedtopossiblesolutions,makesurethatyourrobotisconnectedtothecomputerbymakingsurethattheStatuscolumnintheNXTwindowsaysConnected(FigureA-2).Ifnot,yourproblemismostlikelyaconnectionissue.Toresolveit,read“ProblemsConnectingtoanNXTwithUSB”onpage286.

Ifyourrobotisphysicallyconnectedtoyourcomputerandyoustillreceiveanerrormessagewhenyoutrytosendaprogramtotherobot(suchastheoneshowninFigureA-3),carefullyreadtheerrormessageandfollowtheappropriateinstructionsinthefollowingsections.

TheNXTdeviceisnolongerconnected.AlthoughyourNXTwasconnectedtothecomputer,itautomaticallydisconnected.ThiserrormessageappearswhenyoutrytodownloadaprogramaftertheUSBcableisremovedoraftertheNXTswitcheditselfoffafternotbeingusedforalongperiod.

Solution:TurntheNXTon,connecttheUSBcable,andretrydownloadingtheprogram.

TheNXTdeviceisoutofmemory.TheprogramsyoudownloadtoyourNXTarestoredinitsmemory.Whenyoucreateaprogramthatplayssoundfiles,thesefilesaretransferredtotheNXTaswell.YourNXThasonlylimitedmemory,soaftermakingseveralprograms,especiallyonesusingsoundfiles,theNXTwilleventuallyrunoutofmemory.

Solution:RemovefilesthatyounolongerneedfromtheNXT’smemory,asshowninFigureA-4.Whenyou’redone,youshouldbeabletodownloadnewprogramstotherobot.

Formoreonmanagingfilesinmemory,seetheNXT-G’shelpfiles,andclickFilesandMemoryontheNXTinthemenuontheleftofthehelppages.

datawireerrormessages

Page 477: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Whenyoucreateaprogramwithincorrectlywireddatawires,yourprogramwon’ttransfertotheNXT.Dependingonthetypeofmistakeinyourprogram,you’llseeoneofthefollowingerrormessages.*Thereisadatawirethatisconnectedtoaplugofthewrongtype(see“TheBrokenDataWire”onpage166).

*Thereismorethanonedatawireconnectedtothesameinputplug(see“ConnectingMultipleWirestoOneDataPlug”onpage167).

FigureA-3:Asampleerrormessagethatmayappearwhendownloadingaprogramtoarobot

Page 478: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

FigureA-4:ToremovefilesfromtheNXT’smemory,gototheNXTwindowandopentheMemorytab.Thiswillshowalistoffilesthatarecurrentlyonthebrick,sortedbycategory.(Hereyouseeonlythesoundfiles.)Toviewfilesinaparticularcategory,clickthecategoryontheleft(suchasProgramFiles).Onceyou’velocatedthefileyouwanttoremove,selectit,andclicktheDeletebutton.

*Thereisadatawirethatdoesnothaveadatasource(see“UsingSettingswithBothInputandOutputPlugs”onpage167).

Solution:Rereadtheappropriateparagraphinthisbooktofixincorrectlyconnectedwires.Iffixingjustonewiredoesn’thelp,deletesomemoreoralldatawiresinyourprogram,andreconnectthemappropriately.

Cannotdownloadneededfilefortheprogram.Thiserrormayoccurinprogramsthatusesoundorimagefilesthatyoumadeyourself.Ifthesoftwareisunabletolocatethem(mostlikelybecauseyouremovedthem),you’llseethiserror.

Solution:Re-createthefilesusingthesoundandimageeditorinthesoftware.

Theprogramisbroken.Itmaybemissing

Page 479: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

requiredfiles.YouseethiserrorwhenyoutrytosendaprogramtotheNXTthatusesaMyBlockthattheprogrammingsoftwarecan’tfindbecauseyoudeletedormovedit.

Solution:Re-createtheMyBlock,ormoveitbacktoMyDocuments\LEGOCreations\MINDSTORMSProjects\Profiles\Default\Blocks\MyBlocks.Next,removetheMyBlockfromtheprogramthatusesit,andchooseanewMyBlockfromtheCustomPalette.Ifthisdoesn’thelp,createanewMyBlockwithadifferentname.

ThefileiscurrentlyinuseontheNXTdevice.ThiserrorpopsupwhenyoutrytodownloadaprogramtoyourrobotwiththeDownloadbuttonontheNXTwhilethatsameprogramiscurrentlyrunning.

Solution:UsetheDownloadandRunbuttoninstead,oraborttherunningprogrambyclickingtheStopbuttonbeforeyoudownloadittotheNXT.

usingBluetoothtodownloadprogramstotheNXT

InsteadofusingtheUSBcabletotransferprogramstoyourrobots,youcanplugaBluetoothdongle(showninFigureA-5)intoaUSBportofyourcomputer,whichsendstheprogramstotheNXTwirelessly.Onceyou’vesetuptheconnectionbetweenyourcomputerandtheNXT,youtransferprogramstotheNXTasyouwouldwiththeUSBcable.

Page 480: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

FigureA-5:JustoneexampleofacompatibleBluetoothdongle

Bluetoothtransfersmakesprogrammingaloteasier,becausewhenusingBluetooth,youdon’thavetorepeatedlyconnectanddisconnecttheUSBcableeachtimeyoudownloadaprogram.

findingaBluetoothdongleTherearemanycompatibleBluetoothdongles,someofwhichcostlessthan$10.Generally,it’snotthedonglehardwarebutitsdriversincombinationwithyourcomputer’soperatingsystemthatcausethedongletoworkornot.Inmanycases,you’llbeabletosimplyplugthedongleintoyourcomputer,waitforthedriverstoinstallautomatically,launchtheNXT-Gsoftware,andfollowtheconnectionprocedureinthenextsection.Thedriversyou’llneedwilldependonyouroperatingsystemandyourBluetoothdongle.BesuretovisitthecompanionwebsiteforlinkstorecommendedBluetoothdongles.

connectingtotheNXTwithBluetoothFollowthenextstepstosetupyourfirstBluetoothconnectionbetweenthecomputerandtheNXT:1.PlugacompatibleBluetoothdongleintoafreeUSBportonyourcomputer.

Dependingonyouroperatingsystem,somedriversareautomaticallylocatedandinstalled.Usually,itisnotnecessarytoinstalltheadditionaldriversthatcomewithyourdongle.

2.ActivateBluetoothontheNXTbyturningtheNXTonandnavigatingtoBluetooth▸On/Off▸On.

3.InNXT-G,gototheNXTwindow,andclickScantosearchforyourNXTviaBluetooth.Thissearchprocessmaytakeabout30seconds.Whenready,thelistofNXTdevicesisupdatedwiththeNXTsthatareavailableforaBluetoothconnection.IfyourNXTisn’tlisted,clickScanagain.

4.SelecttheNXTyouwanttoconnectto(theConnectionTypecolumnshouldreadBluetooth),andclickConnect.

5.WhenyouconnectanNXTforthefirsttime,thesoftwaremayaskyoutoenterapasswordtoprotectyourconnection,butIrecommendthatyoustickwiththedefaultpassword(1234)becausethisiseasier,especiallywhenerrorsoccur,forcingyoutorunthesestepsmorethanonce.ClickOKto

Page 481: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

confirmthispassword.6.Ifyouhadtoenterapasswordinstep5,theNXTshouldnowmakeasound

andpromptyoutoenterthesamepassword.Sinceyou’reusingthedefaultpassword,justselecttheVsignbypressingtheorangeEnterbuttonontheNXT.Yourcomputershouldnowautomaticallyinstallsomeextradrivers.Ifnoerrormessagesappear,yourNXTshouldnowbeconnectedtothecomputerviaBluetooth,andyoushouldbereadytostartdownloadingprogramstoit.YoucantellwhetheranNXThasmadeaworkingBluetoothconnectionby

lookingatthetopleftoftheNXTscreen,whichshows<>whenconnectedand<whennotconnectedtoacomputer.IfyouhavejustoneNXT,youcanskipallofthesestepsonceyou’vegonethroughthemonce.IfyoutrytotransferaprogramtoyourNXTthenexttimeyoulaunchthesoftware,thesoftwareshouldautomaticallytryconnectingtotheNXTitwaslastconnectedto,whichis,inthiscase,yourNXTviaBluetooth.

problemsconnectingtoanNXTwithBluetoothOnceyou’vesetuptheBluetoothconnection,youusuallywon’thaveaproblemdownloadingprogramstotheNXT.IfdownloadingfailsbuttheBluetoothconnectionappearstobeworkingcorrectly,followthedirectionsin“ProblemsDownloadingProgramstotheNXT”onpage287.

However,insomecases,settinguptheBluetoothconnectionitselfisproblematic.ThereisnoeasywaytosolveBluetoothproblemsbecausetheyvarydependingon,forexample,whichBluetoothdongleandwhichoperatingsystemyouuse.Still,thefollowingsolutionsmayhelpinsomecases.*Makesureyouhaveadministrationrightsonyourcomputer.*RestarttheNXT-Gsoftware,andrestartyourNXT;thenretryconnecting.*IntheNXTwindow,removealltheNXTdevicesthatthecomputerpreviouslyconnectedtobyselectingthemandclickingRemove.ThenclickScan,andwhenit’sfinishedsearchingforNXTs,retrytheconnection.

conclusion

Page 482: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

Ihopethatthisshortappendixhashelpedyoufindasolutiontoyourproblem.Ofcourse,onlyafewproblemsandsolutionsarelistedhere,andyoumayhavemanyotherquestionsrelatingtooneofthebuildingorprogramminginstructionsinthisbook.Feelfreetopostyourquestiontothecompanionwebsite(http://www.discovery.laurensvalk.com/).

Moreno-nonsensebooksfrom nostarchpress

TheUnofficialLEGO®MINDSTORMS®NXT2.0Inventor’sGuide

byDAVIDJ.PERDUEwithLAURENSVALK

DECEMBER2010,336PP.,$29.95

ISBN978-1-59327-215-9

Page 483: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheLEGO®TechnicIdeaBook:SimpleMachines

byYOSHIHITOISOGAWA

OCTOBER2010,168PP.,$19.95

ISBN978-1-59327-277-7fullcolor

TheUnofficialLEGO®TechnicBuilder’sGuide

Page 484: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

byPAWEŁ“SARIEL”KMIEC

NOVEMBER2012,352PP.,$29.95

ISBN978-1-59327-434-4fullcolor

TheCultofLEGO®

byJOHNBAICHTALandJOEMENO

NOVEMBER2011,304PP.,$39.95

ISBN978-1-59327-391-0fullcolor,hardcover

Page 485: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

TheUnofficialLEGO®Builder’sGuide,2ndEdition

byALLANBEDFORD

NOVEMBER2012,240PP.,$24.95

ISBN978-1-59327-441-2fullcolor

TheLEGO®AdventureBook,Vol.1:Cars,Castles,Dinosaurs&More!

Page 486: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

byMEGANROTHROCK

NOVEMBER2012,200PP.,$24.95

ISBN978-1-59327-442-9fullcolor,hardcover

PHONE:800.420.7240OR415.863.9900

EMAIL:[email protected]

WEB:WWW.NOSTARCH.COM

Page 487: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

companionwebsite

Visithttp://www.discovery.laurensvalk.com/forupdates,errata,downloadableprograms,hintsforsolvingthediscoveries,contests,andmore.Besuretovisitthewebsite’sforumifyouhavequestionsaboutthebookandtoshareyourdiscoverieswiththeworld!

TheLEGOMINDSTORMSNXT2.0DiscoveryBookissetinChevin.ThebookwasprintedandboundbyTranscontinental,Inc.atTranscontinentalGagnéinLouiseville,Quebec,Canada.ThepaperisDomtarHusky60#Smooth,whichiscertifiedbytheForestStewardshipCouncil(FSC).ThebookhasanOtabindbinding,whichallowsittolieflatwhenopen.

LEGOMINDSTORMSNXT2.0partslist

Page 488: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots
Page 489: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

DISCOVERTHECAPTIVATINGWORLDOFLEGO®MINDSTORMS®NXT2.0!

TheLEGO®MINDSTORMS®NXT2.0Discoverybookisthecomplete,illustratedbeginner’sguidetoMINDSTORMSthatyou’vebeenlookingfor.

AuthorLaurensValk’scrystal-clearinstructionswillshowyouhowtoharnesstheNXT2.0setandsoftwaretobuildandprogramyourownrobots.Thebook’smanystep-by-steptutorialswillmakeiteasyforyoutobuildcomplexrobotsthatmove,monitorsensors,anduseadvancedprogrammingtechniqueslikedatawiresandvariables.

Fiftysampleprogramsandmorethan85programmingandbuildingchallengeswillsparkyourimaginationasyoufollowdetailedbuildinginstructionstocreateaseriesofeightinnovativerobots:*Explorer,arovingvehicle*Discovery,arobotthatusessensorstonavigatearoundaroomandfollowlines

*Shot-Roller,aroboticdefensesystemthatcanshootinanydirection*Strider,asix-leggedwalkingcreature*SmartBot,arobotyou’llusetoexploreadvancedprogrammingtechniques*TheSnatcher,aroboticarmthatgrabs,lifts,andmovesobjectsautonomously*TheHybridBrickSorter,amachinethatsortsLEGObricksbycolorandsize

*CCC,acompactchimneyclimberThisisaperfectintroductionforanyonenewtobuildingandprogrammingwiththeLEGOMINDSTORMSNXT2.0set.Withthisbookasyourguide,you’ll

Page 490: The LEGO MINDSTORMS NXT 2.0 Discovery Book: A Beginner's Guide to Building and Programming Robots

bebuildingyourownout-of-this-worldcreationsinnotime!

abouttheauthorLaurensValkisamemberoftheMINDSTORMSCommunityPartners,aselectgroupofMINDSTORMSexpertswhohelptestanddevelopnewNXTproducts.HehasbeeninventingrobotswiththeMINDSTORMSNXTsetssincetheirintroduction,andoneofhisrobotdesignsappearsontheNXT2.0packaging.Valkisaco-authorofLEGOMINDSTORMSNXTOne-KitWonders(NoStarchPress)andacontributortoTheNXTSTEPblog(thenxtstep.blogspot.com).HelivesintheNetherlands,whereheteachesrobotics.

RequiRements:ONELEGOMINDSTORMSNXT2.0SET(LEGOSET#8547)

THISBOOKISNOTAUTHORIZEDORENDORSEDBYTHELEGOGROUP.