Upload
others
View
10
Download
0
Embed Size (px)
Citation preview
quickbuildingreferencechart
THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK
THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK
abeginner’sguidetobuildingandprogrammingrobots
laurensvalk
THELEGO®MINDSTORMS®NXT2.0DISCOVERYBOOK.Copyright©2010byLaurensValk.
Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.
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
StarchPress,Inc.Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespectiveowners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weareusingthenamesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementofthetrademark.LEGO®,MINDSTORMS®,thebrickconfiguration,andtheminifigurearetrademarksoftheLEGOGroup,whichdoesnotsponsor,authorize,orendorsethisbook.Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthiswork,neithertheauthornorNoStarchPress,Inc.shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.
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/.
aboutthetechnicalreviewer
Dr.DamienKeeholdsaPhDinroboticsandabachelor’sdegreeinelectricalengineering,bothfromtheUniversityofQueensland,Australia.Hehasbuiltawidevarietyofrobots,frommaze-solvingmicetohumanoidstorobotsthatdispensetrafficcones.DamienhasbeenheavilyinvolvedwiththeRoboCupJuniorcompetitionsince2001,andin2009hewaselectedchairmanofRoboCupJuniorAustraliaandtechnicalchairoftheRoboCupJuniorInternationalRescueCommittee.Since2003,Damienhasbeenconductingroboticsworkshopsforteachers,educators,andstudentsworldwide,andhehaswrittenseveralteacherresourcebooks.HeisamemberoftheMINDSTORMSCommunityPartners;acontributortotheNXTSTEPblog;andeditorinchiefofTheNXTClassroom(http://theNXTclassroom.com/),awebsiteprovidingresourcesandsupportforteachers.
briefcontents
acknowledgments
introduction
partIgettingstartedchapter1collectingtheequipmentforyourrobot
chapter2buildingyourfirstrobot
chapter3creatingandmodifyingprograms
chapter4workingwithprogrammingblocks:move,sound,anddisplay
chapter5waiting,repeating,andotherprogrammingtechniques
partIIbuildingandprogrammingrobotswithsensorschapter6understandingsensors
chapter7usingthetouch,color,androtationsensors
chapter8shot-roller:aroboticdefensesystem
chapter9strider:thesix-leggedwalkingcreature
partIIIcreatingadvancedprogramschapter10usingdatahubsanddatawires
chapter11usingdatablocksandusingdatawireswithloopsandswitches
chapter12usingvariables,constants,andplayinggamesontheNXT
partIVadvancedrobotprojectschapter13snatcher:theautonomousroboticarm
chapter14hybridbricksorter:sortbricksbycolorandsize
chapter15CCC:thecompactchimneyclimber
appendixtroubleshootingandsolvingconnectionproblems
index
contentsindetail
acknowledgments
introductionwhythisbook?isthisbookforyou?howdoesthisbookwork?
thediscoverieswhattoexpectineachchapter
gettinghelp:thecompanionwebsiteconclusion
PARTIGETTINGSTARTED1collectingtheequipmentforyourrobotwhat’sinthebox
theNXTbricktheNXT-Gprogrammingsoftwarethetestpad
insertingbatteriesconclusion
2buildingyourfirstrobotbuildingtheexplorer
buildingtip:beamsandaxlesbuildingtip:frictionandnonfrictionpinsconnectingthecables
usingtheNXTbuttonstonavigateontheNXTbrick
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
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!
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!
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!
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!
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!
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
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
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!
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
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
neverhavemet.
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
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
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
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!
PARTI
gettingstarted
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.
Figure1-1:TheLEGOMINDSTORMSNXT2.0set
Figure1-2:TheNXTkitcontainsvarioustypesofparts.
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.
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.
insertingbatteriesTopowertherobot,insertsixAAbatteriesintotheNXT,asshowninFigure1-5.YoucanusestandardrechargeableornonrechargeablebatteriesortheLEGOrechargeablebattery(LEGOcatalog#9798)withthetransformer(#9833).YoumayalsousethenewLEGOrechargeablebattery(#9693)withitstransformer(#8887).
Figure1-4:TheTestPad
conclusionNowthatyou’vecollectedeverythingyouneedtobuildandprogramaworkingrobot,you’rereadytostartbuildingone.InChapter2you’lllearnmoreabout
theNXT,motors,andcablesasyoubuildyourfirstrobot.
Figure1-5:YoucanpowertheNXTbrickwithsixAAbatteriesortheLEGOrechargeablebattery.
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.
Figure2-1:TheExplorer
Figure2-2:Billofmaterials
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-
and-whiteimagesinthebook.
connectingthecablesTousetheNXTmotors,youneedtoconnectthemtotheNXTbrickusingcables.MotorsareconnectedtooutputportscalledA,B,andC,asshowninFigure2-4.
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
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.
Figure2-7:TurningontheNXTBrickwiththeEnterbuttonwillopenthemainmenu.
selectingandchoosingitemsTheselecteditemisalwaysinthemiddleofthescreen,asshowninFigure2-8.Youcanswitchtoiconsontheleftandtherightwiththelightgrayarrowbuttons.Toselectanitem(Figure2-8),presstheEnterbutton.
Figure2-8:YoupresstheEnterbuttontochooseaselecteditem.
Toreturntothepreviousmenu(Figure2-9),pressthedarkgrayExitbutton.
Figure2-9:YoucanreturntothepreviousmenubypressingtheExitbutton.
turningoffthebrickToturnoffthebrick,returntothemainmenu,andpresstheExitbutton.Whenyouseetheoptionforturningoffthebrick,eitherselectthecheckmarktoturnitofforselecttheXicontocancel(Figure2-10).
Figure2-10:TurningofftheNXTbrick
runningaprogramNXTrobotsbeginperformingtheiractionswhenyouselectandrunaprogramthathasbeentransferredtothebrick.Youhaven’ttransferredaprogramtothebrickyet,butyoucantryasampleprogramthatisalreadyonthebrick,called
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.
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.
Figure3-1:Therobotconnectedtothecomputer
3.CreateanewprogrambyenteringExplorer-1intheCreatenewprogrambox(locatedinthemiddleofthescreen),andthenclicktheGo>>button(Figure3-3).Youcanchooseanynameforyourprogram,butit’sagoodideatogiveitadescriptivenamethatwillbeeasyforyoutorecognizelater.Forexample,inthiscase,youcancallyourprogramExplorer-1becauseitisthefirstprogramfortheExplorerrobot.
Figure3-2:TheNXT-Gstartupscreen
Figure3-3:Creatinganewprogram
4.PickablockandplaceitonthelocationindicatedbyFigure3-4.Rememberthataprogramisbasicallyalistofinstructionsforactionsthattherobotshouldperform.Thesingleblockyouplacehereisjustsuchaninstruction—onethatmakestherobotmoveforwardforashortwhile.
Figure3-4:Pickingandplacingablock
5.Onceyou’vefinishedsteps1through4,clicktheDownloadandRunbutton,andwaitforyourrobottostartmoving.(Figure3-5).Eachtimeyouwanttodownloadtheprogramagain,simplyclickthisbutton.
Figure3-5:Downloadingtheprogramtotherobot
Congratulations!Ifyourrobotmovesforwardashortdistance,you’vesuccessfullycreatedyourfirstprogram.
NOTE Ifforsomereasonyourrobotdidnotmoveasdescribedorifyou
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.
Figure3-6:TheNXT-Gsoftwarewindowhasseveralsections.Youusedeachofthelabeledoneswhenyoucreatedyourfirstprogram.
Figure3-7:TheProgrammingPalette(aclose-upofsection1inFigure3-6)
2.workareaOnceyou’veselectedablocktouseinyourprogram,youplacethatblockontheWorkArea,asshowninFigure3-8.TheWorkAreaiswhereyoucreate
yourprogram.Programsoftenconsistofmorethanoneblock.
Figure3-8:Onceyou’vepickedablockbyclickinganiconontheProgrammingPalette,youplaceitontheWorkArea.Ifit’sthefirstblockinaprogram,youplaceitontheStartArea.
TomoveablocktotheWorkArea,simplyclickaniconontheProgrammingPalette,andthenclicktheWorkAreawhereyouwanttoplacetheblock.
movinganddeletingblocksOnceyou’veplacedablockontheWorkArea,youcanmoveitbyclickingitwiththeleftmousebuttonandkeepingthebuttonpressedasyoumovetheblockaround.TodeleteablockfromtheWorkArea,clicktoselectit,andpresstheDELETEkey.
3.startArea
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
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.
5.configurationpanelIfyouclickaprogrammingblockontheWorkArea,theConfigurationPanelshowsupatthebottomofthesoftwarewindow(Figure3-11).
Youlearnedthateachblockmakestherobotperformacertainaction.TheblockyouseeinFigure3-10makestheExplorermove,buttheexactmovementisspecifiedwiththeConfigurationPanel.Forinstance,youcanusethepaneltoconfiguretherobottomovebackwardinsteadofforward.
Figure3-10:Thesection“WorkingwiththeNXT-GSoftware”discussestheseremainingsections.
Figure3-11:TheConfigurationPanel
Manydifferentprogrammingblocksexist,eachwithitsownConfigurationPanel.SubsequentchapterswillteachyouaboutmanyoftheseblocksandtheirConfigurationPanels.
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
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.
Figure3-14:ThebuttonsontheToolbarareusedtomanageandmodifyprograms.
Figure3-15:Copyingaseriesofblocks.Step1:Keeptheleftmousebuttonpressedwhileyoudragaselectionaroundtheblocksyouwanttocopy;thenpresstheCopybutton.Step2:ClickthePastebutton.Step3:Usetheleftmousebuttontodragthenewblocksnexttotheblocksthatwerealreadythere.
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
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
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
programs,aswellashowtotransferprogramstotheNXTbrick.Nowthatyou’vegainedthisessentialbitofinformation,you’rereadyto
takeonsomeseriousprogrammingchallengesinChapter4.
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
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
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
accomplishthis,you’llchangethesettingsintheConfigurationPanelofeachblock,asshowninFigure4-3.
3.Next,you’llmodifytheconfigurationsofthesecondblock,asshowninFigure4-4.ThisblockwillmaketheExplorerspinquicklytotheright.Whenbothwheelshavemadetwocompleterotations,themotorswillstopasspecifiedintheblock.(You’lllearnmoreabouteachofthesettingsinthenextsection.)
Figure4-3:TheconfigurationofthefirstblockintheExplorer-Moveprogram.Clicktheblocktoselectit,andconfigureyourblocksettingstolooklikethoseinthisfigure.TheselectedblockmakestheExplorerdrivebackwardslowlyforthreeseconds.
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.
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
Explorermoveforthreeseconds.OtheroptionshereincludeRotationsandDegrees:*Rotationscontrolsthenumberoftimesthatthewheelsgothroughacompleterotation.Forexample,whenyousetDurationto2Rotationsinthesampleprogram,bothwheelsmadetwocompleterotations.
*DegreesworkslikeRotation,exceptthatitcontrolsthenumberofdegreesthatthewheelsturn.Forexample,youcouldsetDurationto180Degreestomakethewheelsturnone-halfrotation.
(You’lllearnabouttheUnlimitedoptioninChapter5.)
Figure4-5:TheMoveblockConfigurationPanelcontainsseveralsubsectionstochangethewaytherobotmoves.
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,
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
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
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.
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
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.
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.
Figure4-11:ThefourblocksoftheExplorer-Soundprogram.UsetheseimagesoftheConfigurationPanelstoconfigureeachoftheprogrammingblocks.Panel“a”showsthesettingsofblock“a.”
NOTEThelettersa,b,c,anddaretheretohelpyouunderstandwhichConfigurationPanelbelongstowhichblock.They’renotpartoftheactual
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
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
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
moreinformation,seepage57oftheNXTuserguide.)Whenyou’redonecreatingyourimage,youcandisplayitwiththeDisplayblockasyouwouldanyotherimage.
displayingtextIfyouselectTextintheActionbox,you’llseeaConfigurationPanelasshowninFigure4-14.
EnterthetextyouwanttodisplayintheTextbox.UsethesettingsinthePositionboxtodefinewherethetextshouldbedisplayedeitherbydraggingthetextwithyourmouseorbyspecifyingtheXandYvaluesaswithdisplayingimages.
YoucanalsopositionlinesoftextbysettingtheLinenumber.Selecting1forLinewilldisplaytextatthetopofthescreen,whileselecting8forLineputstextonthebottomofthescreen.Thisconfigurationisusefulwhenyouwanttodisplayalongersentencethatdoesn’tfitononeline:Youcansplitthesentenceintomultiplepartsanddisplayeachpartononetextlinetokeepyourtextnicelyaligned.
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
image.Therobotthenstartstomove,andtheimagestaysonthescreenwhiletheMoveblock(b)isrunning.ThenextDisplayblock(c)isalsoconfiguredtoclearthescreen,soitremovestheimagebeforeitwritesalineoftextonthescreen.TheprogramthenmovesontoanotherDisplayblock(d),whichputsacircleonthescreen.Thisblockdoesn’tclearthescreeninadvance,soyou’llseeboththetextandthecircleonthescreen.Finally,aMoveblockmakestherobotturntotheright,andthentheprogramends.
Figure4-15:TheConfigurationPanelofaDisplayblockconfiguredtodisplayadrawing
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.”
Figure4-17:ThedrivingpatternandthenavigationimagesofDiscovery#8
DISCOVERY#9:CIRCLETIME!Difficulty:EasyCanyoumaketheExplorerdriveinacircularpatternwithadiameterofabout1meter(3feet)?You’llneedonlyoneMoveblocktoaccomplishthis.HowdoyouconfiguretheDurationandSteeringsettings?Andhowdoeschangingthemotorspeedaffectthecircle?
DISCOVERY#10:W8FORTHEEXPLORER!Difficulty:MediumProgramtheExplorertodriveinafigureeight,asshowninFigure4-18.The
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?
5
waiting,repeating,andotherprogrammingtechniques
Thepreviouschaptertaughtyouhowtoprogramyourrobottoperformavarietyofactions,suchasmoving.Inthischapter,you’lllearnseveralprogrammingtechniquesthatwillallowyoutodomorewiththeblocksyouusedearlier,includinghowtopauseaprogramwithWaitblocks,howtorepeatasetofactionswithLoopblocks,howtorunmultipleblockssimultaneously,andevenhowtomakeyourownso-calledMyBlocks.
thewaitblockSofaryou’vebeenusingthreedifferentprogrammingblockstomaketherobotmove,playsounds,ordisplaysomethingonitsscreen.Nowyou’llmeetablockthatdoesnothingmorethanpausetheprogramforagivenamountoftime.ThisblockistheWaitblock,asshowninFigure5-1.
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
accordingtotheinstructionsshowninFigure5-2,andrunit.ThisprogramwilldisplaytwotextlinesontheNXTscreen.
Figure5-2:TheconfigurationoftheblocksintheExplorer-Waitprogram
understandingtheexplorer-waitprogramWhenyouruntheExplorer-Waitprogram,theWaitblocksgiveyoutimetoreadwhatisdisplayedontheNXTscreen.HadyounotplacedtheWaitblocksintheprogram,theprogramwouldendimmediatelyafterthetextwasdisplayedontheNXTscreen,makingitimpossibletoreadthistext.
moreonthemoveblock:movingunlimited
TheMoveblockcomesinhandywhenyouwanttomaketheExplorerdrivearound,andyou’veuseditinmanyofyourprogramssofar.However,thereisanimportantsettingonitsConfigurationPanelthatyouhavenotusedyet.
theunlimitedoption
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.
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.)
Figure5-4:TheconfigurationoftheblocksintheExplorer-Unlimitedprogram
theloopblock
Imagineyouarewalkingonasquare-shapedline,liketheoneshowninFigure5-5.Asyouwalk,youfollowacertainpatternoverandoveragain:Gostraight,thengoright,gostraight,goright,andsoon.
Figure5-5:TheExplorermovinginasquare
Figure5-6:TheLoopblockanditsConfigurationPanel(1).Toplaceblocks
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
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.
Figure5-8:TheconfigurationoftheblocksintheExplorer-Loopprogram
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
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
programasafoundationforthisexperiment.
NOTE Ifyoudidn’tsavetheExplorer-Loopprogramearlier,createitagainbyfollowingthedirectionsinFigure5-8,ordownloaditfromthecompanionwebsite.
1.SelecttheblocksthatyouwanttoturnintoaMyBlock,andclicktheCreateMyBlockbutton,asshowninFigure5-11.
Figure5-11:SelectingtheblockstobeturnedintoaMyBlock
2.EnteranameforyourMyBlockintheBlockNamebox,suchasSquare,asshowninFigure5-12.UsetheBlockDescriptionareatodescribeyourblocksothatyou’llrememberhowitworksifyouwanttoreuseitlater,andthenclickNext.
Figure5-12:EnteranameanddescriptionforyourMyBlock.
3.DragiconstoyourblockfromtheIconBuildertogiveitauniquelook(asshowninFigure5-13),andthenclickFinish.
Figure5-13:AddingiconstoyourMyBlock
usingmyblocksinprogramsOnceyou’vefinishedcreatingyourMyBlock,itshouldappearontheWorkAreaandintheCustomPalette,whichyoucanopenasshowninFigure5-14.(ThefigurealsoshowstheExplorer-MyBlockprogram.)
Figure5-14:TheconfigurationoftheblocksintheExplorer-MyBlockprogram.YoucanfindMyBlocksontheCustomPalette.(TheMyBlock’sConfigurationPanelsarenotshownbecausetherearenosettingstochangeonthesepanels.)
Whenyouruntheprogram,therobotshouldfirstmoveinasquare(controlledbythesquareMyBlock)andthenturn,makeasound,anddriveanothersquare.
editingmyblocksYoucaneditMyBlocksafteryoucreatethem.Todoso,double-clickaMyBlockontheWorkAreatorevealitscontents,andthenedititasyou’dlike.Whenyou’refinished,clickSave,andreturntotheprogramthatusestheMyBlock.
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.
Figure5-15:BlocksontheMainSequenceBeamandaParallelSequenceBeamarerunatthesametime.NotethattheWaitBlockherecausesonlythesequenceofblocksitappearsintopause;theblocksontheParallelSequencearenotaffectedbytheWaitBlock.
Figure5-16:TheconfigurationoftheExplorer-Parallelprogram.PlacetheblocksrequiredforthisprogramontheWorkArea(1).Next,connectthetwoSequenceBeamsasshowninthefigure(2).
DISCOVERY#17:LET’SMULTITASK!Difficulty:EasyExpandtheExplorer-Parallelprogram(Figure5-16)tomaketherobotdriveintrianglesindefinitelywhileatthesametimeplayingatunecomposedofdifferentnotes.
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!
InBuildingDiscovery#1(inChapter4),youfoundinstructionstocontrolathirdNXTmotor.ThistimeyouarechallengedtousetheextramotortocreateawavinghandforyourExplorer.UseotherLEGOpartstofurtherdecorateyourrobot,andturnitintoyourownMr.Explorer.Makehimrepeatedlywavehishandandplaysoundslike“Goodmorning!”atthesametime.
PARTII
buildingandprogrammingrobotswithsensors
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
you’lllearninChapter7).
Figure6-1:TheDiscoveryrobot:anenhancedversionoftheExplorerequippedwithanUltrasonicSensortomaketherobot“see”
Figure6-2:TheNXTkitcomeswithanUltrasonicSensor(left),twoTouchSensors(middle),andaColorSensor(right).
YouconnectthesensorstotheNXTviainputports,numbered1through4,asshowninFigure6-3.
Figure6-3:Sensorsareconnectedtoinputports.
Inthischapter,you’llexploretheUltrasonicSensor,andyou’lltakeamoredetailedlookattheothersensorsinChapter7.Theprogrammingtechniquesthatyou’lllearnfortheUltrasonicSensorcanbeusedforallthesensorsinthekit.
understandingtheultrasonicsensorTheUltrasonicSensorservesasyourrobot’seyes.To“see,”thesensormeasuresthedistancebetweenitandotherobjects(asshowninFigure6-4).TheNXTretrievestheinformationfromthesensorandusesitsmeasurementsinprograms.Forexample,usinginputfromthissensor,youcouldmakeyourrobotsay“Hello”whentheultrasonicsensorreportsanobjectinfrontofitthat’snearerthan50cm.
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
sensor’s“eyes”towardtheceilingwhilemeasuring.Ifyouseeonlyquestionmarksonthescreen,youmightneedtoholdthesensorupalittleclosertotheceiling.
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
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.
Figure6-7:TheWaitblockconfiguredtopollanUltrasonicSensor
Figure6-8:TheconfigurationoftheblocksintheDiscovery-Waitprogram.Experimentwiththetriggervalue(50cmhere)bychangingittomaketherobotresponddifferently.
Now,beforeyouproceedwithothersensorprogrammingtechniques,trytosolveDiscovery#20togetabetterunderstandingofhowtoworkwithsensors.
DISCOVERY#20:HELLOANDGOODBYE!Difficulty:Medium
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
UltrasonicSensorseessomethingthat’scloserthan25cm(10inches).
Figure6-9:TheprogramflowfortheDiscovery-Avoidprogram.Afterturningright,theprogramreturnstothestart,andtherobotmovesforwardagain.
Figure6-10:TheconfigurationoftheblocksintheDiscovery-Avoidprogram
DISCOVERY#21:AVOIDWALLSANDABADMOOD!
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
NowmaketheDiscovery-LoopprogramshowninFigure6-11.Whenyourunthisprogram,therobotshouldmovebackandforthrepeatedlyuntilthesensorspotssomethingcloserthan25cm(10inches).
Thisprogramdoesn’talwaysrespondtoobjectsvisiblewithin25cmoftherobotbecauseitpollsthesensoronlyonceperrepetition,justafteralltheblocksinsidetheloopcomplete.Forthisreason,whenyouquicklymoveyourhandinfrontoftherobotwhilethefirstblockisrunning,therobotwon’tnoticeyourhand.
Figure6-11:TheconfigurationoftheblocksintheDiscovery-Loopprogram
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.
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
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.
Runthisprogrammultipletimestodeterminewhenyoumustkeepyourhandinfrontofthesensortomaketherobotgobackward.DoingsoshoulddemonstratethatwhenyouusetheSwitchblockinyourprograms,therobotpollsthesensoronlyonceandcomparesthesensorvaluetothetriggervaluetoseewhethertheparticularconditionistrue.Inthisprogram,thesensorvalueismeasuredaftertherobotfinishesgoingforward(whentheMoveblockfinishes).
Figure6-15:TheDiscovery-Switchprogramhastherobotdecidewhatdobasedonasensorreading.
DISCOVERY#24:SEETHEDISTANCE!Difficulty:EasyLet’spracticewiththeSwitchblock!TrytocreateaprogramtoimplementthedecisiontreeshowninFigure6-16.HowdoyouconfiguretheSwitchblock,andwhydoyouhavetoputaWaitblockattheendoftheprogram?
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
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).
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.
willcontinuetosay“Yes”and“No”basedonthesensorreading.CreatetheDiscovery-RepeatprogramshowninFigure6-19now.
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.
Usethismotortomoveaself-madebarrierthatstopscarsfromcrossingtherailwayifatrainpasses.UsetheUltrasonicSensortospotwhenamodeltrainapproachesandwhenthebarriersshouldbelowered,aswellaswhentheyshouldberaisedagain.
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.
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.
creatingthebumperattachmentwithtouchsensors
You’llnowcreateanextensionforyourDiscoveryrobotthatusestwoTouchSensorsasbumpers(Figure7-1)toallowyourrobottofeelobjectsthatitrunsinto.Onceitdetermineswhichbumperwaspushed,therobotwillbackupandturnawayfromthisobject.Createthebumpersnow,asshownintheinstructionsonthenextpages.
Figure7-2:TheTouchSensordetectsthreeactions:pressed,released,andbumped.
connectingthecablesNowconnectthecablesthatyou’vealreadyaddedtotheTouchSensorstotheNXT,asshowninFigure7-3.
FromnowonI’llrefertotheTouchSensorconnectedtoport1astheRightTouchSensorandtheTouchSensorconnectedtoport2astheLeftTouchSensor.
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.
Figure7-4:TheConfigurationPanelofaWaitblock,configuredtopollaTouchSensor.OntherighthalfofthepanelarethespecificsettingsfortheTouchSensor.TheConfigurationPanelsofLoopandSwitchblocksthatcontrolaTouchSensorcontainthesamesettings.
Figure7-5:ConfigurationoftheblocksintheDiscovery-Touchprogram
NOTE TheWaitblocksontheProgrammingPalettearebasicallyallthesame.ThedifferencebetweenthemisthateachblockhaspresetControlandSensorsettingstomakeprogrammingeasier.
avoidingwallswithtouchsensors
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
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?
Figure7-7:Step1:TheblocksshownhereturnthemotorsonandhandlethefirstdecisionwithaSwitchblock.ThecompletesequenceofblocksisplacedinsideaLoopblockconfiguredtoloopforever.
Figure7-8:Step2:TheblocksyouaddinthissteparerunwhentheRightTouchSensor(onport1)isnotpressed.Theblocksenabletherobottomaketheseconddecision.Ifneithersensorispressed,therobotdoesn’ttakeanyaction,anditreturnstothebeginningoftheprogramtoseewhetherasensorisbeingpressed.
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.
Figure7-10:ConnectingtheColorSensortotheDiscoveryrobotusingtheshortcable
Figure7-11:TheplacementoftheDiscoveryrobotandtheColorSensorontheTestPad
usingtheviewmodetopollthecolorsensorTopolltheColorSensor,selectView▸Color▸Port3onyourNXT,placeyour
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
robotwillwaituntilthesensorreportsacolorthatiseithergreenoryellow.IfyouweretoselectOutsideRange,theblockwouldwaituntilthesensorspotssomethingthat’snotgreenoryellow.
stayinginsideacoloredlineYournextprogram,Discovery-Circle,willdemonstratehowyoucanusetheColorSensorasalinedetector.Onceyourprogramisloaded,you’llplacetheDiscoveryrobotinthecircleontheTestPadandhaveitdrivearoundwithoutleavingthecircle.Figure7-13showstheprogramflowforthisbehavior;Figure7-14showshowtocreatetheprogram.
Figure7-13:TheprogramflowoftheDiscovery-Circleprogram
Figure7-14:TheconfigurationoftheblocksintheDiscovery-Circleprogram.TheWaitblockisconfiguredtowaituntilthesensorseessomethingthatisblackasspecifiedintheUntilsetting(usingtheslidingbars).
BUILDINGDISCOVERY#4:CLEANTHATTESTPAD!WiththeDiscovery-Circleprogramtherobotconstantlymovesthroughthecircle.IfyouputsomeLEGOpiecesinthecircle(Figure7-15),yourrobotwill
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.
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).
Figure7-17:Discoverysteersrightifitseestheblackline(a)andsteersleftifitseesthewhitearea(b).AsDiscoverysteers,itmovesforward,soifyourepeatthisbehavior,youendupwithaline-followingrobot.
Figure7-18:TheconfigurationoftheDiscovery-Lineprogram.NotethattheDurationsettingsintheMoveblocksaresettoUnlimited.Oncetherobotstartstoturn,itinstantlygoesbacktothebeginningoftheprogramtoseewhetheradifferentcolorhasbeendetectedorwhetheritshouldkeepturninginthesamedirection.UnlimitedMoveblocksjustswitchonthemotorsandhavetheprogramcontinue.
usingtheNXTbuttonsassensorsInadditiontotheUltrasonic,Color,andTouchSensors,theNXTcontainsitsownsensors:theNXTbuttons.YoucanuseboththeEnterandRightArrowandLeftArrowbuttonsontheNXTjustlikeyouuseTouchSensors.Forexample,youcanmaketherobotturnaroundifyoupresstheRightArrowbutton.
TousetheNXTbuttons,you’llconfigureaWait,Switch,orLoopblockset
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.
HINTYoucanmaketheprogramevenmoreinteractiveifyouimplementtheUltrasonicSensorinyourprogram.Howcanyouuseitasasoundtrigger?
Figure7-19:TheconfigurationoftheblocksintheDiscovery-Buttonprogram.Whenyourunthisprogram,therobotshouldturnrightwhenyoupresstheRightArrowbutton.
therotationsensorsWhenyoutelltherobottomoveforwardforthreerotationswiththeMoveblock,thevehicleknowsthatitshouldstopmovingwhenthewheelshaveeachmadethreerevolutions.TherobotknowsthisbecausetheRotationSensorineachNXTmotortellstheNXThowmuchthemotorshaveturned.
Youcanusetheinformationfromthissensorinyourprograms,for
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
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.
resettingtherotationsensorAsaprogramruns,theRotationSensorvaluechangesasyouturnamotorbyhandorifaMoveblockmakestherobotmove.Sometimes,though,itisusefultoresetthisvaluetozero.Forexample,youmightwanttomodifytheDiscovery-Rotationprogramtoresetthesensorafteritconfirmsthatthemotorhasturned180degrees.WithaLoopblockandtheActionsettingspecifiedtoRead,theRotationSensorwillrepeattheblocksinituntilthetriggervalueisreached.WhenResetisselected,thesensorvalueisresettozeroaftereachloop.Therefore,aLoopblockwiththissettingstopsonlyifthetriggervalueisreachedduringoneloop.
Figure7-21:TheconfigurationoftheblocksintheDiscovery-Rotationprogram.ExperimentwiththissensorbychangingthesettingsintheUntilboxoftheLoopblocktoseewhateachsettingreallydoes.
DISCOVERY#35:ROTATIONALMUSIC!Difficulty:MediumTheprogramshowninFigure7-22playsdifferenttonesdependingonhowtheleftandrightwheelsofDiscoveryarerotated.Ifawheelisturnedforward,therobotplaysadifferenttonethanwhenitisturnedbackward.Canyoufigureouthowthisprogramworksandhowitisconfigured?
HINTThehiddentabsoftheSwitchblocksalsocontainSoundblocks.
Figure7-22:Canyoure-createtheprogramshownhere?Howdoyouthinktheblocksshouldbeconfiguredtomaketherobotplayfourdifferenttonesdependingonhowthewheelshaveturned?
NowmodifytheDiscovery-Rotationprogram.ChangetheActionsettingtoReset,andrunthemodifiedprogramtoseehowthisworks.
NOTE IfyouselectResetinaSwitchblock,thevalueisresettozeroafterthesensorvalueiscomparedtothetriggervalue.YoucannotresetthesensorvaluewithaWaitblock.
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
theotherdirection?
BUILDINGDISCOVERY#5:AUTOMATICHOUSE!LongbeforeyougottheLEGOMINDSTORMSNXT2.0roboticskit,youmighthavebuilthousesfromregularLEGObricks.Nowthatyouknowhowtoworkwithmotors,howtousesensors,andhowtomakeworkingprograms,howabouttryingtobuildarobotizedhousewiththeNXT?
IDEASUsemotorstoautomaticallyopenthedoorwhensomeonepressesthedoorbell(theTouchSensor),andsetanintruderalarmthatsoundswhentheUltrasonicSensorseessomeone.UseanothermotortocloseandopentheshutterswhenyouholdacoloredballinfrontoftheColorSensor.
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!
Figure8-1:TheShot-Roller
InadditiontobuildingtheShot-Roller,you’lllearnsomenewprogrammingtechniques.You’llalsogettousesomenewprogrammingblockssuchastheColorLampblockandtheMotorblock.
buildingtheshot-rollerNowthatyou’velearnedabitaboutShot-Roller’sfunctionality,you’rereadytobuildit.Todoso,followthedirectionsonthenextpages,butfirstselectthe
piecesyouneedasshowninFigure8-2.
Figure8-2:TherequiredpiecestobuildtheShot-Roller
connectingthecablesConnectthesensorsandmotorstotheNXTbrickaccordingtoTable8-1,makingsurethattheydonotinterferewiththewheels.OnewaytoaccomplishthatistowindthecablesaroundseveralLEGOpiecesontherobot.
Makesurethatyourrobotcanturnaroundsmoothlyandmovetheturretupanddowneasily,withouthavingthecablesblockingthesemovements.Checkthisbymovingtheturretandthewheelswithyourhands.
table8-1:cableplacementfortheshot-roller
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
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.
Let’screateaprogramthatturnsthesensorintoadiscolampthatquicklyflashesdifferentcolors.StartanewprogramcalledTestColorLamp,andplaceandconfigurefourblocksinitasshowninFigure8-4.
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),
themotorturnsmoreslowlywhenyoutrytostopitwithyourhandsbecausethepowertothemotorstaysconstant.However,whenyouusetheControlMotorPoweroption,theNXTwillautomaticallyapplymorepowertothemotorwhenthere’saloadonitsothatthemotorcontinuesturningataconstantspeed.YoucanseeaMotorblockwithitsConfigurationPanelinthefollowingsampleprogram.
ToillustratetheControlMotorPowersetting,you’llshoottwoballswiththeShot-Roller’sFiringMotor.Toshootaball,themotorhastomakeonefullrotation.You’lllaunchthefirstballwithaMotorblockspecifiedtocontrolthemotorpowerandwiththesecondonewithoutthepowercontrol,asshowninFigure8-5.
Whenyouruntheprogram,thefirstballshouldbereleasedathighspeedbecausethemotorpoweriscontrolled,whilethesecondballisstuckintheballmagazine:thereisnotenoughpowertopushitout.
Figure8-5:TheconfigurationoftheblocksintheMotorControlTestprogram
DISCOVERY#39:AMOTORBLOCKTASK!Difficulty:EasyBeforecreatingbigprogramsforarobot,itisgoodtotesttherobot’smechanicalfunctionstogiveyouabetterunderstandingofhowtheyworkandtomakeiteasiertolocalizeproblems.Forexample,ifrunningtheTurnmotordoesn’tmaketherobotturn,someLEGOpieceswereprobablymisalignedwhileconstructingtherobot.Createaprogramthatmakeseachmotoronthe
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.
Figure8-6:Step1:YoumaketheTurnmotormovebyactivatingmotorBwiththeDurationoptionsettoUnlimited.AstheShot-Rollerturnsright,aWaitblockmakestheUltrasonicSensorlookfortargetsinsight.Oncetherobotseesatargetcloserthan45cm(18inches),motorBisturnedoff,andtheturretisraisedbyspinningmotorAbackward.
NOTE Inadditiontothenewlyplacedprogrammingblocks,Figure8-7
alsoshowssomeoftheblocksplacedpreviously.Youdon’tneedtoconfiguretheseblocksagain;theyjusthelpyouseewheretoputthenewblock.Youmayalsoseesuchblocksfrompreviousstepsinotherfiguresinthisbook.
Figure8-7:Step2:TheWaitblockinstep1waiteduntilthesensorsawsomethingcloserthan45cm,butitcouldn’tdetermineexactlyhowcloseatargetwas.Tofindout,youuseaSwitchblock.Ifthedetectedobjectiscloser
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.
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
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.
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.
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!
Figure8-13:TwoTouchSensorsareusedtocontroltheShot-Rollerremotely.
Youcansolvethisproblemasfollows:ThefirsttimeyoupressaTouchSensor,thecontrolledmotormovesforwarduntilyoureleasethebutton.Then,whenyoupressthebuttonagain,themotormovesbackwarduntilyoureleasethebutton.Thenexttimeyoupressthebutton,themotorspinsforwardagain,andsoon.
BecauseyouwanttobeabletousetheTurretandTurnmotorssimultaneously,youplacetheblockstohandlethesemotorsontwoseparateSequenceBeamssothattheycanrunatthesametime.
CreatetheShot-Roller-RemoteprogramasshowninFigures8-14to8-20.
Figure8-14:Step1:WhenyoupresstheTouchSensoronport1,theTurnmotormovesforward,andtheShot-Rollerspinstotheright.Whenyoustoppressingthesensor,aMotorblockmakesthemotorstop.
Figure8-15:Step2:Theseblocksworkliketheonesplacedinstep1,exceptthattheymaketheTurnmotorspinbackward,causingtheShot-Rollertoturnleft.
Figure8-16:Step3:PlaceaLoopblockontheWorkArea,andthenselectalltheotherblocksanddragthemintotheloop.BecauseoftheLoopblock,theprogramwillrepeatedlywaitforbuttonpressesandthereforerepeatedlycontroltheTurnmotorbasedonthisinput.
Figure8-17:Step4:SelecttheLoopblockthatyouplacedinstep3,andthenpresstheCopybuttonandthenthePastebuttononthetoolbartoduplicatetheloopandtheblocksinit.Dragthenewlooptothepositionshowninthefigure,andthenconnectthenewblockstothemainprogramasshownhere.
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.
Figure8-19:Step5:PlaceandconfigureaLoopblockandtwoSwitchblocks
asshown,andthenconnecttheblockstothemainprogrambyconnectingtheSequenceBeams,asyoudidinstep4.BecausethisisthesecondParallelBeam,holdtheSHIFTkeywhilemakingtheconnection.
Figure8-20:Step6:PlaceandconfigurethreeMotorblocksasshown.TheseblocksarerunwhentheconditionofbothSwitchblocksistrue;inotherwords,whenbothTouchSensorsarepressed.TheTurnandTurretmotorsareturnedoff,andtheFiringmotorstartstofireballs.
Congratulations,youfinishedcreatingtheremote-controlprogram!DownloadtheprogramtotheShot-Roller,andhavefun!
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
MINDSTORMSsystem,anduseanNXTmotorto,forexample,releasetherubberbandorthespooninordertolaunchsomethingwhentherobotseesyou.Whenusingrubberbands,useonesotherthanthosefoundintheNXT2.0kit,oryou’lllikelybreakthem.
9
strider:thesix-leggedwalkingcreature
Youcanmakeinterestingmodelsthatmoveonwheels,butitisalsopossibletomakerobotsthatwalk.Suchcreationsareslightlymorechallengingtomake,butinthischapteryou’llfindinstructionstobuildStrider,asix-leggedwalkingcreature,asshowninFigure9-1.Onceyoufinishbuildingit,you’llprogramittowalkaroundandrespondtohumaninteraction.
Figure9-1:Strider
TheStriderrobotusesthreeidenticalmotorassembliestowalk,eachofwhichcontrolsonepairoflegs.Thelegmodulesareinterconnectedwithatriangle-shapedframe,whichalsocarriestheNXTwithseveralsensorsattached.TwoTouchSensorsontheStrideractlikeantennas,detectingtouchesfromobjectsorpeopleinStrider’senvironment(theyarenotusedasbumperstopreventtherobotfromwalkingintosomething).TheUltrasonicSensorallowsthewalkertomeasurethedistanceofnearbyobjects,whiletheColorSensorinLightSensormodecandetectwhetheritisdarkorlightoutside.
buildingstriderWe’llnowmoveontobuildingtherobotbyfollowingtheinstructionsonthesubsequentpages.Beforeyoustartbuilding,selectthepiecesyou’llneedtocompletetherobotasshowninFigure9-2.
Figure9-2:TherequiredpiecestobuildtheStrider
connectingthesensorcablesYouconnectedthemotorcablesonpages132and133.Table9-1andFigure9-3willshowyouhowtoconnectthesensors.Whenconnectingthecables,guidethemthroughthespaceundertheNXTsothattheydon’tstickout.
table9-1:thecableplacementforstrider
Frommotor/sensor
ToNXTbrickport
Cablelength
RightTouch Inputport1
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.
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.
Figure9-5:MotorsAandCpulltherobotforward(dashedarrows),andmotorBpushes(grayarrow).Asaresult,theStriderwalksforward(solidblackarrow).(Thesensorshavebeenremovedheretomakethemotorsmorevisible.)
Figure9-6:WhenNXTmotorsarespecifiedtoturnforward,thecorrespondinglegpairmovesintheblackdirection.Thegraydenotesbackwardmovementofthemotor.
NOTE TheStridercanonlywalkonareallysmoothsurface,suchastiles,adesk,orasmoothwoodenfloor.Ifyouputitoncarpetoraroughfloor,thelegswillprobablybreak!
programmingstriderNowthatyouunderstandthebasicsofmakingStriderwalk,you’llcreatethreeMyBlockstomakeitwalk.Followingthat,you’llusetheseblockstocreatelargerprograms.
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.
Figure9-7:TheconfigurationoftheblocksintheWalk-ForwardMyBlock
Figure9-8:AquicktestprogramtomaketheStriderwalkforward
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
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.
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
Blocksinsteps3,4,and5(Figures9-13,9-14,and9-15).
Figure9-13:Step3:HereyouaddtheblocksthatshouldberunwhentherightTouchSensorispressed.Whenthesensorispressed,abluelightshouldbeswitchedon,therobotshouldstopwalking,anditshouldsay“Right”anddisplay“Youpressedtherightsensor!”ontheNXTscreen.Next,theStriderrobotshouldwalktotherightbecauseoftheWalk-RightMyBlockthatyouplacedearlier.
Figure9-14:Step4:Theblocksyouplaceherearesimilartothoseinstep3,exceptthattheyarerunwhentheleftTouchSensorispressed.Consequently,theSoundandDisplayBlocksareconfiguredtotellthattherobotiswalkingtotheleft.
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.
creatingthescaredstriderprogramInthenextprogram,you’llhaveStriderwalkforwarduntilsomeoneturnsonalight,atwhichpointitwillshoutandimmediatelysitstilluntilthelightisswitchedoff.Butbeforeyoucreatethisprogram,youneedtolearntwonewprogrammingtricks:FeedbackBoxesandthresholds.
pollingsensorswithfeedbackboxesTheConfigurationPanelsofcertainblockscontainasectionwithafixedvaluecalledFeedbackBoxes.FeedbackBoxes(asshowninFigure9-16)displaysensorvalueswhentherobotisconnectedtothecomputer,eitherthroughUSBorthroughBluetooth.
Figure9-16:AFeedbackBoxreportssensorvalues.TheWaitBlockConfigurationPanelshownhereisconfiguredtopollthevalueoftheUltrasonicSensor.
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
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.
Figure9-18:UsingtheFeedbackBoxtopolltheLightSensorvalue
creatingtheprogramYou’llnowcreatetheprogramthathastheStriderrobotmoveforward,shoutwhenalightcomeson,andstopmovinguntilthelightturnsoff.Createanewprogram,storeitonyourcomputerasStrider-Scared,andfollowtheinstructionsshowninFigure9-20.
Figure9-20:AftermakingtheStridermoveforward,theprogramwaitsuntilthemeasuredlightintensityexceedsthethreshold(setto17here).Oncethethresholdisexceeded,allmotorsstop,andtherobotmakesaloudsound.Thelastblockwaitsuntilthesensorseesthatitisdarkagain,atwhichpointthelooprestartsandStriderstartswalkingagain.
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
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?
Figure9-21:Strideronthreewheels
PARTIII
creatingadvancedprograms
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
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.
Figure10-2:You’llusetheSmartBotrobottolearnmanynewprogrammingtechniques.I’llrefertothemotorwiththeColorSensorastheHandmotorandtheonewiththewheelastheWheelmotor.
Figure10-3:TherequiredpiecestobuildSmartBot
aprogramtogetstartedwithdatawires
Toseehowdatahubsanddatawireswork,you’llcreateasmallprogramthat
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.
Figure10-4:Step1:PlaceallthenecessaryblocksfortheSmart-IntroprogramontheWorkArea,andconfigurethemasshownhere.
Figure10-5:Step2:Opentheblocks’datahubsbyclickingthetabsatthelower-leftedgeoftheblock.YoushouldalreadyseeasmalldatahubjustbelowtheUltrasonicSensorblock,butyoucanopenthecompletedatahubbyclickingthesametab.
Figure10-6:Step3:Createandconnecttheyellowwireasshownhere.Theyellowlineisthedatawire.
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.
Figure10-7:AnoverviewoftheSmart-Introprogram.TheUltrasonicSensorblockpollsthesensorandsendsthesensorvaluethroughadatawiretotheMotorblock,whichusesthisvaluetosetthemotorspeed.
howdodatahubsanddatawireswork?
You’llnowanalyzesomeofthenewfeaturesthatyouusedintheprogramyoujustmade.Asyoucansee,youuseadatawiretocarryinformationbetweenblocks.Intheexampleprogram,theyellowdatawirecarriesthesensorvaluetotheMotorblocktosetthemotor’spowerlevel.
Youcreatedthedatawirebyfirstclickingoneofthedataplugsonthedata
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.
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.
Figure10-9:Step1:Placeandconfigurethetwoblocksasshownhere.NotethattheCountersettingischeckedintheLoopblock,whichopensalittleplugontheleftsideoftheLoopblock.
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,
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.
Figure10-12:AConfigurationblock’ssettingisignoredwhenadatawiredefinesthesamesetting;theblockwillusethedatawire’svalue.
deletingdatawiresTodeleteadatawire,followtheinstructionsshowninFigure10-13.
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.
Figure10-14:TheincompleteprogramforDiscovery#47.Canyoucompleteitbyconnectingadatawireappropriately?
DISCOVERY#48:DYNAMICSPEED!Difficulty:MediumTheSmart-IntroprogrampolledtheUltrasonicSensoronceandusedthesensorvaluetosetthespeedoftheHandmotor.Youcanmodifythisprogramsothatthemotorspeediscontinuouslyupdatedwithanewsensorreadingasfollows:1.RemovetheSoundblock.
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,
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).
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.
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
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.
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
TextblockinFigure10-18,whichalsoshowsyouhowtomaketheSmart-TextWireprogram.
Figure10-18:TheconfigurationsoftheblocksintheSmart-TextWireprogram.YoucanfindtheNumbertoTextblockbetweentheAdvancedprogrammingblocks.NoticethattheDisplayblock(e)isconfiguredtodisplaytheMindstormsNXTtextline.However,theprogramignoresthissetting,becauseyoualsouseaTextdatawiretospecifywhatshouldbedisplayed.
DISCOVERY#51:READTHESENSORREADINGS!Difficulty:HardExpandtheSmart-TextWireprogramtomakeitdisplaytheRotationSensor
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
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.
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
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).
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.
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
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.
Figure10-25:Hidingunuseddataplugswillmakeprogramsmorecompactandunderstandable.
usingdatawiresacrossyourprogramWhenconfiguringprogramswithdatawires,youdon’thavetoconnectablocktotheonerightnexttoit;youcanconnectblockswhenthereareotherblocksinbetween,asshowninFigure10-26.
Figure10-26:Datawiresallowyoutoconnectblocksspreadoveryourprogram,asshownhere.Theconnectedblocksdonothavetoberightnexttoeachother.
furtherexploration
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
eachtimeitsensessomeonepassingby.Now,whenyoudisplaytheloopcountontheNXTscreen,you’redisplayinghowmanypeoplehavewalkedby!Toensurethatyourprogramworksproperly,placeaSoundblockinsidetheloopsothatyou’llhearasoundeachtimesomeonepassesby.
BUILDINGDISCOVERY#10:APOLITESMARTBOT!Inthisdiscovery,you’llgivetheSmartBotahatthatitcantakeoffwhenitnoticesthatsomeoneispassingby.Todothis,you’llexpandtherobotdesignwithanextramotorwhichyou’llcontrolwithaMotorblock.Forthearmmechanism,lookattherobot’sHandmotor.Whenyoufinishcreatingthenewrobotdesign,createaprogramthatmakestherobotinteractwithpeoplebymakingittakeitshatoffandtalkifitseessomeone.CanyouturntheSmartBotintoapoliterobot?
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:
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.)
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.
Figure11-2:TheSmart-Soundprogram.InsteadoffillingintwonumbersintheMathblock’sConfigurationPanelasinthepreviousprogram,youfeedonevaluetotheblockwithadatawire.
DISCOVERY#57:MATHPRACTICE!Difficulty:MediumCreateaprogramthatcontinuouslydisplaystheLightSensorandUltrasonicSensorreadings,aswellasthesumofthetwo,ontheNXTscreen,asshowninFigure11-3.UseaMathblocktoaddthetworeadings,andaddaWaitblockconfiguredtowaitfor0.5seconds(intheLoopblock)sothatyou’llhaveenoughtimetoreadthedisplay.
Figure11-3:TheNXTscreeninDiscovery#57
therandomblockYouusetheRandomblocktogeneratearandomnumberforuseinyourprogram.Usetheblock’sConfigurationPaneltoselectarangefortherandomnumber,suchas35to47.TheRandomblockwilloutputtherandomvaluethroughaNumberdatawire,whichinthiscasewillbe35,47,orsomevaluewithinthisrange.
TheRandomblockisusefulwhenyouwantyourrobottodosomethingunexpected.Forexample,youcoulduseaRandomblocktomaketheSmartBot’sWheelmotorturnatarandommotorspeed,asshownintheSmart-RandomprograminFigure11-4.
Figure11-4:TheconfigurationoftheSmart-Randomprogram.TheRandomblockgeneratesarandomvaluebetween0and100,whichiscarriedtothePowerplugontheMotorblock,switchingonamotor.NexttheprogramwaitsuntilyoubumptheTouchSensor,atwhichpointtheloopreturnstothebeginning,andthemotorspeedchangestoanewrandomspeed.
DISCOVERY#58:RANDOMSOUND!
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
somethingfartherawaythan100cm.Ifeitherorbothconditionsdonotoccur,theColorLampisswitchedoff,becausetheLogicblock’soutputisfalse.Figure11-6showstheSmart-Logicprogram.
Figure11-5:TheSmart-Compareprogram.TheCompareblockinthisprogramcheckstoseewhethertheRandomblock’soutput(between0and100)islessthan50.Ifitis,theCompareblock’soutputvalueistrue,andtheWheelmotorontheSmartBotturnsforward.Ifnot,theoutputvalueisfalse,andthemotorturnsbackward.
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
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
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
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.
Figure11-8:Step1:Becausethecompleteprogramrepeatscontinuously,youplacealloftheprogrammingblocksinsideaLoopblock.TheotherblocksshownhereallowtherobottodisplaytherandomnumberontheNXTscreen.ThatsamerandomnumberisalsosenttoaCompareblock,whichcheckstoseewhetheritisgreaterthan40.
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.
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
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?
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
programs,butitcan’treallydomuch.Inthisdiscovery,you’llbuildaroboticclaw,attachittoyourhand,andusesensorsortheNXTbuttonstocontrolit.BesuretoaddtheUltrasonicSensorandprogramtherobotsothatthearmwillwarnyouwhenthesensorseesyouapproachawall.Usetheprogrammingtechniquesyoulearnedinthischaptertodisplayseveralsensorvaluesonthescreenortomakesoundsbasedonsensormeasurements.
NOTE YoumaywanttouseSmartBotinthenextchapter,butyoudon’thavetodoso.Ifyou’dliketoworkonBuildingDiscovery#11,taketheSmartBotapartifyoulike.
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
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.
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
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.
Figure12-3:TheconfigurationoftheblocksintheSmart-Variableprogram.TheWaitblockattheendoftheprogramgivesyoutimetoseethevalueontheNXTscreenbeforetheprogramends.
DISCOVERY#63:OLDVS.NEW!Difficulty:MediumYou’llcreateanotherprogramwithvariablesthatrepeatedlycomparesnewsensorreadingstothesensorvaluestoredinavariableatthebeginningoftheprogram.Ifthenewreadingishigher,therobotshouldsay“Yes”;otherwise,itshouldsay“No.”Figure12-4showspartoftheprogram.
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.
initializingvariablesWhenprogrammingwithvariables,it’simportanttoinitializethembygivingthemastartingvalue.YoudothisintheSmart-CountprograminFigure12-5bysettingthePressCountvalueto0atthebeginningoftheprogram.Initializingvariablesmakesaprogrammorereliablebymakingsurethateachtimeyouruntheprogram,itwillfunctionthesamewaybecauseitstartsatthesameplace.
Figure12-5:TheSmart-CountprogramcountsthenumberofTouchSensorpressesanddisplaysthetotalontheNXTscreen.
It’sagoodideatoinitializevariablesatthebeginningofaprogram,
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.
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.
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.
Figure12-7:TheSmart-Constantprogram.ThefirstCustomblock(blockb)isacustomconstant,whilethesecondone(blocke)isaconstantyoudefinedpreviously.
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
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
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.
Figure12-11:Theconfigurationoftheblocksplacedinstep2
step3:storingwhichbuttonispressedWhenyoupressabuttoninthepreviousstep,theLoopblockstopslooping,andtheprogramjumpstotheblocksyou’llplaceinthisstep.Becauseprogrammingblocksarerunsoquickly,thenextblockwillrunbeforeyoucanreleasethepressedbutton,soyou’llassumethatthebuttonisstillpressedastheprogramrunsthroughtheblocksinthisstep.Asaresult,you’llsimplyuseaSwitchblocktoseewhethertheLeftbuttonispressed.Ifso,yousettheButtonvariableto1,andyouwaituntilthebuttonisreleased.Iftheleftbuttonisnotpressed,youknowthattherightbuttonis,andyousettheButtonvariableto2andwaituntiltherightbuttonisreleased,asshowninFigure12-12.
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.
Figure12-13:Theconfigurationoftheblocksplacedinstep4
step5:adjustingthescoreIfButtonandPositionwereequal,theblocksintheupperpartoftheSwitchshowninstep4arerun.Inthisstep,you’llplacetheblocksthataddonetotheScorevariable.TheNXTwilltellyouthatyou’vemadethecorrectchoicebydisplayingaVsignonthescreenandbyplayingahighnote.Theblocksinthelowerpartoftheswitchsubtractthreefromthescore,displayanXsignonthescreen,andplayalownote.Figure12-14showshowtoconfiguretheblocks.
Figure12-14:Theconfigurationoftheblocksplacedinstep5
step6:displayingthecurrentscoreTheblocksinstep6displaythecurrentscoreandgiveyoutimetoseethescoreaswellastheVorXsignontheNXTscreenbeforetheprogramgoesbacktodisplayanewtarget.Figure12-15showstheblocksthatdisplaythescore.
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
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
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.
Figure12-17:AnexampleadditionprobleminNXTBrainTrainergame
BUILDINGDISCOVERY#12:WHACK-A-MOLE!TheSmart-GameprogramisjustoneexampleofagameyoucanplayontheNXT.ThisdiscoverychallengesyoutobuildaconstructionsimilartotheWhack-a-Molegame.UseNXTmotorstorandomlymakemolespopupoutofaframeofLEGOpieces,andthenusetheNXTbuttonsorTouchSensorstowhackthemolesdown.CreateyourownadvancedprogramforthismachinetoturnitintoarealWhack-a-Molegame.YoucanmaketheNXTdisplayhighscores,playsounds,orincreasethedifficultylevelastimepasses.
PARTIV
advancedrobotprojects
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.
Figure13-1:TheSnatchercanfindandpickupobjects.
thegrabbingmechanismFigure13-2showshowtheSnatchergrabsobjects.AstheNXTmotorspinsforward,asmallgear(indicatedwithanumber1)makesabiggergear(2)rotate
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.
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.
Figure13-3:OncetheSnatcherhasgrabbedanobject,itcanliftit.Hereisasimplifiedoverviewoftheliftingtechnique(top),withanillustrationofthe
actualrobot(bottom).
buildingthesnatcherNowthatyou’vegottenasenseofhowtheSnatcher’sgrabbermechanismworks,it’stimetobuildtherobottolearnhowitreallyworks.Todoso,followthedirectionsonthenextpages,butfirstselectthepiecesyou’llneed,asshowninFigure13-4.
Figure13-4:TherequiredpiecestobuildtheSnatcher
creatingobjects
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,
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
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
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.
Figure13-10:TheseblockspreparetheSnatchertofindobjects:therobotturnsleft,initializesthevariables,resetstherotationsensorinmotorC,andstartsturningright.
Figure13-11:Theseblockstakecareofsearchingforobjects,asdiscussedinFigure13-10.
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.
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.
Figure13-15:Thenextstepistograbtheobjects.Tomakesurethattheobjectremainspositionedbetweentherobot’sfingers,theSnatchermovesforwardasitgrabs.Nextitidentifiestheobject’scoloranddropsitelsewhere.
troubleshootingthesnatcherIftheSnatcher’sprogramisn’tfunctioningproperly,carefullyreconfiguretheblocksordownload(andexamine)afunctioningprogramfromthecompanionwebsite.
IfthegrabberarmontheSnatcherdoesn’tseemtoworkproperly,youmayhaveconnectedsomeLEGOpartstootightly.TryremovingthesmallgraypartasshowninFigure13-16tofreeupsomespacearoundthedarkgraybeamthatconnectstotheaxle.
Figure13-16:RemovethepartshownhereandthenfreeupspacearoundthehighlighteddarkgraybeamiftheSnatcher’sgrabberjamswhiletryingtograbsomething.
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
edge?Howdoyoubuildarobotsothatitwillneverfalloffthetable?Formorefun,buildasweepermodulewiththethirdNXTmotortowipeanyLEGOpartoffthetable!
14
hybridbricksorter:sortbricksbycolorandsize
TheLEGOMINDSTORMSNXT2.0roboticskitcomeswithinstructionstobuildarobotthatsortsthecoloredballsintheset.Thischaptergoesabitfurtherbyshowingyouhowtobuildandprogramasorterthatsortsbybothcolorandsize.TheHybridBrickSorterrobotseparatesregularLEGObricks(2-by-4studs)fromsmallerbricks(2-by-2studs)andalsoseparatesred,yellow,green,andbluebricks,asshowninFigure14-1.Itdropseachtypeofbrickintodifferentbucketsorsimplyontodifferentplacesonthegroundasshowninthefigure.
Figure14-1:TheHybridBrickSortersortsLEGObricksbycolorandsize.
understandingthesortingtechnique
TheBrickSorterconsistsoftwomodules,asshowninFigure14-1:theScanningmodule,whichidentifiesthesizeandcolorofeachbrick,andtheDrivingmodule,whichmovestherobottowardtheappropriatebuckettodropthebrick.
thedrivingmoduleTheDrivingmodulenavigatestherobottodifferentbucketsbeforeitdropsthebricksbyturningtheDrivingmotorasshowninFigure14-2.Themotor’sRotationSensortellstheNXTwheretherobotispositioned.
Figure14-2:TheDrivingmotorallowstherobottomovebackandforthinastraightlinebetweendifferentbuckets.Thearrowsshowwhathappenswhenthemotorturnsforward.
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
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.
Figure14-5:TherequiredpiecesfortheHybridBrickSorter
connectingthecablesHavingbuiltthesortingmachine,it’stimetoconnectthecables,asshowninTable14-1.MakesurenottoconnecttheColorSensorcabletootightly,oritwillmaketheColorSensorinterferewiththesorterwheel.
table14-1:cableplacementforthehybridbricksorter
From ToNXTbrick Cablelength
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
programmingthehybridbricksorter
You’llnowprogramyourmachinetosortLEGObricks.Figure14-7showsanoverviewofthecompleteHybridBrickSorterprogram.
Figure14-7:AnoverviewoftheprogramfortheHybridBrickSorter
NoticethatthisoverviewisanexpandedversionoftheoneinFigure14-4.InadditiontoidentifyingthesizeofaLEGObrick,thisprogramalsocheckstoseewhetherthereareanybrickslefttosort.Ifthesorterwheelhasturned46degreestwiceandifthesensorstilldoesn’tseeabrick,therearenobrickslefttosort,orthere’sbeenanerror(thatis,abrickgotstuck).Inthiscase,thesorter
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
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
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.
Figure14-11:Theconfigurationofboththeblocksthatcheckwhetherabrickisavailabletobesortedandtheblocksthatrunwhenthereisn’tabricklefttosort
step3:calculatingthepositionofabucketNowyou’llconfiguretheblocksthatrunwhentheColorSensorseesabrick.Figure14-1(page237)showshowthebricksendupifyourunthisprogram.Noticethatthesorterdropssmallbrickstotherightandbigbrickstotheleftofthestartingposition(inbetweenthebigandsmallbluebricks).
Forexample,whensortinglargegreenbricks,thedrivingmotormovesforwardacertainnumberofdegreestoreachtheappropriatebucket.Itmovesthesamenumberofdegreeswhensortingsmallgreenbricks,butintheoppositedirection.TheprogrammingblocksinthisstepcalculatethisnumberofdegreesbasedonthedetectedcolorandstoresthatnumberintheBucketvariable.ConfiguretheblocksinthisstepasshowninFigure14-12.
Figure14-12:Theconfigurationoftheblocksthatfindtherightbucketpositionbasedonthedetectedcolor
step4:droppingabrickintherightbucketOnceyouknowhowmanydegreesyouneedtomoveinordertoreachtherightbucket,youusethisnumbertogetherwiththevalueintheBricksizevariable.YoutransferthevalueinBricksizetoaSwitchblockspecifiedtoruntheblocksintheupperpartoftheswitchwhentheBricksizevariableistrue(asmallbrick)andspecifiedtoruntheblocksinthelowerpartoftheswitchwhenthevalueisfalse(abigbrick).
Theblocksintheswitchmaketherobotdrivetowardthebucket(basedonthevalueintheBucketvariable),dropthebrick,andthenreturntothestartingposition.YouuseaWaitblockinthelooptopausetheprogrambrieflyeachtimeitsortsabrick.ConfiguretheblocksinthisstepasshowninFigure14-13.
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.
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.
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.
Figure15-1:TheCompactChimneyClimbermovesverticallybetweentwosolidobjects,suchasabookcaseandawall.
understandingtheclimbingtechnique
TheCCCconsistsoftwoarmsthatextendtotouchthewallsitwillclimbsothattherobotcanmoveupanddownbyturningthewheelsonitsarms(seeFigure15-1).Thisclimbingtechniqueisn’tverycomplicatedanditworksfairlywell,butasimplerobotwiththistechniquewilleventuallylosecontactwiththewallandfalldown.Topreventtherobotfromcrashingtotheground,you’llneedtokeepitbalancedasitmoves,onboththex-andy-axes,asshowninFigure15-2.
stayingbalancedonthex-axisTheCCCrobotbalancesonthex-axisautomaticallybydesign.Themainweightoftherobot,theNXTwithitsbatteries,ispositionedbelowtheaxis,causingtherobottobehaveliketheswingshowninFigure15-3.Ifyouweretotrytoturntheaxisinthisfigurewithyourhands,you’dnoticethatgravitytriestostopyou.Somethingsimilarhappenswhentheclimbertriestorotatealongthex-axis:Gravitykeepsitupright.
Figure15-2:Tobeabletoclimb,theCCChastobalanceontwoaxes.(Onlyonewallisshownhereforbettervisibility.)Ifbalanceisn’tmaintained,therobotwilleventuallytiltinoneofthedirectionsindicatedbythegrayarrowsandlosecontactwiththewalls.
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
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.
Figure15-5:RequiredpiecesfortheCompactChimneyClimber
preparingachimneyBeforeprogrammingthisrobot,you’llneedtofindanappropriate“chimney”fortherobottoclimb,suchasthecrevassemadebetweenawallandthesideofabookcase,asshowninFigure15-6.Whateveryourchoice,yourchimney’s
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!
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.
Figure15-7:TheconfigurationoftheblocksthatswitchontheWheelmotorsandextendthearms
Figure15-8:Anoverviewofthecontroltechniqueusedtokeeptherobotbalanced.Ifthesensorreadswhite,therobotiscorrectlybalanced,sononeoftheWheelmotorsshouldbestopped.
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
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!
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
“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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
wires.SeedatawiresWorkArea
displayingSwitchblockson,64
moving,29
placingblocksin,26
XXOroperation,outputvaluefor,176
YYes/Nooutputplug,controlling,159
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.
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.
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
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
Whenyoucreateaprogramwithincorrectlywireddatawires,yourprogramwon’ttransfertotheNXT.Dependingonthetypeofmistakeinyourprogram,you’llseeoneofthefollowingerrormessages.*Thereisadatawirethatisconnectedtoaplugofthewrongtype(see“TheBrokenDataWire”onpage166).
*Thereismorethanonedatawireconnectedtothesameinputplug(see“ConnectingMultipleWirestoOneDataPlug”onpage167).
FigureA-3:Asampleerrormessagethatmayappearwhendownloadingaprogramtoarobot
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
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.
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
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
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
TheLEGO®TechnicIdeaBook:SimpleMachines
byYOSHIHITOISOGAWA
OCTOBER2010,168PP.,$19.95
ISBN978-1-59327-277-7fullcolor
TheUnofficialLEGO®TechnicBuilder’sGuide
byPAWEŁ“SARIEL”KMIEC
NOVEMBER2012,352PP.,$29.95
ISBN978-1-59327-434-4fullcolor
TheCultofLEGO®
byJOHNBAICHTALandJOEMENO
NOVEMBER2011,304PP.,$39.95
ISBN978-1-59327-391-0fullcolor,hardcover
TheUnofficialLEGO®Builder’sGuide,2ndEdition
byALLANBEDFORD
NOVEMBER2012,240PP.,$24.95
ISBN978-1-59327-441-2fullcolor
TheLEGO®AdventureBook,Vol.1:Cars,Castles,Dinosaurs&More!
byMEGANROTHROCK
NOVEMBER2012,200PP.,$24.95
ISBN978-1-59327-442-9fullcolor,hardcover
PHONE:800.420.7240OR415.863.9900
EMAIL:[email protected]
WEB:WWW.NOSTARCH.COM
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
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
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.