adventures in arduino by becky stewart
DESCRIPTION
Adventures in Arduino by Becky StewartTRANSCRIPT
Thiseditionfirstpublished2015
©2015JohnWileyandSons,Ltd.
Registeredoffice
JohnWiley&SonsLtd,TheAtrium,SouthernGate,Chichester,WestSussex,PO198SQ,UnitedKingdom
Fordetailsofourglobaleditorialoffices,forcustomerservicesandforinformationabouthowtoapplyforpermissiontoreusethecopyrightmaterialinthisbookpleaseseeourwebsiteatwww.wiley.com.
TherightoftheauthortobeidentifiedastheauthorofthisworkhasbeenassertedinaccordancewiththeCopyright,DesignsandPatentsAct1988.
Allrightsreserved.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inanyformorbyanymeans,electronic,mechanical,photocopying,recordingorotherwise,exceptaspermittedbytheUKCopyright,DesignsandPatentsAct1988,withoutthepriorpermissionofthepublisher.
Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprintmaynotbeavailableinelectronicbooks.
Designationsusedbycompaniestodistinguishtheirproductsareoftenclaimedastrademarks.Allbrandnamesandproductnamesusedinthisbookaretradenames,servicemarks,trademarksorregisteredtrademarksoftheirrespectiveowners.Thepublisherisnotassociatedwithanyproductorvendormentionedinthisbook.Thispublicationisdesignedtoprovideaccurateandauthoritativeinformationinregardtothesubjectmattercovered.Itissoldontheunderstandingthatthepublisherisnotengagedinrenderingprofessionalservices.Ifprofessionaladviceorotherexpertassistanceisrequired,theservicesofacompetentprofessionalshouldbesought.
Trademarks:WileyandtheWileylogoaretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliatesintheUnitedStatesand/orothercountries,andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheirrespectiveowners.JohnWiley&Sons,Ltd.isnotassociatedwithanyproductorvendormentionedinthebook.
AcataloguerecordforthisbookisavailablefromtheBritishLibrary.
ISBN978-1-118-94847-7(paperback);ISBN978-1-118-94846-0(ePub);978-1-118-94845-3(ePDF)
Toeverystudentevertoldtheyhadtochoosebetweentheartsandsciences.
AbouttheAuthorBECKYSTEWARTisanengineerandeducator.Sheworkswithartistsanddesignerstobringtolifeoftencrazyideas—fromshoesthatshowyouhowtogethometosuspensionbridgesthatcanbeplayedlikegiantharps.AftercompletingaPhDinElectronicEngineeringatQueenMaryUniversityofLondon,BeckyhelpedfoundCodasign,aneducationcompanythatcreatestechnologyworkshopsforartgalleriesandmuseums.AtCodasignsheteachesartistsanddesignershowtouseelectronicsandcodeascreativetools.Shedocumentsherprojectsathttp://theleadingzero.com.
AcknowledgmentsMyfirstthanksgotoAlexandraDeschamps-Sonsino,withoutwhomIwouldhaveneverstartedthisbook.IalsooffermysinceregratitudetoAlexforherworkwithTinkerthatjumpstartedtheArduinocommunityinLondon.
NoneofthiswouldhavebeenpossiblewithoutthesupportoftheamazingeducatorsthatformCodasign.IhavelearnedmuchfromMelissaColemanandPollieBardenabouthowtoimprovemyArduinoteaching,andIamconstantlylearningfromAdamStarkabouthowtobetterteachprogrammingconcepts.Ican’tstopthankingEmilieGiles—Codasignwouldgrindtoahaltwithoutyou;thankyouforeverythingyoudo.Igiveaparticularlyhugethank-youtoLiatWassershtromforallyourfeedbackandexpertise.
I’dliketoalsothanktheartisticandeditorialstaffthathelpedshapethisbook.Ithasbeengreatlyimprovedbyyourguidance.
Lastly,thankyoutomyfamilywhohavesupportedmeineverythingIdo.Thankyoutomyparents,whoprovidedaquietplacetositandwrite,andtoBen,whohaspatientlytoleratedourweddingplanningandvacationsbeingpunctuatedbywriting.
Publisher’sAcknowledgementsSomeofthepeoplewhohelpedbringthisbooktomarketincludethefollowing:
Editorial
SeriesCreator:CarrieAnnePhilbin
VPConsumerandTechnologyPublishingDirector:MichelleLeet
AssociateDirector—BookContentManagement:MartinTribe
ProfessionalTechnology&StrategyDirector:BarryPruett
AcquisitionsEditor:AaronBlack
ProjectEditor:CharlotteKughen
CopyEditor:GraceFairley
TechnicalEditor:RussellBarnes
EditorialManager:MaryBethWakefield
EditorialAssistant:JessiePhelps
Marketing
MarketingManager:LornaMein
MarketingAssistant:PollyThomas
AdventuresinArduino®
Contents
CoverTitlePageAbouttheAuthorIntroduction
WhatIsanArduino?WhatYouWillLearnPartsYouWillNeedToolsYouWillNeedSoftwareYouWillNeedOtherUsefulMaterialsWhatIAssumeYouAlreadyKnowHowThisBookIsOrganisedConventionsTheCompanionWebsiteReachingOut
Adventure1:SettingUpYourArduinoWhatYouNeedDownloadingandInstallingtheArduinoSoftwareonYourComputerUsingBlinktoTestThatEverythingIsSetUpCorrectlyBuildinganLEDCircuitFurtherAdventureswithArduino
Adventure2:ReadingfromSensorsWhatYouNeedAddingMoreLEDsPrintingMessagestotheComputerReadingDatafromaPotentiometerMakingDecisionsinCodeBuildingaStatusMessageSignFurtherAdventureswithArduino
Adventure3:WorkingwithServosWhatYouNeed
UnderstandingDifferentTypesofMotorsControllingaServowithArduinoRepeatingtheSameThingOverandOverDigitalInputwithaPushButtonBuildingaCombinationSafeFurtherAdventureswithArduino
Adventure4:UsingShiftRegistersWhatYouNeedOrganisingYourCodeGettingMoreOutputswithShiftRegistersBuildingYourNameinLightsFurtherAdventureswithShiftRegisters
Adventure5:PlayingSoundsWhatYouNeedMakingaListMakingNoiseBuildinganAugmentedWindChimeFurtherAdventureswithSound
Adventure6:AddingLibrariesWhatYouNeedAnalogueOutCapacitiveSensingBuildingaCrystalBallFurtherAdventureswithLibraries
Adventure7:WorkingwiththeArduinoLeonardoWhatYouNeedIntroducingtheArduinoLeonardoSensingLightBuildingaGameControllerFurtherAdventureswiththeLeonardo
Adventure8:WorkingwiththeLilypadArduinoUSBWhatYouNeedIntroducingtheLilypadArduinoUSBGettingCleverwithArraysPassingDataBetweenFunctionsBuildingaPOVHoodie
FurtherAdventureswiththeLilypadAdventure9:TheBigAdventure:BuildingaMarbleMazeGame
WhatYouNeedPartOne:ScoringPointsPartTwo:DesigningYourMazeGamePartThree:WritingtheCodePartFour:BuildingtheMazeGameFurtherAdventures:ContinuingYourAdventureswithArduino
AdventureA:WheretoGoFromHereMoreBoards,Shields,SensorsandActuatorsOntheWebBooks
AdventureB:WheretoGetToolsandComponentsStarterKitsBrick-and-MortarStoresOnlineStores
GlossaryEndUserLicenseAgreement
ListofIllustrations
IntroductionFIGUREI-1ArduinoUno(topleft),ArduinoLeonardo(bottomleft)andLilypadArduinoUSB(right)FIGUREI-2AUSBandUSBMicrocableFIGUREI-3BreadboardsindifferentsizesandcoloursFIGUREI-4JumperwiresFIGUREI-5DifferenttypesofLED,withacolour-changingLEDontherightandbelowitaLilypadLEDFIGUREI-6Resistorsneededfortheprojectsinthisbook:100Ω(topleft),220Ω(topright),10kΩ(bottomleft),1MΩ(bottommiddle)and10MΩ(bottomright)FIGUREI-7ThreedifferenttypesofpotentiometerFIGUREI-8AservomotorFIGUREI-9Atactilepushbutton(left)andthreedifferentpanelmountbuttons(right)FIGUREI-10AshiftregisterFIGUREI-11ApiezoFIGUREI-12Alight-dependentresistorFIGUREI-13MaleheaderpinsFIGUREI-14Solidcorewire(left)andstrandedwire(right)FIGUREI-15Enamelled(left)andplasticcoated(right)wireFIGUREI-16SolderonspoolsFIGUREI-17A9Vbattery-to-DC-barrelconnector(left)andaUKplugforaUSBcable(right)FIGUREI-18AlligatorclipsFIGUREI-19ConductivethreadFIGUREI-20AsolderingironFIGUREI-21DifferentkindsofwirestripperFIGUREI-22WirecuttersFIGUREI-23PairsofpliersFIGUREI-24AmultimeterFIGUREI-25Apairofscissorsandautilityknife
Chapter1FIGURE1-1AnArduinoUnoandUSBcableFIGURE1-2YoucandownloadtheArduinoIDEforyourcomputerfromthe
Arduinowebsite.FIGURE1-3PlugtheUSBcableintotheArduinoUnoandthenconnectittoyourcomputer.FIGURE1-4TheArduinoprogramiconFIGURE1-5TheimportantpartsoftheArduinoIDEFIGURE1-6Thebuilt-inLEDontheArduinoboardisnearthenumber13.FIGURE1-7OpeningtheBlinksketch,whichislocatedintheexamplesthatareincludedwiththeArduinoIDEFIGURE1-8SelectingtheboardyouareusingFIGURE1-9SelectingtheportyourArduinoboardispluggedintoFIGURE1-10MessageintheArduinoIDEaftersuccessfullyuploadingyourcodeFIGURE1-11Acommonerrorwhenthecomputercan’ttalkwiththeArduinoFIGURE1-12TheelectroniccomponentsyouneedtobuildthecircuitFIGURE1-13ThecircuitschematicfortheLEDcircuitFIGURE1-14Abreadboardhasaseriesofholesthatareconnectedinrowswithtwopairsoflongrowsontheoutsideandshorter,perpendicularrowsinthecentreoftheboard.FIGURE1-15BasiclayoutofabreadboardFIGURE1-16TheLEDcircuitonthebreadboardFIGURE1-17ThedigitalpinsontheArduinoboard.DigitalPins0and1arespecialpinsthatyoulearnaboutlater.
Chapter2FIGURE2-1TheelectroniccomponentsyouneedforthefirstpartofthisadventureFIGURE2-2BuildingacircuittocontrolthreeLEDsFIGURE2-3TheSerialMonitorbuttonFIGURE2-4TheSerialMonitorintheArduinoIDEFIGURE2-5DifferentpotentiometersFIGURE2-6AnaloguepinsontheArduinoUnoFIGURE2-7CircuitforconnectingapotentiometerFIGURE2-8AstatusmessagesignFIGURE2-9TheelectroniccomponentsyouneedtomakeastatusmessagesignFIGURE2-10CircuitschematicforthesignFIGURE2-11PrototypecircuitonthebreadboardforthesignFIGURE2-12CuttingholesfortheLEDsandknobFIGURE2-13TheLEDportionofthecircuit
FIGURE2-14SolderedpotentiometerFIGURE2-15PowersupplythatyoucanusewithanArduinoboardFIGURE2-16Completedstatusmessagesign
Chapter3FIGURE3-1TheelectroniccomponentsyouneedforthefirstpartofChapter3FIGURE3-2AservomotorandtoyDCmotorFIGURE3-3OpeningtheSweepexamplesketchFIGURE3-4CircuittoconnectaservototheArduinoboardFIGURE3-5HowatactilepushbuttonworksFIGURE3-6CircuitwithatactilepushbuttonFIGURE3-7Circuitwithapull-upresistorFIGURE3-8Circuitwithapushbuttonandinternalpull-upresistorontheArduinoboardFIGURE3-9CombinationsafeFIGURE3-10TheelectroniccomponentsyouneedtobuildyourcombinationsafeFIGURE3-11CircuitschematicforthecombinationsafeFIGURE3-12CircuitforthecombinationsafeFIGURE3-13Ifthelidisnotalreadyattachedtoyourbox,addapaperhinge.FIGURE3-14Extendtheservo’sarmbyattachinganobjectlikeapapercliporbambooskewer.FIGURE3-15PaperloopsotheservocanclosethesafeFIGURE3-16SolderedcomponentsFIGURE3-17Completedcombinationsafe
Chapter4FIGURE4-1WhatyouneedforthefirstpartofthisadventureFIGURE4-2TheanatomyofafunctionFIGURE4-3TheanatomyofaforloopFIGURE4-4TheCLOCKsignalFIGURE4-5HowashiftregisterworksFIGURE4-6Pin-outdiagramfortheshiftregisterFIGURE4-7FirstconnectionsfortheshiftregisterFIGURE4-8ThefullcircuitfortheshiftregisterFIGURE4-9HowtoconvertfromabinarynumbertoadecimalnumberFIGURE4-10Howwouldthisbinarypatternberepresentedbyadecimalnumber?FIGURE4-11Addingasecondshiftregister
FIGURE4-12Yourname(oranyotherword)inlights!FIGURE4-13TheelectroniccomponentsyouneedtobuildyournameinlightsFIGURE4-14CircuitschematicforthreeshiftregistersFIGURE4-16CardboardletterswithholesforLEDsFIGURE4-17SolderedLEDsandresistorsFIGURE4-18Backoflights
Chapter5FIGURE5-1TheelectroniccomponentsyouneedforthefirstpartofthisadventureFIGURE5-2TwoexamplearraysFIGURE5-3ThecircuitforanarrayofLEDsFIGURE5-4HowsoundismadeFIGURE5-5ThecircuitforausingapiezoasaspeakerFIGURE5-6AnaugmentedwindchimeFIGURE5-7TheelectroniccomponentsyouneedtomakethewindchimeFIGURE5-8CircuitschematicfortheaugmentedwindchimeFIGURE5-9BreadboardprototypecircuitFIGURE5-10ConductivitytestFIGURE5-11AchimeFigure5-12AchimeattachedtothebaseFIGURE5-13Topofbase
Chapter6FIGURE6-1TheelectroniccomponentsyouneedforthefirstpartofthisadventureFIGURE6-2AnalogueanddigitalsignalsFIGURE6-3ThepinsthatsupportanalogWrite()FIGURE6-4LEDcircuitforfadinganLEDFIGURE6-5PulsewidthmodulationexamplesFIGURE6-6RGBLEDsFIGURE6-7CircuitconnectinganRGBLEDtoanArduinoboardFIGURE6-8MixinglightversusmixingpaintFIGURE6-9PlacethedownloadedandunzippedfolderinthelibrariesfolderoftheArduinosketchbook.FIGURE6-10Checkforthelibraryandexampleinthemenus.FIGURE6-11CapacitivesensingcircuitFIGURE6-12Atouch-sensitivecrystalballFIGURE6-13Theelectroniccomponentsyouneedtomakethecrystalball
FIGURE6-14CircuitschematicforthecrystalballFIGURE6-15BreadboardprototypecircuitFIGURE6-16MappingavaluetoanewrangeFIGURE6-17PapiermachécrystalballFIGURE6-18Aluminiumfoil–coveredbaseFIGURE6-19SolderedLEDcircuitFIGURE6-20SolderedsensorcircuitFIGURE6-21Completedcrystalballcircuit
Chapter7FIGURE7-1TheelectroniccomponentsyouneedforthefirstpartofthisadventureFIGURE7-2SelectingtheArduinoLeonardofromTools⇒BoardintheArduinoIDEFIGURE7-3USBconnectorsFIGURE7-4TheLeonardotypinginawordprocessingprogramFIGURE7-5AnalogueanddigitalsignalsFIGURE7-6Ohm’sLawdefineshowvoltage,currentandresistancearerelated.FIGURE7-7Twovoltagedividercircuits,onewithanLDRasthetopresistanceandtheotherwithanLDRasthebottomresistanceFIGURE7-8TheequationtocalculatehowdifferentresistorvaluesinavoltagedividerchangetheoutputvoltageFIGURE7-9ArduinoLeonardogamecontrollerFIGURE7-10TheelectroniccomponentsyouneedtomakethegamecontrollerFIGURE7-11CircuitschematicforthegamecontrollerFIGURE7-12ThegamecontrollercircuitFIGURE7-13Coverwithoutanycircuitry
Chapter8FIGURE8-1TheelectroniccomponentsyouneedforthefirstpartofthisadventureFIGURE8-2TheLilypadArduinoUSBFIGURE8-3AnFTDIprogrammingboard,whichyouneedifyouareusingatypeofLilypadArduinootherthanaLilypadArduinoUSBFIGURE8-4TheArduinoLilypadArduinoUSBONswitchFIGURE8-5SelectLilypadArduinoUSBfromthelistofboardsFIGURE8-6Insteadofjumperwirestoconnectcomponents,usealligatorclipswhenprototypingsoftcircuits.FIGURE8-7LilypadLEDsaresewableLEDsthatalreadyhavecurrent-limitingresistors.
FIGURE8-8Alistofintegers,alsocalledaone-dimensionalarrayFIGURE8-9Atwo-dimensionalarrayofintegersstoredinrowsandcolumnsFIGURE8-10CircuitforanarrayofLEDsFIGURE8-11Iteratingoverframesofananimationstoredinatwo-dimensionalarrayFIGURE8-12Persistence-of-visionhoodieFIGURE8-13TheelectroniccomponentsyouneedforthePOVhoodieFIGURE8-14CircuitschematicforthePOVhoodieFIGURE8-15PrototypingthecircuitwithalligatorclipsFIGURE8-16Persistenceofvisionmessagecapturedwithalong-exposurephotographFIGURE8-17BendingthelegsofcomponentstomakethemsewableFIGURE8-18FirstconnectionsforsewingtheLilypadcircuitFIGURE8-19ContinuingtosewtheLEDsintothecircuitFIGURE8-20ThesewnPOVcircuit
Chapter9FIGURE9-1AcompletedbigadventuremarblemazegameFIGURE9-2TheelectroniccomponentsyouneedtobuildyourmazegameFIGURE9-3CircuittouseapiezoasasensorFIGURE9-4CircuitforfivepiezosassensorsandonepiezoasaspeakerFIGURE9-5GuidelinesfordesigningyourmazeFIGURE9-6HowthecodeworkswhenagameisplayedFIGURE9-7CircuitschematicofthemazegameFIGURE9-8MazegameprototypecircuitonabreadboardFIGURE9-9Howaloop()worksFIGURE9-0Gluestripsofcardtoguidethemarbleafteritdropsthroughahole.FIGURE9-1LidofthemazegamefittedtobottomFIGURE9-3WiringlayoutforpiezosFIGURE9-4SolderthenegativelegsoftheLEDsandonecontactofthebuttontogether.
IntroductionAREYOUANadventurer?Doyouboldlyembarkonnewendeavours,tacklingnewskillsandmasteringnewtools?Doyouwanttolearnhowtousetechnologytomakeyourideasburstintolife?Areyoucuriousabouthowyoucancombinecomputercodeandelectricalcircuitswithscissorsandpaper—orevenneedleandthread?Iftheanswerisanemphatic“yes”thenthisisthebookforyou!
WhatIsanArduino?TheArduinoisatoolforbuildingcomputersthatcaninteractwiththephysicalworldaroundyou.Youcanuseittoconnectsensorsthatdetectsound,lightorvibration,thenturnonalight,changeitscolour,moveamotorandmuchmore.TheArduinoisthemagicaldevicethatsitsinthemidstofallofthesethings.Itreadsinfromsensorsmeasuringtherealworld,makesdecisionsbasedonthatdataandthenmakessomethinghappenintherealworld,whetherlight,soundormovement.
TheArduinoisusuallyablueboardaboutthesizeofyourhand.Ithaswhitewritingonitlabellingitsdifferentsectionsandhasallitschipsandcircuitsexposed.TherearedifferenttypesofArduinoboards,andtheyaren’tallblue,butyouwilllearnmoreaboutthatlaterinthe“PartsYouWillNeed”sectionandalsoinAdventures7and8.
TheArduinoisamicrocontroller.Amicrocontrollerisasimplecomputer.Itcan’tdomanythingsatthesametimebutitdoeswhatitistoldtodoreallywell.Youalreadyinteractwithlotsofmicrocontrollerseverydaybecausetheycontrolthingslikemicrowavesandwashingmachines.
Therearealotofdifferenttypesofmicrocontroller,butthespecialthingaboutArduinoisthatitisdesignedforpeoplewhoarejuststartingout.So,ifyouarenewtocodeorelectronics,that’sokaybecausetheArduinoisgreatforbeginners.Butdon’tunderestimateit—itcanstilltakeonbigprojects.
WhatYouWillLearnAftercompletingtheseadventures,youwillhavelearnedhowtosetuptheArduinoprogrammingenvironmentonyourcomputerandhowtowriteanduploadcodetoyourArduinoboard.YouwillfindouthowtoworkwiththreedifferentArduinoboards:theUno,LeonardoandtheLilypadUSB.
YouwilllearnbasicprogrammingconceptsthatyoucanusebeyondworkingwiththeArduino.TheArduinolanguageisbasedontheC/C++language.ThismeansthatasyoulearnhowtocodeArduinos,youarealsolearningabouthowprogrammingworksoncomputerslikealaptoporaRaspberryPi.
Alongsideprogramming,youwillbeintroducedtocircuitsandelectronics.Youwilllearnhowtousesensorstodetectreal-worldsignalslikelightormovement,andyouwilllearnhowtogenerateactionsintherealworld,suchasplayingasoundorturningonalight.
Bytheendofthisbook,youwillhaveabroadunderstandingofwhatyoucandowithanArduinoandbereadytostartdesigningandbuildingprojectideasofyourown!
PartsYouWillNeedIt’sbecomingeasiertobuyArduinoboardsinstores.PopularretailchainslikeMaplinintheUKnowstockArduinos.Bothofthosestoresalsoselltheelectroniccomponentsthatyouneedfortheprojectsinthisbook.Ifit’snotconvenientforyoutogettoastoretherearealsomanyonlineretailerstochoosefrom,andsomeofthesearelistedinAppendixB.
Thissectionexplainsallthepartsyouneedtomakealltheprojectsinthisbook.Manyoftheprojectsusethesamecoreparts.
Ofcourse,themostimportantthingyouneedisanArduinoboard.TherearemanydifferentkindsofArduinoboards,buttheArduinoUnoisthemostcommononeandtheoneyouusethemostinthisbook.YoualsoneedanArduinoLeonardoforAdventure7andaLilypadArduinoUSBforAdventure8.AllthreeboardsareshowninFigureI-1.
FIGUREI-1ArduinoUno(topleft),ArduinoLeonardo(bottomleft)andLilypadArduinoUSB(right)
YouwillneedaUSBcabletoconnectyourArduinoboardtoyourcomputer.FortheArduinoUnoyouneeda“normal”USBcable,butfortheArduinoLeonardoandLilypadArduinoUSByouneedaUSBMicrocable.BotharepicturedinFigureI-2.
FIGUREI-2AUSBandUSBMicrocable
Youusebreadboardstobuildcircuits.Breadboardsletyouconnectcomponentseasilywithouthavingtousesolder.Theycomeindifferentcoloursandsizes.Thelargeronesareusefulformorecomplicatedprojectswithlotsofparts,whereasthesmalleronesaregoodforprojectsthatyouwanttofitinsideasmallspace.TwodifferentsizesofbreadboardsmadefromtwodifferenttypesofplasticareshowninFigureI-3.Adventure3istheonlyprojectthatusesabreadboardinthecompletedproject;theotheradventuresuseabreadboardonlytotestacircuit.Alargerbreadboardwillbeeasiertoworkwith,butifyoucanonlyfindsmallerones,that’sperfectlyokay.
FIGUREI-3Breadboardsindifferentsizesandcolours
Jumperwiresarewiresyouusewhenyoubuildprototypecircuitstotryoutnewconcepts.TheymaybeshortpiecesofstiffwirelikethoseshownontherightinFigureI-4,ortheymaybemoreflexiblewirewithpinsoneitherendliketheonesontheleft.
FIGUREI-4Jumperwires
LEDsareaparticularsortoflight(LEDsstandsforlight-emittingdiodes)thatcomeina
bigselectionofsizesandcolours.FormostoftheprojectsinthisbookyoucanusewhateversizeandcolourofLEDsyoulike.Themostcommonsizeis5mm,butthelarger10mmLEDscanbegreatfuntousetoo.MostLEDsaresingle-colour,butyouuseanLEDinAdventure6thathasfourlegsinsteadofonlytwoandcanchangecolour.InAdventure8youusesomethingcalledaLilypadLED,whichismadeespeciallyforsewingcircuits.AllthedifferenttypesofLEDusedintheprojectsareshowninFigureI-5.
FIGUREI-5DifferenttypesofLED,withacolour-changingLEDontherightandbelowitaLilypadLED
Resistorsareacomponentyoureadmoreaboutintheadventures.Theycomeindifferentvaluesofresistance,whichismeasuredinohms(Ω).Youdon’tneedmanydifferentresistancesfortheprojectsinthebookbutasresistorsaresmallandquitecheapit’sagoodideatobuyextra.Youneedresistorsof68or100Ω,220Ω,10k(10,000)Ω,1M(1,000,000)Ωand10M(10,000,000)Ω.FigureI-6showsthedifferentresistors.
FIGUREI-6Resistorsneededfortheprojectsinthisbook:100Ω(topleft),220Ω(topright),10kΩ(bottomleft),1MΩ(bottommiddle)and10MΩ(bottomright)
Potentiometersaretheelectroniccomponentsbehindvolumeknobsordialsonastereo.Theycomeinmanydifferentsizesandshapes.Somefitintoabreadboardontheirown,liketheblueoneinFigureI-7,whereasothersneedwiressolderedtothemthatcanconnecttoabreadboard,liketheoneinthemiddleinFigureI-7.Largeronesareeasiertomountinaprojectandmaybecalledpanel-mountpotentiometers.
FIGUREI-7Threedifferenttypesofpotentiometer
Aservo,showninFigureI-8,isamotorthatyouuseinAdventure3.
FIGUREI-8Aservomotor
Buttonsareanothercomponentthatcomeinmanyshapesandsizes.Youmighthavenevernoticedthisbefore,buttherearemanydifferentkindsofbutton!Alltheprojectsinthisbookusepush-to-make(theoppositeofpush-to-break)buttonssothosearetheonestobuy;aslongastheyarepush-to-make,youcanuseanykindofbuttonyouwouldlike.Tactilepushbuttonsareverylittlebuttonsthatfitinabreadboard,sotheyaregoodtohavewhenyouaretestingyourcircuit.Foryouractualprojects,panelmountpushbuttonsarebetter.BothareshowninFigureI-9.
FIGUREI-9Atactilepushbutton(left)andthreedifferentpanelmountbuttons(right)
InAdventure4youdiscoverhowtouseshiftregisters,whicharesmallblackchipsyoucanusetocontrolalotofLEDs.Youwantachipthatisa74HC595shiftregister—youfindoutwhatthatmeansintheadventure.Youneedtobuyachipwith16legsonit,asshowninFigureI-10.
FIGUREI-10Ashiftregister
Piezosareusedtodetectvibrationsandcanalsomakesound,likeaspeaker.YouneedonepiezoforAdventure5andsixforAdventure9.Theysometimescomeinsideblackplastichousing,whichisokayfortheoneinAdventure5butyouneedatleastfivewithouthousing(liketheoneinFigureI-11)forAdventure9.
FIGUREI-11Apiezo
Alight-dependentresistorcantellanArduinoboardhowbrightordarkitis.TheselookliketheoneinFigureI-12orcanbealittlebigger.
FIGUREI-12Alight-dependentresistor
HeaderpinsaresmallstripsofmetalthatareseparatedbyplasticsothattheyfitperfectlyintotheholesontheArduinoUno.Theycomeindifferentspacings(calledpitches),soyoushouldmakesureyouget2.54mmmaleheaderpins,liketheonesinFigureI-13.YouneedastripoffiveforAdventure5,butyoucanbuytheminlongerstripsandeasilybreakthemapartintosmallersectionswithpliers.
FIGUREI-13Maleheaderpins
Whenyouthinkaboutcircuitsandelectricity,oneofthefirstthingsyoupictureis
probablywire.Butwireisn’tasingleitem;therearemanydifferentkinds.Wirecanbemadeofasinglepieceofmetal(calledsolidcore)oralotofsmallerpiecesofmetaltwistedtogether(calledstranded).FigureI-14showssolidcoreandstrandedwire.Solidcorecanbeusefulforbreadboardsbutit’sverystiff.Strandediseasiertobend,butyouneedtosoldertheendofitinordertogetittofitinabreadboard.Youcandecideforeachprojectwhichsortyouwanttoworkwith—thereisn’tarightorwrongtypetouse.
FIGUREI-14Solidcorewire(left)andstrandedwire(right)
Wireusuallycomeswithsomekindofcoatingthatdoesn’tconductelectricity.ItmaybecolouredplasticlikethewireontherightinFigureI-15,oritmaybeenamelledlikethewireontheleft.Youcandecidewhichwireworksbestinyourprojects.TheenamelledwireworkswellintheaugmentedwindchimeinAdventure5becauseit’sverythinandletsthechimesswingeasily.However,youcouldbuildthewindchimeusingadifferentthinwire.
FIGUREI-15Enamelled(left)andplasticcoated(right)wire
Solderislikeaconductiveglueforelectronics.ItsometimescomesonspoolsindifferentthicknesseslikeinFigureI-16.Theprojectsinthisbookdon’trequireverysophisticatedsoldering,soyoudon’thavetoworryaboutwhichthicknesstobuy.Justaboutanythicknesswillworkokay.Theonlyimportantthingtowatchoutforistomakesureyoubuysolderforelectronics—don’tbuysolderthat’susedforplumbing!
FIGUREI-16Solderonspools
Afteryoubuildyourprojects,youmightwanttorunthemwithouthavingtoconnectthemtoyourcomputerforpower.Ifso,youcaneitherpoweryourprojectfromapowersupplyorfromabattery.Ifyouuseapowersupply,it’seasiesttobuyaUSBwalladapter—apowersupplythatletsyouconnectaUSBcabletoawallsocket,withtheotherendoftheUSBcablepluggedintoyourArduinoboard.Ifyou’dliketouseabattery,thebestoptionistogeta9VbatteryconnectorwithaDCbarrelontheend.ThereisablackplugsocketonyourArduinoboardwhereyoucanplugintheconnector.BothoptionsareshowninFigureI-17.FortheLilypadArduinoUSB,youcanuseaLiPobattery,butyoureadmoreaboutthatinAdventure8.
FIGUREI-17A9Vbattery-to-DC-barrelconnector(left)andaUKplugforaUSBcable(right)
WhenyouworkwithsoftcircuitsinAdventure8,youneedalligatorclipsliketheonesinFigureI-18,whichyouuseinsteadofjumperwires.
FIGUREI-18Alligatorclips
InAdventure8,youalsouseconductivethread,whichisthreadspunwithconductivefibres.Therearedifferentkindsavailablefromdifferentmanufacturers,butalltheoptionsareasilvercolourasshowninFigureI-19.
FIGUREI-19Conductivethread
ToolsYouWillNeedJustasyouneedhammersandsawstobuildsomethingwithwood,youneedspecialtoolstoworkwithelectronics.
Whenyoutestyourcircuitsyouuseabreadboard,butyoueventuallyneedtogobeyondthebreadboard.Forexample,youmightneedtoaddlongerwirestoacomponentsoitfitsinsideyourhousing,oryoumightwanttoconnectcomponentstogetherinamorepermanentwaythatwon’tfallapart.
Thefirstthingyouneedisasolderingiron.Solderislikeglueforelectronics,butitonlyworksathightemperatures(thinkofitasahotglueforelectronics).Asolderingironisatoolthatgetsveryhot(muchhotterthananoven)sothatitcanmeltsolder.Onlyuseasolderingironwhenanadultisnearbytohelpyou.
Asolderingironmaybeasinglehand-heldtoolthatplugsintothewall,liketheoneinFigureI-20.Oritmayplugintoaboxwithatemperaturedialthatplugsintothewall.Eitherkindisokay.Theimportantthingistobuyonethatismeantforsmallelectronicsandnotplumbingoranyotheractivity.
FIGUREI-20Asolderingiron
Wireoftencomeswithaplasticcoatingthatisaninsulatorthatdoesn’tconductelectricity.Yousometimesneedtoremovethisplasticcoatingfromtheendsofthewiresoyoucanfititintoabreadboardorsolderacomponenttoit.Youcouldalwayscarefullyuseaknifeorcutterstotryandremovetheplastic,butthatcanbeaveryfrustratingmethod.Itiswellworthbuyingtherighttoolforthejob.Enterthewirestripper!
Wirestripperscomeinlotsofshapesandsizes,asyoucanseeinFigureI-21.Choosewhicheveroneyoulikebest.
FIGUREI-21Differentkindsofwirestripper
Wirecuttersdowhatyouexpect—theycutwires.Besuretogetsmalleronesthateasilyfitinyourhandasyouwillbeworkingwithsmallcomponentsandthinwires.FigureI-22showsthekindofwirecuttersyoucouldget.
FIGUREI-22Wirecutters
Pliershelpyoushapeandbendwires.Theycomeindifferentsizesandshapes,butasmallergeneralpurposepairofpliersisallyouneedfortheprojectsinthisbook.EitherofthepairsinFigureI-23wouldworkwell.
FIGUREI-23Pairsofpliers
Thenexttoolmayseemabitdaunting,butitcanbeyourbestfriendwhenworkingwithelectronics.It’sthemultimeter!Itmeasuresmultiplethings(that’showitgotitsname),withresistanceandvoltagebeingthemostusefultothebeginner.Theyrangefromverycheaptoextremelyexpensive.Whenyouarechoosingoneforyourself,youdon’tneedtospendalotofmoney,especiallyifitisyourfirstmultimeter.Youprobablywantonethatauto-ranges,thoughthat’snotessential,butyoudefinitelyneedonewithacontinuitytest.(Whenyoulookatmultimetersinastore,auto-rangingandcontinuitytestingwillbelistedintheirfeatures.)Auto-rangingmeansthatyoudon’tneedtoknowtheapproximatevalueofwhateveryouaretestingbeforeyoutestit.Acontinuitytestiswhenthemultimeterbeepswhenanelectricalconnectionismadebetweentheprobes.FigureI-24showsalessexpensivemultimeter,whichisn’tauto-rangingbutdoeshaveacontinuitytest.
FIGUREI-24Amultimeter
Thefinaltoolsarenotspecificallyusedwithelectronicsbutarebeessentialforconstructingthehousingforyourprojects:scissorsandautilityknife(FigureI-25).Alwaystakecarewhenusingeither!
FIGUREI-25Apairofscissorsandautilityknife
SoftwareYouWillNeedWhenwetalkaboutArduino,itiseasytothinkabouttheboardandnothingelse.Afterall,that’sthepartyouphysicallyplaceintoyourproject.However,theArduinoneedscodeinordertodoanything.YouwritethatcodeonanothercomputerfirstandthenuploadthecodetotheArduinoboard.
ThecompanythatmakestheArduinoboardalsomakesthesoftwarethathelpsyouwriteanduploadthecode.It’sfreetodownloadfromhttp://arduino.cc/en/Main/Software.
Adventure1takesyouthroughthestepstosettingupthesoftwareonyourcomputer.
ThecircuitschematicsanddiagramsofcircuitsonbreadboardsinthisbookaremadewithaprogramcalledFritzing,whichisalsofreeonlineathttp://fritzing.org/download.YoucanevenuseFritzingtostartdesigningyourownprojects!
OtherUsefulMaterialsWritingcodeandbuildingacircuitisonlyonehalfofcompletingaproject.Yourprojectdoesn’tcomealiveuntilitissurroundedbysomekindofhousing.Whetherit’sagameoraninteractivelight,whenitisjustacircuitonabreadboardithasn’tyetreacheditsfullpotential.
So,tomaketheprojectsinthisbook,youusemanylow-techtechniquesalongsideyournewlyacquiredhigh-techskills.Scissors,paperandglueformthebasisofmanyofyourprojects.It’sgoodtohavethefollowingitemstohand,butit’sneverabaddecisiontoadddecorativeitemslikeglitterthatallowyoutoletyourimaginationrunriot!Inparticular,youneedthefollowingthings:
SmallcardboardboxesorshoeboxesCard,cardboardandpaperPaintfordecoratingStringoryarnWhitecraftglue,glue-stickorahotgluegunPaintbrushAballoon(forAdventure6)Amarble(forAdventure9)
WhatIAssumeYouAlreadyKnowBecauseyou’vestartedreadingthisbook,I’mgoingtoassumeyou’realreadyinterestedintechnology!Youdon’tneedtohavedoneanycomputerprogrammingpreviouslyorbuiltanycircuits(that’swhatthisbookisexplaining!),butIdoassumethatyouhaveusedacomputerbefore.
YouneedacomputertoworkwiththeArduinobutitdoesn’treallymatterwhatoperatingsystemyourcomputeruses—MacOSX,WindowsormanydifferentLinuxdistributions(seehttp://playground.arduino.cc/Learning/LinuxforguidanceonwhichLinuxdistributionsyoucanuse).Iassumethatyouarecomfortablegoingonlineanddownloadingfilesandthatyouknowhowtofindandopenapplicationsonyourcomputer.
Youmayneedanadministratorpasswordtoinstallsomeofthesoftware,soifyoudon’tknowthepasswordforyourcomputeritwillhelpifsomeonewhodoesknowthepasswordisnearbywhenyouinstallit.
HowThisBookIsOrganisedThisbookguidesyouthroughprogrammingyourArduinoboardandconstructingcircuitsinnineadventures.Eachadventurestartsbyintroducingthenewskillyouneedinordertocompletethestandaloneprojectattheendoftheadventure.Thenewskillmightbelearninghowtouseanewcomponentsuchasamotor,forexample,orhowtodosomethingcleverincode.
ThemostimportantadventureforyoutostartwithisAdventure1.IthelpsyouinstallthesoftwareneededtouploadyourcodeontoyourArduinoboard.Afterall,ifyoudon’tdothat,therestoftheadventureswon’tbemuchfun!
Adventures2to9buildonpreviousadventures,soIrecommendthatyoufollowtheadventuresinorder.Ofcourse,ifyoupreferyoucanthrowcautiontothewindanddotheminanyorderyouwant.Youcanalwayslookupmoreguidanceonaparticulartopicfromanearlieradventureifyoucomeacrosssomethingyoudon’tknow.
AswellashelpingyousetupyourcomputersoyoucanprogramyourArduinoboard,Adventure1alsoguidesyouthroughyourfirstArduinoprogram,calledasketch.YouevenbuildyourfirstcircuitonabreadboardandcontrolanLED.
InAdventure2youlearnhowtocontrolmorethanoneLED,howtoprintmessagesfromyourArduinoboardtoyourcomputerandhowtouseyourfirstsensor—apotentiometer.Yougettoputyournewskillsintopracticebybuildingastatusmessagesignthatlightsuptoshowthatyoudon’twanttobedisturbed.
InAdventure3youareintroducedtoyoursecondsensor:apushbutton.Youcombineitwithpotentiometerstocontrolamotor.Youalsolearnhowtouseforloopsincomputercodetorepeatthesamethingoverandoveragain.Puttingitalltogether,youbuildacombinationsafethatopensonlywhenthecorrectcombinationisdialed.The“safe”isonlyacardboardbox,soit’sprobablynotfitforstoringthefamilyjewels,butit’sgoodenoughtoprotectyourfavouritesweets.
Adventure4showsyouhowtobreakupyourcodeintobite-sizedpiecesusingfunctions.YouthenusefunctionstocontrolmultipleLEDsusingspecialchipscalledshiftregisters.Inthefinalprojectoftheadventure,youmakeletterswithembeddedLEDsinthestyleofoldcarnivalsigns.
Adventure5addssoundtothegrowinglistofactionsyoucancontrolwithyourArduino.Youfindouthowtomakelistsincodetoplayshorttunesoveranewcomponent—apiezo.Youthenmakeanaugmentedwindchimethatputsanelectronictwistonatraditionalinstrument.
Adventure6introducesmoresubtlecontrolsbyshowinghowyoucanfadeanLEDandnotjustturnitonandoff.YoualsoexpandtheabilitiesofyourArduinobyinstallingnewlibrariesthatdon’tcomewiththeArduinosoftware.Youthencombineyournewskillswithathree-colourLEDtocreateacrystalballthatmagicallychangescolour!
InAdventure7youareintroducedtoanewArduinoboard,theArduinoLeonardo.You
masteroneoftheexcitingfeaturesoftheLeonardo:makingacomputerthinktheArduinoisakeyboard.Youaddanewsensorthatdetectslightandmakeacomputergamecontrollerthatletsyouplayagamewithawaveofyourhand.
InAdventure8yougettoworkwithanotherArduinoboardandbuildcircuitsusinganeedleandthreadinsteadofwireandasolderingiron.Thisadventurehelpsyoubecomeamasterofarraysandcreateahoodiethatdisplaysasecretmessage.
Andfinally,Adventure9isthebigadventure!Youhavetochancetoputtogetheralltheskillsyou’vegainedovertheearlieradventurestocreateamarblemazegamethatautomaticallykeepstrackofyourscore,countsdowntheremainingtimeandplayssoundeffects.Youuseafamiliarcomponentinanewway,usingapiezotodetectvibrationsaswellasplaysoundeffects.
AppendicesAandBprepareyouforfurtheradventuresbeyondthisbook.AppendixApointsyoutowardotherArduinoresourcesinprintandonline,andAppendixBshowsyouwheretobuytoolsandcomponentsforyourprojects.
ConventionsThroughoutthisbookthereareboxestohelpyouout:
Theseboxesexplainconceptsortermsyoumightnotbefamiliarwith.
Theseboxesgiveyouhintstomakeyourcodingandbuildingeasier.
Theseboxescontainimportantwarningstokeepyouandyourcomputersafewhencompletingasteporproject.
Theseboxesfeaturequickquizzesforyoutotestyourunderstandingormakeyouthinkmoreaboutatopic.
IntheseboxesIexplainthingsorgiveyouextrainformationIthinkyou’llfinduseful.
Theseboxespointyoutovideosonthecompanionwebsitethattakeyouthroughthesteps.
Youwillalsofindtwotypesofsidebarinthebook.TheChallengesidebarsaskyouhowmightexpandonthenewskillsyouarelearningoraddnewfeaturestoyourprojects.TheDiggingintotheCodesidebarsgodeeperintotheprogrammingconceptsusedinArduinoprogramming.
Whenyouarefollowingtheinstructionsinthebook,youshouldtypeinthecodeexactlyasyouseeit—every;isveryimportant!However,thespacesbetweenwordsdon’tmatter.Spacesareusedtomakethecodeeasiertoread,butitdoesn’tmattertotheArduino.
Forexample,bothofthefollowinglinesmeanthesamething:
if(i<4)
if(i<4)
YoursketchcouldbewrittenasasingleverylonglineoftextanditwouldstillrunontheArduino!Butitwouldbeverydifficultforanotherprogrammertounderstandwhatis
happening.Addingspacesandnotestoexplainwhatishappeninginthecodeisthebestwaytoprogram.
Sometimesalineofcodeistoolongtofitononelineofthisbook.Ifyouseethesymbolattheendofalineofcode,thatmeansthatlineandthenextlineshouldbetypedasa
singlelineofcodeinyourArduinosoftware.
Forexample,thefollowinglineshouldbetypedononeline,nottwo:
Serial.println("Hello,fromthesetup()functionin
yourArduinoUno!");
Tohelpyoukeeptrackofthenewcodingconceptsyoulearn,thereisaQuickReferenceTableattheendofeachadventure,whichlistsanynewfunctions,datatypesorotherprogrammingcommandsthathavebeenintroducedinthatadventure.
Whenyoucompleteanadventure,youunlockanachievementandcollectanewbadge.YoucancollectbadgestorepresenttheseachievementsfromtheAdventuresinArduinowebsite(www.wiley.com/go/adventuresinarduino).
TheCompanionWebsiteThroughoutthebook,you’llfindreferencestotheAdventuresinArduinocompanionwebsite,www.wiley.com/go/adventuresinarduino.Here,you’llfindtutorialvideostohelpyouthroughthephysicalmakingofyourprojectsalongwiththecodeused.Itcanbeveryfrustratingtotrackdownamistakeafteryou’vetypedincodefromabookbyhand.Theimportantthingisunderstandingwhatthecodeisdoingandnotjusthowtotypeitalloutyourself(oratleastnotwhenyouarefirststartingout)!
ReachingOutYou’llfindalotoftipsinAppendixAaboutwheretogoforhelpbutthefirstplaceyoushouldalwayslookistheArduinowebsite(www.arduino.cc).IthaslotsofusefulinformationintheLearningsection,andyoucanalwaysaskquestionsintheForum.
Youcanalsocontactmebysendingmeamessagethroughthewebsitewww.adventuresinarduinobook.com.
Timetostartyouradventures!
YOUWILLSOONbecreatingexcitingprojectsthatbridgethephysicalanddigitalworlds!You’lllearnhowtowritecodethattriggerssound,controlsmotorsandflasheslights.TheArduinoistheperfecttoolforcombiningcircuitsandcode!
YouwillusethesamethreestepsforeachprojectyoubuildwithyourArduino:
1. WritethecodethattellstheArduinoUnowhattodoonyourcomputerusingtheArduinosoftware.
2. ConnectyourArduinoUnotoyourcomputer,anduploadyourcodeontotheboard.3. BuildandconnectyourcircuittoyourArduinoUno.
Butfirstthingsfirst.Beforeyoucandoanythingelse,youneedtodownloadandinstalltheArduinosoftwareandsetupyourcomputertoprogramyourArduinoUno.That’swhatyouwillbedoinginyourfirstadventure.Then,whenyou’vegoteverythingworkingasitshould,you’regoingtostartyourfirstArduinoproject—controllingwhenalightturnsonandoff.
WhatYouNeedTogetstarted,youneedthefollowingthings.Figure1-1showstheelectroniccomponentsyouwillneed.
AcomputerAnArduinoUnoAUSBcableAnInternetconnectionsoyoucandownloadtheArduinosoftware
FIGURE1-1AnArduinoUnoandUSBcable
DownloadingandInstallingtheArduinoSoftwareonYourComputerInordertorunArduinoprograms,inadditiontoanArduinoUnoyouneedacomputerandsomespecialsoftwaretomaketheArduinowork.YouwillbewritingthecodethatrunsontheArduinoUnoonanothercomputerfirst,andwillthenuploadittotheboard.Soundscomplicated,doesn’tit?Don’tworry;you’llbeguidedthroughtheprocessstepbystep.Andit’snotasdifficultasitsounds.
You’regoingtouseapieceofsoftwaretowritethecodeandthenuploadit.ThispieceofsoftwareiscalledtheArduinoenvironment,orintegrateddevelopmentenvironment(IDE).ItisavailableforfreefromtheArduinowebsiteathttp://arduino.cc/en/Main/Software(seeFigure1-2).
FIGURE1-2YoucandownloadtheArduinoIDEforyourcomputerfromtheArduinowebsite.
Anintegrateddevelopmentenvironment(IDE)isasoftwareapplicationthatisusedtowritecomputercodeinaparticularlanguage;it’salsoreferredtoasaprogrammingenvironment.Theapplicationcancreateandeditcode,aswellasrun(orexecute)thecode.ManyIDEsalsoprovidefeaturestohelpprogrammersdebugtheirprograms—inotherwords,checktheirprogramsforerrors.
YouarenowgoingtodownloadandinstallthelatestversionoftheArduinosoftwaredesignedforyourparticularcomputer’soperatingsystem,usingthestepsoutlinedhere.Whenthisbookwaswritten,1.0.6wasthecurrentversionofthesoftware.Youcanseewhatthecurrentversionisbyvisitinghttp://arduino.cc/en/Main/Software.Youcan
findthecurrentversiontowardsthetopofthepage.Afteryouhaveinstalledthesoftware,youcanseewhatversionyouareusingbyreadingthetitlebarofthewindowthatappearswhenyoulaunchtheArduinoIDE.
ThesoftwarecanrunonWindows,MacorLinuxcomputers,butdependingonyourcomputer’soperatingsystem(OS),youmayneedtoinstallboththeIDEandanotherpieceofsoftware,calledadriver.Thisadventuredescribeswhatyouneedtodo,butyoucanalsovisithttp://arduino.cc/en/Guide/HomePage,whichhaslotsofguidanceonhowtogetthesoftwareinstalled.
HaveyourArduinoUnoandUSBcabletohandasyouinstallthesoftware,becauseyoumightneedthemforsomeoftheinstallationsteps,dependingonyourcomputer’soperatingsystem.
Adriverisapieceofsoftwarethatletsyourcomputercommunicatewithanexternaldevice,suchasaprinterorakeyboard.
InstallingArduinoSoftwareonaMacItisquitesimpletoinstallthesoftwareonaMac.Youdon’tneedtoinstalladriver,onlytheArduinoIDE.Justfollowthesesteps:
1. InyourInternetbrowser,opentheArduinodownloadpageathttp://arduino.cc/en/Main/Software.
2. SelecttheMacOSXzipfilefromthelistofcurrentArduinodownloads.3. Findthefilecalledarduino-1.0.6-macosx.zipandunzipitbydouble-clickingit.
NowmovetheArduino.appfileintoyourApplicationsfolder.4. Afteryou’veinstalledthesoftware,plugoneendofyourUSBcableintoyour
Arduinoboard(showninFigure1-3)andtheotherendintoyourcomputer.Amessageaboutanewnetworkdevicemayappearonscreen.Ifthathappens,youcanjustcancelorclosethemessagewindow.
FIGURE1-3PlugtheUSBcableintotheArduinoUnoandthenconnectittoyourcomputer.
Ifyouhaveanyproblems,visithttp://arduino.cc/en/Guide/MacOSXformorehelp.
ToseeavideoofhowtoinstalltheArduinoIDEonacomputerrunningMacOSX,visitthecompanion
siteatwww.wiley.com/go/adventuresinarduino.
InstallingArduinoSoftwareonaWindowsPCYouneedtofollowanumberofstepstoinstalltheArduinosoftwareonWindows7,VistaandXP(seetheTipsandTricksboxforWindows8).Youwillbeinstallingtwothings:thesoftwareandthedriver.
1. InyourInternetbrowser,opentheArduinodownloadpageathttp://arduino.cc/en/Main/Software.
2. StartbydownloadingthefilecalledWindowsZIPfile.3. FindthedownloadedzipfileandunzipittotheProgramFilesfolder.Itshould
containmultiplefoldersandfiles,includingafoldercalleddriversandafilecalledarduino.exe.Ifyouwouldlike,youcanright-clickarduino.exeandcreateashortcuttoplaceonyourDesktop.
4. PlugoneendoftheUSBcableintoyourArduinoboardandtheotherendintoyourcomputerasshowninFigure1-3.YoushouldseelightsilluminateonyourArduinoUno.Thisjustmeansithaspower.
5. YourcomputerwillnowstarttolookforadrivertousewiththeArduinoboard.Yourcomputermayfindthedriveronitsown,but,dependingontheversionofWindowsyourcomputerisrunning,youmayneedtofollowdifferentstepstofinishinstallingthedriver.Youmayneedtoknowanadministratorpasswordforthecomputerandmightneedsomehelpwithsomeonewithmorecomputerexperience.Youcanalwaysvisithttp://arduino.cc/en/Guide/Windowsformoredetailedinstructions.
6. ClicktheStartmenuandopentheControlPanel.7. WhileintheControlPanel,navigatetoSystemandSecurity.ClickSystem,andwhen
theSystemwindowappears,opentheDeviceManager.8. InsidetheDeviceManagerlookunderPorts(COM&LPT).Youshouldseeaport
namedArduinoUNO(COMxx).Ifyoudon’tseeaCOM&LPTsection,lookunderOtherDevicesforUnknownDevice.
9. Right-clickArduinoUNO(COMxx)portandchoosetheUpdateDriverSoftwareoption.
10. IfyouarerunningWindowsXPortheHardwareUpdateWizardappears,gotohttp://arduino.cc/en/Guide/UnoDriversWindowsXPandfollowthescreenshotstoinstallthedriverslocatedinthefolderyoudownloadedandunzipped.
11. IftheHardwareUpdateWizarddoesn’tappearandinsteadyouseeawindowwiththeoptionsSearchAutomaticallyforUpdatedDriverSoftwareandBrowseMyComputerforDriverSoftwareappears,clickBrowseMyComputerforDriverSoftware.
12. Navigatetothefolderyoudownloadedandunzipped.Gotothefolderinsideitcalleddriversandselectarduino.inf.
Wow,thatwascomplicated.Luckily,youdon’thavetodothatagain.Youonlyneedtodoitonce.ThestepsmightchangewhennewversionsoftheArduinoIDEarereleasedorif
thereareupdatestoyouroperatingsystem.YoucanalwaysgototheArduinoforumboardforinstallationproblemsathttp://forum.arduino.cc/index.php?board=2.0.Youcanlookoverthequestionsaskedbyothersandevenaskyourownifyoucan’tfindaquestionsimilartotheproblemsyouarehaving.
Ifyourunintoanyproblems,firstvisithttp://arduino.cc/en/Guide/Windowsformorehelp.
Youcanalsovisithttps://learn.adafruit.com/lesson-0-getting-started/installing-arduino-windows,www.dummies.com/how-to/content/how-to-install-arduino-for-windows.html,orhttps://learn.sparkfun.com/tutorials/installing-arduino-ide/windowsforevenmoretipsincludingextraguidanceforinstallingonWindows8.
IfyourcomputerrunsWindowsXP,youcanfollowalongwiththescreenshotsathttp://arduino.cc/en/Guide/UnoDriversWindowsXPtoinstallthedrivers.
InstallingArduinoSoftwareonaLinuxMachineIfyourcomputerrunsLinux(ifyouareusingaRaspberryPi,forexample),youshouldfirstvisittheonlinedocumentationforLinuxandArduinoathttp://playground.arduino.cc/Learning/Linux.TherearemanydifferenttypesofLinux,soIhaven’tlistedthemallhere,andifyourcomputerrunsaLinuxdistribution,youlikelyalreadyknowhowtoinstallnewsoftware.ItisprobablyeasiesttoinstalltheArduinoenvironmentbyusingapackagemanager.Here’showtodotheinstallationonaDebianvariantofLinux,suchasRaspbianonRaspberryPi.Onacommandline,enterthefollowingcommand:sudoapt-getinstallarduino
Thiscommanddownloadsandinstallsthesoftware.Alternatively,youcandownloadthe32-and64-bitapplicationsdirectlyfromtheArduinodownloadpageathttp://arduino.cc/en/Main/Software.Youdon’tevenneedtoworryaboutcompilingsourcecode,butdon’tforgettoreadtheguidelinesforyourdistributionathttp://playground.arduino.cc/Learning/Linux.
IfyouareusingaRaspberryPiorotherLinux-basedsystem,Iamassumingthatyouknowhowtousethecommand-lineinterfacetoinstallsoftwareforwhateverversionofLinuxyouarerunning.IfyouneedmoreinformationorarefresheronusingtheRaspberryPi,checkoutAdventuresinRaspberryPibyCarrieAnnePhilbin(JohnWiley&Sons,Inc.,2014).
ExploringtheArduinoIDEWelldone!Nowthatyouhavethesoftwareinstalled,you’rereadytostartusingtheArduinoIDE!It’stimetolaunchthesoftware.IfyourcomputerisaMac,gotoApplicationsanddouble-clickArduino.IfyourcomputerisrunningWindows,eitherdouble-clicktheshortcutontheDesktop(ifyoumadeoneasdescribedearlierintheadventure),orgotothefolderyoudownloadedearlieranddouble-clicktheArduinoapplication.IfyourcomputerisrunningLinux,starttheArduinoIDEeitherfromthecommandlineorbydouble-clickingtheprogramicon.TheArduinoprogramicon(seeFigure1-4)looksthesameonMac,WindowsandLinux.
FIGURE1-4TheArduinoprogramicon
WhentheArduinoIDEhasfinishedstarting,awindowsimilartotheoneshowninFigure1-5willappear.
FIGURE1-5TheimportantpartsoftheArduinoIDE
First,you’regoingtofindoutaboutsomeofthebasicfunctionsoftheArduinoIDE.TherearesixbuttonsatthetopoftheArduinowindow(seeFigure1-5),andmostofthemareeasytofigureout.ThemiddlethreebuttonsareNew,OpenandSave.ClickingtheNewbutton(surprise!)startsanewArduinofile,theOpenbuttonopensanexistingArduinofile,andtheSavebuttonsavesthecurrentthefile.You’llnoticethere’sabuttononitsownonthefarright—youwillbefindingoutaboutthisinAdventure2.Thatjustleavesthetwobuttonsontheleft.
ThebuttonthatlookslikeatickistheVerifybutton.Whenyouclickthisbutton,theArduinocompilesthecode;inotherwords,ittakesthecodeyouhavegivenitandtranslatesitintosomethingtheArduinoboardcanunderstand.Thereisasecondthingthisbuttondoes.IftherearepartsofthecodethatArduino’scompilerdoesn’tunderstand—perhapsasemicolonwasmissedoutoratypowasmadewhenthecodewastyped—itprintsouttheerroratthebottomoftheArduinoIDEwindow.Ittriestobehelpfulwithwhatitprints,butsometimesitdoesn’tmakesense!Laterthisadventuregoesoversomeofthecommonerrormessagesandwhattheymightmean.
Compilingcodeistheprocessoftakingcodewrittenbyahumanandturningitintoinstructionsthatcanbeunderstoodbyamachine.
Don’tworrytoomuchabouthowthishappensyet.AllyouneedtoknowfornowisthattheVerifybuttonisusedtoturnyourcodeintosomethingtheArduinocanunderstand,anddeterminethatthecodeisfreefromsimpleerrors.Afteryouhavedonethat,youclickthefinalbutton,whichistheUploadbutton.ThiscompilesanduploadsthecodetotheArduinoUno.Thisisthebuttonyouwillprobablyusemost,asitputsyourcodeontotheArduinoUno.TheVerifybuttoncanbeusefulifyouarewritingcodeanddon’thaveyourArduinoUnonearbybecauseitmeansyoucanatleastcheckifyouhaveanysimpleerrorsinyourcode,althoughyouwon’tknowifyourcodecompletelyworksuntilyoucanuploaditontoaboard.
UsingBlinktoTestThatEverythingIsSetUpCorrectlyYoucanwritecomputercodeforadevicelikealaptoporRaspberryPiandthenrunitonthesamecomputeryou’vewritteniton.WithArduino,it’sabitdifferentbecauseanArduinoboardcan’tprogramitself,soyouhavetowritetheArduinocodeonacomputerthatcanruntheArduinoIDE.TheIDEthentakesthecodethathumanscanwriteandreadandtranslates(orcompiles)it,turningitintocodethattheArduinoboardunderstands.TheIDEthencopiesanduploadsthecompiledcodeontotheArduinoboard.
Softwaredevelopersusebasicprogramstotestthattheircomputerisworkingastheywouldexpect.ThesearecalledHelloWorldprograms.
AHelloWorldprogramisverysimple.Ifyouwerelearninganewprogramminglanguage,youwouldwriteaprogramthatwouldjustprintthephrase“Helloworld”tothescreen,whichwouldshowyouthateverythingwassetupproperly.Butwait—theArduinodoesn’thaveascreen!AfteryouloadthecodeontheArduinofromyourcomputer,itdoesn’ttalktothecomputeranymore;alltheUSBcabledoesisprovidetheArduinowithpower(thoughyoufindoutinthenextadventurehowtosendmessagestothecomputerthroughtheUSBcable).
WhattheArduinoboardcandoisblinkalight.Itevenhasonebuiltintotheboardforexactlythispurpose.There’satinyyellowororangelight-emittingdiode(LED)nearthenumber13ontheboard(seeFigure1-6).ThisLEDisusefulbecauseyoucanprogramittoturnonandoffinordertoquicklycheckthattheArduinoboardisworking.Youdon’tneedanythingbesidesyourcomputer,aUSBcableandyourArduinoboard.
FIGURE1-6Thebuilt-inLEDontheArduinoboardisnearthenumber13.
TheArduinoIDEcomeswithsomeexamplecodetohelpgetyoustarted.OneoftheseexamplesistheBlinkprogram,orsketch,whichisusedastheHelloWorldprogramforArduino.You’renowgoingtousethattocheckeverythingisworkingasitshould.
AnLED,orlight-emittingdiode,isanelectricalcomponentthatlightsupwhenelectricalcurrentflowsthroughit.Adiodeonlyletselectricityflowinonedirection,soanLEDlightsuponlywhenthelonglegisconnectedtothepositivesideofapowersourceandtheshortlegisconnectedtothenegativeside.Iftheyareswitched,theLEDwon’tlightup.
Arduinoprogramsareoftenreferredtoassketches,likequickdrawingsartistsmake.
UploadingBlinkTotestthatyourArduinoUnocanreceivemessagesandnewprogramsfromthecomputerwithoutanyproblems,youneedtocompileanduploadtheBlinksketch.SelectFile ⇒ Examples ⇒ 01.Basics ⇒ Blink(seeFigure1-7)toopenanewwindowwiththeBlinksketch.
FIGURE1-7OpeningtheBlinksketch,whichislocatedintheexamplesthatareincludedwiththeArduinoIDE
Beforeyouuploadyourcode,youfirstneedtochecktwosettings:theboardandtheport.YouneedtomakesurethesesettingsarecorrecteachtimeyoulaunchtheIDE.Afteryouhavesetthem,youdon’tneedtochangethemagainuntilyouquitandstarttheIDEagainatalatertime.Tofindtheboard,selectTools ⇒ Boards(seeFigure1-8).YoushouldseealistofallthedifferentArduinoboards.Makesureyouselecttheboardyouareusing.(ThiswillbeanUno,butifyou’renotsure,itiswrittenontheboarditself.)
FIGURE1-8Selectingtheboardyouareusing
You’llfindtheportunderTools ⇒ SerialPort(seeFigure1-9).Selecttheportyouareusing,thesamewayyoufoundtheboard.MakesureyouhavepluggedyourboardintoyourcomputerwiththeUSBcable,ortheportwon’tappearonthelist.
FIGURE1-9SelectingtheportyourArduinoboardispluggedinto
Itmaynotbeobviouswhichportyoushouldselectifthereismorethanonelisted.YoucantrylookingatthelistwhentheArduinoboardisnotpluggedin,thenpluggingintheboardandlookingagain.Ifoneappearedthatwasn’ttherebefore,thatisprobablywhatyoushouldselect.
IfyouareusingaMac,lookfortheportthatstartswith/dev/tty.usbmodem.OnaWindowscomputer,theportisjustlistedasaCOMport.InLinux,theportstartswith/dev/ttyACM.Itwon’thurtanythingifyoudon’tselecttherightport,soifyou’renotsure,justselectaportandclicktheUploadbutton.Ifyougetanerrormessage,tryselectingthenextportinthelist,andcontinuedownthelistuntilyoufindtheportthatyourArduinoboardison.
RememberthatyouneedtoplugyourUSBcableconnectedtoyourArduinoboardintoyourcomputer.Yourportwon’tshowupinyourlistofportoptionsiftheboardisn’tconnectedtothecomputer!
Afteryouhaveselectedyourboardandport,youarereadytouploadyourcode—thisistheBlinksketchyouhavealreadyopened.Todothis,simplyclicktheUploadbutton.Ifyouhaveforgottentoselecttheport,amessagemaypopupaskingyoutoselectone.
Ifyouhaveeverythingsetupcorrectly,youwillseeamessagetowardsthebottomoftheArduinoIDEwindowthatsaysCompilingSketchandthenUploading.Ifthesketchhasbeenuploadedwithoutanyproblems,youwillseeaDoneUploadingmessageasshowninFigure1-10.
FIGURE1-10MessageintheArduinoIDEaftersuccessfullyuploadingyourcode
LookattheLEDnexttothenumber13onyourboard.Isitflashingonforonesecondthenturningoffforonesecond?Ifso,success!Welldone.Ifnot,orifanyorangetexthasappearedatthebottomofyourArduinoIDE,thenextsectionwillhelpyoutroubleshootwhatmightbegoingwrong.
YouwillbesoonmakingchangestoyourBlinksketchandevenwritingnewsketchesofyourown.It’simportanttorememberthatthecodeyouwriteintheIDEhastobeuploadedtotheArduinoUno.Everytimeyoumakeachangetothecode,uploaditagaintoyourboard!
TroubleshootingCommonProblemsWhensomethinggoeswrongwhenyou’retryingtouploadcodetoanArduinoboard,amessagefromsomethingcalledavrdudemightbeprintedatthebottomoftheArduinoIDE(suchastheoneshowninFigure1-11).
FIGURE1-11Acommonerrorwhenthecomputercan’ttalkwiththeArduino
TheArduinoboardisbuiltaroundamicrocontroller(computer)chipmadebyacompanycalledAtmel.ThischipisatypeofmicrocontrollercalledanAVRandtheprogramthattheArduinoIDEusestotalktotheArduinoboardiscalledavrdude.Sowhenyougetmessagesfromavrdude,itmeanssomethinghasgonewrongwiththecommunicationbetweentheboardandthecomputer.Usuallyit’sthatthecomputeristryingtouseavrdudetosendanewsketchtotheArduinoUno,butthecomputercan’tfindit.Problemscouldbecausedbyselectingthewrongport,butifyouhavetriedalltheportstheremaybesomethingelsegoingwrong.
TheeasiestthingtotrywhenyougetanerrorfromavrdudeistounplugtheArduinoboardfromtheUSBcable(thisremovesthepowerandturnsitoff).Thenplugitbackinagain.Ifyoustillhaveproblems,tryunpluggingtheArduinoboardandthenquittingtheArduinoIDElikeyouwouldanyotherapplication.LaunchtheIDEagainandconnecttheArduinoUnooncemoretoseeifyoucanuploadanewsketch.
Ifyou’vedoneallthatandyoustillcan’tuploadsketchestotheArduinoboard,trygoingthroughtheinstallationprocessfortheIDEanddriversagain.
TheArduinowebsite(http://arduino.cc)isagreatresourcewithlotsoftutorials.Italsohostsaforumwhereyoucanpostquestions.Youwillmostlikelyfindquestionspostedbyotherpeoplewhoarehavingthesameproblemasyou.
DIGGINGINTOTHECODE
HopefullyyounowhaveyourcodeuploadedandrunningonyourArduinoUno.Butwhatisthecodeactuallydoing?YouknowthattheArduinoUnoisturningonandofftheLEDnextto13,buthowdoesitknowtodothat?
Agreatwaytostartlearningaboutcodeisbyreadingitbeforeyouwriteit.Afterall,youdidn’tlearnhowtowriteinschoolbeforeyoulearnedhowtoread!YoucanusetheBlinkasanintroductiontocode.Don’tworryaboutunderstandingallthedetailsrightaway—it’salottolearn.Youwillbeshownabunchofnewterms,butyoudon’tneedtorememberwhattheyallmeanrightaway.Youwillgettospendmoretimeunderstandingthemintheotherchapters.
IfyoulookagainattheBlinksketchonthescreen,you’llseethatthefirstsectionisallingrey.TheArduinoIDEhelpsyouunderstandwhatishappeninginthecodebychangingthecolourofthecodeaccordingtowhatitdoes.Thetextthatturnsgreyiscalledacomment.Commentsarenotestotheprogrammertohelpexplainwhatishappeninginthecode.Thelongcommentatthetopofthesketchexplainswhatthesketchdoes:
Commentsarenoteswithinyourcodethatexplainwhatalineorsectionofcodeisintendedtodo.Eachcommentlinebeginswith//or,ifyouwanttowriteacommentthatspansmultiplelines,isbetween/*and*/.Thesespecialcharacterstellthecomputerrunningtheprogramtoignorethatlineorlines.
/*
Blink
TurnsonanLEDonforonesecond,thenoffforonesecond,
repeatedly.
MostArduinoshaveanon-boardLEDyoucancontrol.OntheUnoand
Leonardo,itisattachedtodigitalpin13.Ifyou’reunsurewhat
pintheon-boardLEDisconnectedtoonyourArduinomodel,check
thedocumentationathttp://arduino.cc
Thisexamplecodeisinthepublicdomain.
modified8May2014
byScottFitzgerald
*/
Therestofthelinesthatdon’tstartwith//arelinesofcodethatthecomputerwillexecute.Thelinesstartingwith//areignoredbythecomputerandarenotestoexplainwhatthecodeisdoing.
EveryArduinosketchhastohavetwofunctions:setup()andloop().Afunctionisasetoflinesofcodethathaveaname.Thenextsectionofcodeisthesetup()function,whichrunsonlyonceandisfortasksthatneedtohappenonlywhentheArduinoisfirstturnedon.WheneveryourArduinoUnofirststartsup,itlooksforthesectionofthesketchthatisthesetup()function,anditrunsthatsectionfirst.continuedcontinued
Afunctionisasetoflinesofcodethathaveaname.Afunctioncanbeusedoverandoveragain.Itmaytakesomeinformationasaninputandoutputmoreinformationwhenitisfinished,butnotallfunctionsneedtodothat.
//thesetupfunctionrunsoncewhenyoupressresetorpower@@ta
theboard
voidsetup(){
//initializedigitalpin13asanoutput.
pinMode(13,OUTPUT);
}
Asyoucansee,thereisonlyoneinstructioninsidethesetup()function—thefunctionpinMode().EverypinontheArduinocanreadininformationoroutputinformation,butitcan’tdobothatthesametime.ThepinMode()functionsetsupwhetherthepininputsoroutputsbytakingtwoarguments.Thefirstisthenumberofthepinyou’reusingontheArduinoboard.TheLEDontheArduinoUnoisconnectedtoPin13.Thesecondisaspecialkeyword,OUTPUT,whichtellstheArduinothatyouwanttooutputonPin13andnotreadinonthatpin.
Anargumentisapieceofinformationgiventoafunction,whichthefunctionthenusestoperformitstask.Theargumentgoesinsidethebracketsthatfollowthefunctionname.Inthefollowingcodesnippet,forexample,thefunctiondelay(1000)hastheargument1000,whichisthenumberofmillisecondsyouwanttheArduinotowaitbeforeexecutingthenextline.
TheremainingcodeintheBlinksketchistheloop()function.AftertheArduinoUnoexecutesallthecodeinthesetup()function,itlooksforafunctioncalledloop().Itthenexecutesallthecodeinthatfunction.Whenitisdone,itexecutesallthecodeintheloop()functionagain.Andthenagain!Andonandon!Theloop()functionrepeatsforever(oratleastuntiltheArduinoUnonolongerhaspower).
//thelooproutinerunsoverandoveragainforever
voidloop(){
digitalWrite(led,HIGH);//turntheLEDon
(HIGHisthevoltagelevel)
delay(1000);//waitforasecond
digitalWrite(led,LOW);//turntheLEDoff
bymakingthevoltageLOW
delay(1000);//waitforasecond
}
Thefirstlineofcodeintheloop()functionturnsontheLEDusingthefunctiondigitalWrite().Ittakestwoarguments:thepinnumberandwhetheryouareturningtheelectricityonoroff.TheargumentforthepinnumberisjustlikewhatyousawwithpinMode().Thesecondargumentisakeyword:HIGHorLOW.HIGHturnsontheelectricity,andLOWturnsitoff.
Thelastpieceofcodethatyouhaven’tlookedatisthedelay()function.TheArduinoboardrunsthiscodeveryfast—millionsoftimesasecond.That’ssofastthatyouwouldn’tbeabletoseetheLEDturnonandoff.SoyouneedtomaketheArduinopausesothatyoucanseethelightblink.ThedelayfunctionmakestheArduinowaitforthenumberofmillisecondstypedastheargument.Inthisexamplethedelayis1000milliseconds,whichisequalto1second.Here’sareviewofwhatthewholesketchdoes:
1. ThesetupfunctionusesthepinModefunctiontosetthepintheLEDisontobeanoutput.
2. Intheloop()function,theelectricityontheLED’spinisturnedon.3. TheArduinoispausedfor1000milliseconds.4. TheelectricityontheLED’spinisturnedoff.5. TheArduinoispausedfor1000milliseconds.6. Theloop()functionstartsoveragain.
Onelastdetailyoumighthavenoticedisthatcodehassomestrangepunctuation.Mostofthelinesendwitha
semicolon(;).Thisislikeafullstopattheendofasentence.Afullstopindicateswhenasentenceisfinished—itkeepswritingneatandtidy.Asemicolondoesthesamethingforacomputer.Ithelpsthecomputerseparatedifferentlinesofcode.
Youmayhavealsonoticedthatthecodehasspacesandindentation.Thesearelikecomments—theymakethecodeeasiertounderstandfortheprogrammer.Thecomputerjustignoresthem.Theindentationmakesiteasiertoseewhatlinesofcodebelongtoafunction.Youmighthavenoticedthatthelinesofcodethatbelongtoloop()areallbetween{and}andareindented.The{and}tellthecomputerthatthosearethelinesthatbelongtoloop(),whereastheindentationmakesthatmorevisuallyobvioustoreader.
Thespacesinbetweenpartsofcodearealsoonlyfortheprogrammer;thecomputerignoresthem.Forexample,delay(1000)anddelay(1000)arethesametothecomputer,butthespacescanmakeitalittleeasierforsomepeopletoreadthecode.Youcandecidehowyouprefertowriteyourcodeinthefollowingchapters!
CHALLENGE
TrychanginghowlongtheLEDturnsonandoffbychangingtheargumentsinthedelay()functions.RememberyouneedtouploadyourcodeaftereachtimeyouchangeitinorderforthesketchwiththenewchangestobeontheArduinoUno.
BuildinganLEDCircuitNowthatyouhaveanLEDblinkingontheArduinoUno,youarereadytogobeyondtheUno’sboardandbuildyourfirstcircuit!Youwillusefirstbecomefamiliarwiththetoolsyouwillusetobuildandtestnewcircuits:circuitschematicsandbreadboards.Theyarethekeystocreatingyourownprojectsthatyoucansharealongwithbeingabletobuildprojectsdesignedbyother.Inthenextchapteryouwillgoastepfurtherandbuildahousingforyourcircuit,butit’sagoodideatofirstbecomecomfortablewithhowyourcodeandcircuitcometogetherontheArduinoUno.
WhatYouNeedYouneedthefollowingthingstobuildyourLEDcircuit.Figure1-12showstheelectroniccomponentsyouneed.
AcomputerAnArduinoUnoAUSBcableAbreadboard1220Ωresistor1LED2jumperwires
FIGURE1-12Theelectroniccomponentsyouneedtobuildthecircuit
UnderstandingCircuitSchematicsElectricityistheflowofelectricalcharge.You’veseenitinnaturethroughlightningorstaticelectricitythatoccurswhenyouwalkacrossacarpetedfloorandthentouchadoorhandle.Youalsousecircuitseverydaytocontrolhowelectricityisallowedtoflow.Youturnonandoffthelightsinaroomwithalightswitch.YoucanturnonaTVandchangethechannel.Thisisalldonebyusingcircuitstocontrolelectricity.You’renotreadyyettobuildthekindofcircuitsthatareinsideaTV,butyoucanbuildacircuitthatturnsonandofflights!
Evenasimplecircuitcanbebuiltinmanydifferentways.Forexample,LEDscomeindifferentsizesandcolours.YoucouldpoweranLEDfromanArduinoUnoorwithabattery.Acircuitschematicissimplyadiagramshowingtheimportantinformationaboutacircuit,usingsymbols.Figure1-13isacircuitschematicshowingthecircuitthatyouarenowgoingtobuild.TherearethreesymbolsintheschematiceachrepresentingtheArduinoUno,theresistor(moreaboutwhatthatisalittlelater)andtheLED(thetriangularsymbol).YoucouldbuildthecircuitusingalargeredLEDorasmallgreenLED;it’syourchoice.TheimportantinformationisthatyouareconnectingthatLEDtoanArduinoUnoandaresistor.
FIGURE1-13ThecircuitschematicfortheLEDcircuit
Electricitycanbedescribedandmeasuredindifferentways.Becauseit’sinvisible,itcanbehardtoimaginehowelectricityworks,sowaterisoftenusedasananalogy.Theflowofelectricityinawireislikewaterinapipe.Thewaterflowmovingthroughthepipeissimilartotheelectricalcurrent(measuredinamps,whichisabbreviatedA),andthewaterpressureisliketheelectricalvoltage(measuredinvolts,whichisabbreviatedV).Thesize
ofthepipeincombinationwithhowmuchwaterisbeingmovedthroughitaffectsthewaterpressure.Asmallerpipecreatesmorewaterpressurethanalargerpipewhenthesameamountofwaterispassedthroughboth.Thesizeofthepipedescribesthethirdpropertyusedtodescribeelectricity:resistance(measuredinOhmsrepresentedandrepresentedwiththesymbolΩ).
Thatmayseemcomplicatedanddifficulttounderstand,butdon’tworryaboutgraspingallthedetailsnow.Byworkingwithelectricityandbuildingcircuits,you’llfigureouthowvoltage,currentandresistancearerelated.Backtothecircuitschematic!
Thestudyofelectricityandcircuitsiscalledcircuittheory.Ifyouareinterestedinlearningmoreaboutcircuittheory,therearegreattutorialsonlinetogetyoustarted.IreallylikeSparkfun’s.Theyhaveanimationstohelpillustratetheconcepts!Startwithhttps://learn.sparkfun.com/tutorials/what-is-electricityandhttps://learn.sparkfun.com/tutorials/voltage-current-resistance-and-ohms-law.
IntheschematicinFigure1-13,thecircuitisconnectedtoPin13andGNDontheArduino.Pin13iswheretheelectricitythatlightsuptheLEDflowsfrom.GNDstandsforgroundor0V.Whenyouuseabatterytopoweracircuit,thebatteryhastwoterminals:positiveandnegative.Electricityflowsfromthepositivetothenegative.Pin13andGNDontheArduinoUnoplaythesameroleasthepositiveandnegativeterminalsofthebattery.ElectricityflowsfromPin13toGNDwhentheyareconnectedinacircuit.
ThecircuithastwocomponentsbesidestheArduinoUno:aresistorandanLED.ThepinsontheArduinoUnoalloutput5V,whichistoomuchfortheLED.Rememberthewateranalogy?ThinkoftheLEDlikeadrinkingstraw.It’snotasstrongasapipe,soforcingtoomuchwaterintoitcancausethestrawtoburst.AresistorhelpstocontrolhowmuchcurrentcanflowthroughtheLED.Inthiskindofcircuit,theresistorlimitstheamountofcurrent,soisknownasacurrent-limitingresistor.
Aresistorisanelectricalcomponentthatresistscurrentinacircuit.Forexample,LEDscanbedamagedbytoomuchcurrent,butifyouaddaresistorwiththecorrectvaluetotheLEDcircuittolimittheamountofcurrent,theLEDisprotected.ResistanceismeasuredinOhms(representedbyΩ).Youneedtopickaresistorwiththecorrectvaluetolimitthecurrentthroughacircuit;thevalueofaresistorisshownbycolouredbandsthatarereadfromlefttoright.
UsingaBreadboardAfteryouknowwhatcircuityouarebuilding,youneedtousesomethingcalledabreadboardtohelpyoubuildit.Abreadboardisaboardwithrowsofholesonit(seeFigure1-14).Ifyoucouldpeekinsidetheplasticcaseofthebreadboard,youwouldseethattheholesineachrowtouchthesamepieceofmetal.Stickingtwowiresinthesamerowmeanstheyaretouchingthesamepieceofmetal,andelectricitycanflowbetweenthem.
Abreadboardisareusabledevicethatallowsyoutocreatecircuitswithoutneedingtosolderallthecomponents.Breadboardshaveanumberofholesintowhichyoupushwiresandcomponentstocreatecircuits.
FIGURE1-14Abreadboardhasaseriesofholesthatareconnectedinrowswithtwopairsoflongrowsontheoutsideandshorter,perpendicularrowsinthecentreoftheboard.
Thelongrowsontheoutsideedgesoftheboardarewhereyoucanconnect5Vandground(GNDontheArduinoboard).Someboardsmaycomewithlabelslike+or-orcolourslikeredandblackorblue.Redisacolourusedtorepresentthepositivevoltage,sowiththeArduinoUnothatwouldbe5V.BlackorblueisusedtorepresentgroundorGNDontheArduinoUno.
Youcanthinkofthelongrowsfor5Vandgroundasexpansionsforthe5VandGNDpinsontheArduinoUno.Thereisonlyone5VpinontheArduinoUno,sowhatifyouhavemorethanonecomponentthatneedstoconnectto5V?Byusingajumperwire,youcanconnect5Vtoarowonthebreadboard.Youthenhavemanyholeswherecomponentscanconnectto5V.It’sthesameforground.TherearemoreGNDpinsontheArduinoUno(therearethree,andtheyalldothesamething,soyoucanuseanyofthemwheneveryouneedtoconnecttoground),butyoucanalsouseajumperwiretoexpandthenumberofgroundconnectionsonthebreadboard.Figure1-15showshowyoucandothis.
FIGURE1-15Basiclayoutofabreadboard
Therowsinthemiddleofthebreadboard,betweenthelongoutsiderows,arewhatyouusetoconnectyourcomponentstoeachother.Ifyoucouldseeinsidetheplasticcaseofthebreadboard,youwouldseethattheserowsareperpendiculartothelongrowsontheedges.Theholesareingroupsoffiveanddon’tconnectacrossthegapinthemiddleofthebreadboard.
BuildingYourFirstCircuitYouarenowreadytobuildyourLEDcircuitusingyour220-OhmresistorandLED.AnLEDisdirectional—thatmeansyoucanaccidentallyputitinacircuitbackwards.IfyoulookattheLEDclosely,youcanseethatthetwolegsaren’tthesamelength.ThelonglegoftheLEDshouldconnecttothepositiveor5Vportionofthecircuit,andtheshortlegshouldconnecttoground.Theresistorisn’tdirectional,sobothlegsarethesamelength,anditdoesn’tmatterwhichlegisconnectedtowhichpartofthecircuit.
GothroughthefollowingstepstobuildthecircuitinFigure1-16:
1. ConnectoneendofajumperwiretooneoftheGNDpinsontheArduinoandtheotherendtoalongrowonthebreadboard.ThisistheblackwireinFigure1-16,butyourjumperwirecanbeanycolour.
2. Putonelegoftheresistorintoanyoftheshortrowsinthemiddleofthebreadboard.3. Puttheotherlegintoanothershortrowinthemiddleofthebreadboard.Itjustcan’t
beinthesamegroupoffiveholesastheotherleg!4. PutthelonglegoftheLEDintoaholeinthesamerowasoneofthelegsofthe
resistor.Theyarenowtouchingthesamepieceofmetalinsidethebreadboard,soelectricitywilleventuallybeabletoflowthroughtheresistorandthenthebreadboardrowandthentheLED.
5. ConnecttheshortlegoftheLEDtothelongrowofthebreadboardwherethejumperwireisconnected.
6. UseasecondjumperwiretoconnectfromPin13tothesameshortrowasthelegoftheresistorthatisn’tconnectedtotheLED.
FIGURE1-16TheLEDcircuitonthebreadboard
Don’teverconnectthe5VandGNDpinstogetherwithoutacomponentlikearesistororLEDinbetweenthem.ThiscreatesashortcircuitandcandamageyourArduinoUno.Ifyoueverdothisby
accident,yourcomputerwillprobablynoticethatsomethingiswrongonyourArduinoUnoandwillcutoffthepowerfromthecomputertotheUno.Ifthishappens,justunplugtheArduinoUnofromthecomputerandthenplugitinagain.
YourLEDshouldnowblinkonandoffonthebreadboard,justliketheLEDdidontheArduinoboard.Congratulations!You’vebuiltyourfirstArduinocircuit!Yourcodeiscontrollingelectricityandwhetheralightisonoroff.ThisisjustthebeginningofyourjourneytobuildsomeexcitingArduinoprojects.
Visitthecompanionsiteatwww.wiley.com/go/adventuresinarduinotoseeavideoshowinghowtobuildthiscircuit.
CHALLENGE
ChangethepinnumberthatyourLEDcircuitisconnectedto.Youcanuseanyofthepinsfrom2to13onthesectionoftheboardlabeledDigital,showninFigure1-17.Theotherpinshavespecialfunctionsthatyoulearnaboutinthenextadventure.
Remember,youneedtomakeachangeinyourcode(andremembertouploadyourchangetoyourArduinoboard),andyouneedtomakeachangetothecircuit.
FIGURE1-17ThedigitalpinsontheArduinoboard.DigitalPins0and1arespecialpinsthatyoulearnaboutlater.
FurtherAdventureswithArduinoCongratulations!Youhaveachievedalot.Itmightseemlikethatwasalotofworkjusttogetasinglelighttoflashonandoff,butitmeansyouarereadyforallkindsofadventures.
Checkoutprojectsthatothershavedonetogetsomeinspirationforwhatispossible:
http://makezine.com/category/electronics/arduino/
www.creativeapplications.net/tag/arduino/
ArduinoCommandQuickReferenceTable
Command Description
setup() FunctionthatrunsoncewhentheArduinoUnofirststarts.Seealsohttp://arduino.cc/en/Reference/Setup.
loop()Functionthatisrepeatedlyrunafterthesetup()iscompletedanduntiltheArduinoisturnedoff.Seealsohttp://arduino.cc/en/Reference/Loop.
pinMode()Setsthepinnumberenteredastheargumenttoeitheroutputelectricityorreaditin.Seealsohttp://arduino.cc/en/Reference/PinMode.
OUTPUTKeywordsetinsecondargumentofpinMode()thatsaysthepinwilloutputelectricity.Seealsohttp://arduino.cc/en/Reference/Constants.
digitalWrite() Turnsonorofftheelectricityatthespecifiedpin.Seealsohttp://arduino.cc/en/Reference/DigitalWrite.
HIGHKeywordusedtoturnontheelectricityindigitalWrite().Seealsohttp://arduino.cc/en/Reference/Constants.
LOWKeywordsuedtoturnofftheelectricityindigitalWrite().Seealsohttp://arduino.cc/en/Reference/Constants.
delay()PausestheArduinoUnoforaspecifiednumberofmilliseconds.Seealsohttp://arduino.cc/en/Reference/Delay.
AchievementUnlocked:Youaremakingalltherightconnectionsandshiningbright!
IntheNextAdventureInthenextadventure,youstartaddinginteractivitytoyourArduinocodeandcontrolLEDsusingadial!
YOUNOWHAVEtheArduinosoftwareinstalledandhaveuploadedyourfirstsketchtomakesureeverythingissetupcorrectly.(Ifyouhaven’tdonethat,itwouldbebesttogotoAdventure1anddothatnow!)It’sgreattellingtheArduinotocontrolsomethinglikeflashinglights,buttherealfunwithArduinostartswhenyourprojectsbecomeinteractive.Thereareacouplethingsthatneedtohappenbeforeaprojectcanbecomeinteractive:firsttheArduinoneedstoknowsomethingaboutwhatishappeningintherealworld;thentheArduinocodeneedstodosomethingbasedonthatinformation.
You’regoingtotravelalongwayinthisadventure!YoustartbycontrollingmultipleLEDsandthenyouprintsomemessagesfromtheArduinotothecomputer.Afterthat,youreadininformationfromasensorandprintthatinformationtothecomputer.Finally,youputallofthatknowledgetogethertobuildaterrificstatusmessagesign,whichwillhavemultiplemessagesandacontrolknobyoucanturntochoosewhatmessageyouwanttodisplay—perfectforwelcomingorsendingawayvisitorsatyourwhim.
WhatYouNeedYoufirstfindouthowtoaddmoreLEDstoyourcircuitandthenhowtouseasensorcalledapotentiometer.Thefollowinglisttellsyouwhatyouneed,andFigure2-1showstheelectroniccomponents.Remember,AppendixBincludessuggestionsofwhereyoucanbuyeverything.
AcomputerAnArduinoUnoAUSBcableAbreadboard3LEDs(1green,1yellow,1red)3220Ωresistors110kΩpotentiometer4jumperwires
FIGURE2-1Theelectroniccomponentsyouneedforthefirstpartofthisadventure
AddingMoreLEDsInChapter1,youbuiltacircuitonabreadboardsothattheArduinocontrolledasingleLED.OneLEDisgreat,butmoreLEDsareevenbetter!SowhatdoyouneedtodotoaddmoreLEDs?
ThefirstthingyouneedismoreLEDs—thisadventureusesthree.Youalsoneedthree220Ωresistors,aseachLEDneedsitsowncurrent-limitingresistor.Resistorshelpcontroltheflowofelectricityinacircuit.Inthiscircuit,theresistorsprotecttheLEDsfrombecomingdamagedfromtoomuchcurrent.YoucanreadmoreaboutcurrentandresistorsinAdventure1.
StartbybuildingthecircuitshowninFigure2-2:
1. Putonelegofoneoftheresistorsinashortrowonthetophalfofthebreadboardtowardstheleftsideoftheboard.Puttheotherlegoftheresistorintheshortrowacrossthegapinthemiddleofthebreadboarddirectlybelowwhereyou’veinsertedthefirstresistorleg.Therowsofthebreadboardaren’tconnectedacrossthegap,soeachresistorlegisinitsownrow;theyaren’ttouchingthesamepieceofmetalinsidethebreadboard.
2. Repeatwiththesecondandthirdresistors.Placeoneresistorinthecentreofthebreadboardandtheothertowardstherightsideofthebreadboard.Eachresistorshouldreachacrossthegapinthemiddleoftheboardandhaveoneleginashortrowabovethegapandtheotherinashortrowbelowthegap.
3. NowaddtheLEDs.ThelonglegofeachLEDconnectstotheresistorandtheshortlegconnectstoground.InsertthelonglegofeachLEDintothesameshortrowaseachresistor.Itshouldbeplacedjustbelowtheresistor.PlacethegreenLEDontheleftsideofthebreadboard,theyellowinthemiddleandtheredontherightside.
4. InserttheshortlegofeachLEDintooneofthelongrowsrunningtheentirelengthofthebreadboardattheverybottom.Ifyourbreadboardislabelledwithablueorblacklineora-,insertthethreeshortlegsintothatrow.Ifyourbreadboardisn’tlabelledthenyoucanuseeitherrow—justmakesureallthreeofthelegsareinthesamerow.
5. Yourcircuitisnowbuiltonyourbreadboard.AllthatisleftistoconnectittoyourArduinoUno.UseonejumperwiretoconnectfromaGNDpin(therearethreeofthemontheArduinoUnoandyoucanusewhicheveryouwouldlike,theyareallthesame)tothelongrowonthebreadboardwhereyourthreeshortLEDlegsareinserted.
6. Usingthreemorejumperwires,connectonewirefromPin5ontheArduinoUno(notA5,butthe5inthesectionlabelledDigital)tothetopoftheresistorontheleftsideofthebreadboardconnectedtothegreenLED.UseasecondjumperwiretoconnectPin6tothemiddleresistorconnectedtotheyellowLED,andathirdjumperwiretoconnectfromPin7tothelastresistorconnectedtotheredLED.
FIGURE2-2BuildingacircuittocontrolthreeLEDs
Finished?Nowyou’rereadytowritethecode.It’sgoingtolookalotliketheBlinksketchdescribedinAdventure1.YouusecodetocontrolwhenanLEDturnsonandoff.ThebigdifferenceisthatyoustartusingvariablestokeeptrackoftheLEDs,andyouneedtocontrolthreeLEDsinsteadofonlyone.Youreadmoreaboutvariablesinthenextsection.
First,launchtheArduinoIDE.Itopensanewsketchwindowwhentheprogramstarts.YoucanalsogotoFile⇒NeworclicktheNewbuttontocreateanewemptysketch.Typeinthefollowingsketchexactlyasitiswritten.Thespacesandindentationaren’timportant;theyjustmakethecodeeasiertoread.However,don’taccidentallyleaveoffa;oryourcodewon’trun!Don’tforgettosaveitbygoingtoFile⇒SaveorclickingtheSavebutton.//Pins
intgreenLED=5;
intyellowLED=6;
intredLED=7;
voidsetup(){
//settooutputtoLEDpins
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
}
voidloop(){
//turnonallLEDs
digitalWrite(greenLED,HIGH);
digitalWrite(yellowLED,HIGH);
digitalWrite(redLED,HIGH);
//wait1second
delay(1000);
//turnoffallLEDs
digitalWrite(greenLED,LOW);
digitalWrite(yellowLED,LOW);
digitalWrite(redLED,LOW);
//wait1second
delay(1000);
}
Typingthesketchesbyhandisagoodwaytobecomemorecomfortablewithallthenewcodingtermsyouarelearning,butitcanbefrustratingifit’sareallylongsketchoryou’vemadeatypothatyoucan’tfind.Forthosecases,allthesketchesareavailabletodownloadfromcompanionsitewww.wiley.com/go/adventuresinarduino.
Afteryouhavefinishedtypingoutthesketchandhavesavedit,youarereadytouploadittoyourArduinoUno.Selecttheboardandportfromthemenus(youcanreviewhowtodothisinAdventure1).ClicktheUploadbuttonandwatchformessagestoappearatthebottomofthewindowoftheArduinoIDE.
Iftherearen’tanyerrors,yourthreeLEDsshouldstartflashingonandoff!That’ssomuchmoreexcitingthanblinkingjustoneLED.
Ifyouseeanyerrorsthatsay“Expectedinitializerbefore'void'”or“expected';'…”thenyouprobablyhaveatypo.Lookcarefullyoveryourcodeandmakesureitmatcheswhatyouaresupposedtotypein.Ifthereareanyerrorsfromavrdude,checkthatyourArduinoUnoispluggedintoyourcomputerandthatyou’vechosenthecorrectoptionsfromtheBoardandPortmenus.Ifyoustillhaveproblems,gobackthroughAdventure1tomakesureyoursoftwareisinstalledcorrectly.
DIGGINGINTOTHECODE
Nowthatyouhaveseenwhatthecodedoes,it’stimetofigureouthowit’sdoingthat!Thesketchcanbebrokenupintothreesections:thelinesbeforethefunctions;thesetup()function;andtheloop()function.
First,thelinesofcodebeforethefunctions.
//Pins
intgreenLED=5;
intyellowLED=6;
intredLED=7;
Thefirstlinebeginningwith//isacommentexplainingwhatthefollowinglinesmean.ThenextthreelinesarevariablesassignedthepinnumbersforeachoftheLEDs.Avariableislikegivingsomethingincodeaname.Hereit’sgivinganametothepinnumberstomakeiteasiertorememberwhichLEDisconnectedtoeachpin.ThenamegreenLEDismuchmoreobviousthatthenumber5,isn’tit?
Avariableisacodeconstructthatholdsavaluethatcanbechanged.Forexample,thevariablegreenLEDstoresthenumber5.
Infrontofeachofthevariablenamesisint.Thisisdescribingwhatkindofdatacanbestoredinthevariable.intisshortforinteger,sothevariablescanstoreonlywholenumbers.
Althoughgivingsomethinganameisconvenient,variablesbecomereallypowerfulwhenthevariablechangesitsvaluebutkeepsthesamename.Thatfeatureofvariablesisn’tbeingusedhere,butitisinthenextsection.
Thereafewrulestokeepinmindwhencreatingnewvariablenames.Thefirstisthattheycan’thavespacesinthem,butyoucanuseunderscores(greenLEDandgreen_LEDarefine,butgreenLEDisnot).Youalsocan’tstartthenamewithanythingbesidesaletter(led3isfine,3ledisnot).Lastly,it’snotarequirement,butvariablesusuallystartwithalowercaseletter(greenLEDratherthanGreenLED).
Thenextpartofthesketchisthesetup()function.ThisfunctioniswhattheArduinoUnorunsrightwhenitstartsup.Itisonlyrunthatonetime,sothisfunctionisforcommandsthatneedtobedoneonlyonce.Themostcommonthingdoneinthesetup()istosetthepinMode()ofpinsbeingused.ThepinMode()determineswhetherthepinwilloutputelectricitytocontrolacomponentlikeanLEDoritwillreadinasignalfromasensor.
Thiscircuitdoesn’thaveanysensors—onlyLEDs—sothepinMode()issettoOUTPUTforeachofthepins.Becausevariablesarebeingusedtorepresentthepinnumbers,theirnames(greenLED,yellowLEDandredLED)canbetypedinsteadof5,6and7.
voidsetup(){
//settooutputtoLEDpins
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
}
Thefinalsectionofcodeistheloop()function.ThisfunctionisexecutedrepeatedlyuntiltheArduinoUno’spowerisremoved.
Theloop()functionusesonlytwootherfunctions:digitalWrite()anddelay().ThedigitalWrite()functionturnsonoroffanLED.ThefirstargumentdetermineswhichLEDisbeingtalkedabout,andthesecondargument
determineswhatistobedone—eitherturnontheLEDiftheargumentisHIGHorturnitoffiftheargumentisLOW.
Tosummarisewhattheloop()does,itturnsoneachLED,thenwaitsfor1secondsoyoucanseethemon,thenitturnsoffeachLEDandwaitsfor1secondsoyoucanseethattheyareoff.
voidloop(){
//turnonallLEDs
digitalWrite(greenLED,HIGH);
digitalWrite(yellowLED,HIGH);
digitalWrite(redLED,HIGH);
//wait1second
delay(1000);
//turnoffallLEDs
digitalWrite(greenLED,LOW);
digitalWrite(yellowLED,LOW);
digitalWrite(redLED,LOW);
//wait1second
delay(1000);
}
CHALLENGE
NowyouhavethreeLEDsthatallblinktogether,makethemlightupinasequenceonebyone.Youwon’tneedtochangethecircuit;youchangeonlythecode.RemembertouploadyourchangesinyourcodetotheArduinoUno.
Afewhints:
Youdon’thavetowritemoredigitalWrite()functions;youonlyneedtomovearoundtheonesalreadywritten.Youneedtoaddmoredelay()functions.
PrintingMessagestotheComputerAfteryouuploadcodeontotheArduinoUno,theboarddoesn’ttalktothecomputer.Infact,itdoesn’tneedthecomputeratall.Theonlythingthat’shappeninghereisthattheArduinoUnoisgettingitspowerfromthecomputer,viatheUSBcablepluggedintothecomputer.Youcouldevenunplugitfromthecomputeranduseabattery.(YoucanfindinformationaboutpoweringtheboardwithabatteryinAdventure5.)ButyourcomputercanstillbeusefulafteryouhaveuploadedyoursketchontotheArduinoUno.Forexample,theArduinoUnodoesn’thaveascreen,butthecomputerdoes.Soifyouaredebuggingyourcode,orjustwanttoreadmessagestoknowwhattheboardisdoing,thecomputerandUSBcablecanbeapowerfultool.
Debuggingisthewhereyoulocatethecauseofanyerrorsinyourcomputerprogramcodeandfixthem.
TheArduinoUnocantalkwiththecomputerusingserialcommunicationovertheUSBcable.Thisjustmeansthatonebitofdataissentatatime.Youcanthinkofitasoneletterofawordbeingsentatatime,eventuallytospelloutawholeword.TosenddatafromtheArduinotothecomputer,therearejustthreefunctionsyouneedtoknowabout.
Serialcommunicationisonewaythattwodevices,likeacomputerandanArduinoboard,cansendandreceivedatatoeachother.Onepieceofdataissentatatime.
Thefirstfunctionisonethatyouonlyneedtocallonceinthesetup()function:Serial.begin(9600);
Thisfunctiontakesonlyoneargument:thespeedatwhichtheArduinoUnoissendingoutandreceivingdata.It’simportantthatthisnumberisthesameasthespeedthatthecomputerissendingandreceivingdata(youfindouthowtocheckthatlater).IfthecomputerandArduinoUnoaresendingandreceivingdataatdifferentspeeds,theywon’tbeabletounderstandeachother.Unlessyouareexplicitlytoldtouseadifferentnumber,9600isagoodnumbertouse.
Rememberthatyoucanalwayslookuptermsintheglossaryatthebackofthebook.
Theothertwofunctionsare:Serial.print("Yourmessagegoeshere");
Serial.println("Yourmessagegoeshere");
ThesearethefunctionsthatsendmessagesfromtheArduinoboardtothecomputer.The
firstone,Serial.print(),doesn’tsendanewlinecharacterattheendofthemessage;inotherwords,thecursorisn’tmoveddowntothenextlineattheendofthemessage.ThefunctionSerial.println()doesincludeanewline;youcanimaginethisasamessagewithanEnterattheendofit.
AnewlinecharacterislikepressingtheEnterorReturnkeyonyourkeyboard.
Thebestwaytounderstandthisistotryitout.There’snocircuitforthis;youjustneedtheArduinoboardpluggedintoyourcomputer.Createanewsketchwiththefollowingcodeanduploaditontotheboard:voidsetup(){
//tostartserialcommunication
//theargumentneedstomatch
//therateyouchooseinthe
//SerialMonitor
Serial.begin(9600);
Serial.println("Hello,thisisfromsetup");
//adelaysothatmessagesaren’ttooquicktoread
delay(3000);
}
voidloop(){
//printingamessageandthenwaitingasecond
Serial.print("Thisisfromloop,withaprint.");
delay(1000);
Serial.println("Andthisisfromloopwithaprintln.");
delay(1000);
intmyVariable=27;
Serial.print("Andthisisprintingavariable:");
Serial.println(myVariable);
delay(1000);
}
YoumayhavenoticedthatthemessagesyousendinSerial.print()andSerial.println()arebetweenquotationmarks("").Thisishowyouwriteincodeapieceoftextthatyoudon’twantthecomputertointerpretascode.Youcanprintthevalueofavariablebyreplacingthemessageandthe""withavariablename,suchasthevariablemyVariableinthesketch.
Afterthesketchisuploadedontotheboard,opentheSerialMonitorbyclickingthatlastArduinoIDEbutton—theoneIdidn’tcoverinAdventure1.It’sthebuttononitsownontherightinFigure2-3.Afteryouclickthebutton,awindowopensliketheoneshowninFigure2-4.Youmaynoticethatthenumber9600appearsinthebottomrightofthewindow(ifitdoesn’tyoushouldclickthenumberthatisthereandselect9600).ThisisthenumberthatneedstomatchtheargumentinSerial.begin()inyourArduinocode.
FIGURE2-3TheSerialMonitorbutton
FIGURE2-4TheSerialMonitorintheArduinoIDE
YouwillseethemessagesfromyourArduinoUnoappearinyourSerialMonitor.TheSerialMonitorisatoolbuiltintotheArduinoIDEthatletsyouseethemessagessentbytheArduinoUnousingserialcommunication.Youwillfinditaveryusefultoolinallofyouradventures!WhenyouaredonewiththeSerialMonitor,youcanjustclosethewindow.Itmayalsocloseonitsownwhenyouuploadanewsketchtoyourboard.YoucanreopentheSerialMonitortoseeanynewmessages.
DIGGINGINTOTHECODE
Sowhat’sgoingoninthecode?Therearethesectionsthatyouareprobablygettingusedto:thesetup()andloop()functions.Thesetup()functiondoesn’thavemuchgoingon.Thefirstfourlinesarecommentsexplainingwhatishappening.Theserialcommunicationisthenstartedandamessageissent:Hello,thisisfromsetup.TheArduinoUnoisthenpausedfor3seconds,justsothatmessagesdon’tprinttoofasttoread.
voidsetup(){
//tostartserialcommunication
//theargumentneedstomatch
//therateyouchooseinthe
//SerialMonitor
Serial.begin(9600);
Serial.println("Hello,thisisfromsetup");
//adelaysothatmessagesaren’ttooquick toread
delay(3000);
}
Theloop()functionthenprintsmessagesinthreedifferentways.ItfirstusesSerial.print()toprintThisisfromloop,withaprint.andthenwaitsfor1second.BecausethemessageusedSerial.print()andnotSerial.println(),thenextmessageappearsonthesameline,withthenewmessageprintingrightafterthepreviousone.There’sanother1-seconddelayandthenanewvariableiscreatedtoholdthenumber27.ASerial.print()functionprintsamessageandthenthevariableprintsattheendoftheline.Becausethevariableisprintedwithoutthesurroundingquotationmarks(not"myVariable"),thenumber27isprinted.
voidloop(){
//printingamessageandthenwaitingasecond
Serial.print("Thisisfromloop,withaprint.");
delay(1000);
Serial.println("Andthisisfromloopwithaprintln.");
delay(1000);
intmyVariable=27;
Serial.print("Andthisisprintingavariable:");
Serial.println(myVariable);
delay(1000);
}
Thesetup()functionisrunoncewhentheArduinoUnoisfirstturnedon,buttheArduinoUnocallsthesetup()functionacoupleothertimesbesideswhenitisfirstturnedon.Forexample,there’saresetbuttonontheboardthatyoucanusetomanuallyrestarttheboard,sothesetup()functioniscalledbeforegoingontotheloop()function.Also,wheneveranewserialconnectionismade,theboardrestarts.SowheneveryouopentheSerialMonitor,theArduinoboardrestartsandrunsthesetup()functionagain.YoumaynoticethishappeningwhenyouopentheSerialMonitor.Themessagebeingprintedgetsinterrupted,andthemessageinthesetup()functionstartsprintinginstead.TryopeningtheSerialMonitorandthenpressingtheresetbuttonontheArduinoUno.
ReadingDatafromaPotentiometerNowyou’rereadytotakeaphysicalactionintherealworldanduseittomakedecisionsincode.ThisisexactlywhattheArduinowasbuilttodo!YouwillsoonbeturningaknobtochangewhatLEDison.
You’regoingtostartbyusingapotentiometer.That’sabignameforasimplecomponent!It’ssimplyaresistorthatadjustshowmuchresistanceithasasyouturnacontrolknob—forexample,theknobyouuseonastereototurnupthevolume.Potentiometerscomeinlotsofshapesandsizes.Figure2-5showsafewpotentiometersthatchangetheirresistancethrougharotatingmotion.Thetwobiggeronescanhaveknobsordialsthatfitovertheendoftheshafts.Thelittleoneissometimescalledatrimpot,anditalreadyhasasmallknobattachedthatyouturn.TrimpotsliketheoneshowninFigure2-5workwellwhenbuildingcircuitsonbreadboardsastheyfitintothebreadboardholes.LargerpotentiometersliketheoneontherightinFigure2-5canalsofitintobreadboards.Potentiometersliketheoneinthemiddleareeasierforsolderingwiresto.
Apotentiometerisatypeofresistorwithanadjustableknobtovarytheresistanceofcurrent.
FIGURE2-5Differentpotentiometers
Visitthecompanionsiteatwww.wiley/go/adventuresinarduinotowatchavideoshowingdifferenttypesofpotentiometers.
ThecircuittoconnectthepotentiometertotheArduinoinvolvesthreeconnections.Youcanthinkofthepotentiometerashavingtwokindsofpins:apairofoutsidepinsandaninsidepin.TheinsidepiniswhatisconnectedtoanAnaloguePinontheArduino.TheAnaloguePinsarethesectionofpinsyouhaven’tyetused(seeFigure2-6).TherearesixpinsintotalandtheyeachstartwiththeletterA(A0,A1,A2,A3,A4andA5).
FIGURE2-6AnaloguepinsontheArduinoUno
It’stimetobuildyourfirstcircuitwithapotentiometer!GothroughthefollowingstepstobuildthecircuitinFigure2-7:
1. Useajumperwiretoconnect5VontheArduinoUnotooneofthelongrowsrunningalongthebottomofthebreadboard.Ifthebreadboardislabelledwitharedlineor+,connect5Vtothatrow;otherwise,chooseeitherrow.
2. UseanotherjumperwiretoconnectGNDontheArduinoUnototheotherlongrowonthebreadboard.
3. Insertthelegsofthepotentiometerintoanyoftheshortrowsinthemiddleofthebreadboard.
4. Useajumperwiretoconnectoneoftheoutsidelegsofthepotentiometertothelong
rowconnectedtoGNDontheArduinoUno.5. Useanotherjumperwiretoconnecttheotheroutsidelegsofthepotentiometertothe
longrowconnectedto5VontheArduinoUno.6. ConnectthemiddlelegofthepotentiometertopinA0ontheArduinoUno.
FIGURE2-7Circuitforconnectingapotentiometer
YoucanreadinavaluecomingfromthepotentiometerthatcorrespondstothepositionoftheshaftorknobonthepotentiometerandprintittotheSerialMonitor.Todothis,gotoFile⇒Examples⇒01.BasicsandopenthesketchAnalogReadSerial.ThenuploadthesketchtoyourArduinoUno(rememberingtosettheboardandportasyoudidinAdventure1andearlierinthisadventure).
Whenyou’vefinished,clicktheSerialMonitorbuttontoopentheSerialMonitor.Rotatethepotentiometerallthewaytotheleftandthenallthewaytotheright.YoushouldseenumbersdisplayedintheSerialMonitor,rangingfrom0atoneendto1023attheother.ThesearetheminimumandmaximumnumbersthattheArduinocanreadinfromananaloginput.Whenthenumberis0,thepinisreadinginground(0V).Whenit’s1023,itmeansthatthepinisreadingin5V.Anynumberinbetweenmeansthatitisreadinginavoltagethat’ssomewherebetweengroundand5V.5VisthemaximumvoltagethattheArduinoUnooutputsand0Vistheminimum,sothiscircuitmeasureswhetherthepotentiometerisallthewaytotheleftorrightbymeasuringwhetherthevoltagethepotentiometerisoutputtingisthemaximum,minimumorsomethinginbetween.
DIGGINGINTOTHECODE
Sowhatishappeninginthecode?There’sonelineofcodeintheAnalogReadSerialsketchthatyouhaven’tseenbefore:
intsensorValue=analogRead(A0);
Thislinereadsinthevalue(orvoltage)beingoutputbythepotentiometercircuittoPinA0usingthefunctionanalogRead().Thisfunctiongivesyounumberbetween0and1023.Youneedtosavethisvalueintoavariablesothatyoucandosomethingwiththisnumberlater.Anewvariable,sensorValue,iscreated,andthenumberthatanalogRead()readsinissavedinthatvariable.ThatvariableisthenprintedtotheSerialMonitor.
YoumighthavealreadynoticedthatArduinousesAmericanspellingsforwordslike“analog.”It’simportanttorememberthisasanArduinoUnodoesn’tknowwhatanalogueRead()means,onlyanalogRead().
CHALLENGE
Switchtheoutsidepinsonthepotentiometersothattheonethatwasconnectedto5Visnowconnectedtoground,andtheonethatwasconnectedtogroundisnowconnectedto5V.Youdon’tneedtochangeanyoftheArduinocode.
Whatchangeswhenyouhavethecircuitsetupthiswayasopposedtohowit’swiredinFigure2-7?
MakingDecisionsinCodeTobuildinteractiveprojects,youneedtobeabletotakeinputfromtherealworldandthenhavetheArduinoUnodowhatyouwantaccordingtothatinput.Thatmeansyouneedtousecodetomakedecisionsbasedonincominginformationfromsensors.Forexample,ifyouwerebuildingaburglaralarm,youwouldwanttosoundthealarmonlyifthealarmeddoorwasopen,soyouneedtoknowhowtoexplainthatincode.
Computersworkbyansweringyesornoquestions.Thoseyesornoquestionsneedtobephrasedlikethis:
Is3greaterthan5?Is10equalto10?Is4lessthanorequalto8?
Writtenincode(sothatthecomputerunderstandsit)thesequestionswouldlooklikethis:3>5
10==10
4<=8
ThecomputerorArduinoUnocanthendodifferentthingsbasedonwhethertheanswertothequestionisyesorno(ortrueorfalse).Itdoesthisbyusingifstatements.Iftheanswertothequestioninthe()isyes,thenthecodebetweenthe{and}isexecuted:if(a<b){
//thenexecutethecodeinhere
}
Iftheanswerisno,thenthecodeinthe{}isskipped.
Forexample,thefollowingcode:if(3<5){
Serial.println("Thestatementistrue.");
}
Serial.println("Thisisaftertheifstatement.");
wouldprintthefollowing:Thestatementistrue.
Thisisaftertheifstatement.
Butthefollowingcode:if(3<1){
Serial.println("Thestatementistrue.");
}
Serial.println("Thisisaftertheifstatement.");
wouldprint:Thisisaftertheifstatement.
It’salwayseasiertounderstandanewconceptbybuildingsomethingyourselfandseeinghowitworks.Inthenextsection,you’regoingtouseifstatementsinaprojecttocreatea
statusmessagesign.
BuildingaStatusMessageSignHaveyoueverseenarecordingstudio,eitherinreallifeoronaTVprogramormovie?Thereisusuallyasignontheoutsideoftheroomthatsays“RECORDING”thatlightsuptoletpeopleknownottoenterbecausethere’sarecordingsessioninprogress.
Youaregoingtobuildyourownsignthatletsotherpeopleknowwhethertheycanenter,knockfirstorstayout.(Ifyoudon’twanttousethesignssuggestedhere,feelfreetomakeupthreedifferentmessagesthatareentirelyyourown.)EachmessagehasanLEDnexttoit.ThelightedLEDindicateswhichmessageistheactiveone.Yousetwhichmessageyouwanttobeactivewithacontrolknobonthesideofthesign,asshowninFigure2-8.
FIGURE2-8Astatusmessagesign
WhatYouNeedForthisadventureyoubuildyourfirstprojectwithitsownhousing.Youneedthefollowingtoolsandmaterialstofirstbuildandtestthecircuitonabreadboardandthenalsothetoolsandmaterialstobuildthecompleteproject.Figure2-9showstheelectroniccomponentsthatyouneed.
AcomputerAnArduinoUnoAUSBcableAbreadboard3LEDs(1green,1yellow,1,red)3220Ωresistors110kΩpotentiometer8jumperwiresSomewireSomeelectricaltapeSomesolderAshoeboxorothersmallboxPaperorpainttodecoratetheboxScissorsorautilityknifeAsolderingironWirecuttersWirestrippersUSBpowersupply(optional)
FIGURE2-9Theelectroniccomponentsyouneedtomakeastatusmessagesign
UnderstandingtheCircuitAssoonasyoustartsolderingandgluingmaterialstogether,ifyoumakeasmallmistakeitcanbedifficulttoundo.There’sawayaroundthis:beforeyoucreateyourfinishedcircuit,youshouldalwaysmakeaprototypeofitonabreadboardfirst,tomakesurethecircuitworksproperly.Thatway,ifyoumakeanymistakesinyourdesignyoucaneasilycorrectthembeforeyouhavethecomponentspermanentlyinplace.
Figure2-10showsthecircuitthatyou’regoingtobuildforyoursign.YouwillbebuildingacircuitwiththreeLEDsandonepotentiometer.TheLEDswillbeconnectedtoPins5,6and7,andthepotentiometerwillbeconnectedtoground,PinA0and5V.
FIGURE2-10Circuitschematicforthesign
YouarenowgoingtotestthecircuitandtheArduinocodeonthebreadboard,thenyouwillrebuildthecircuitwithoutabreadboard.
PrototypingonaBreadboardTobuildyourprototypecircuit,usethefollowingsteps:
1. Useajumperwiretoconnect5VontheArduinoUnotooneofthelongrowsrunningalongthebottomofthebreadboard.Ifthebreadboardislabelledwitharedlineor+,connect5Vtothatrow;otherwise,chooseeitherrow.
2. UseanotherjumperwiretoconnectGNDontheArduinoUnototheotherlongrowonthebreadboard.
3. Insertthelegsofthepotentiometerintoanyoftheshortrowsinthemiddleofthebreadboard.
4. UseajumperwiretoconnectoneoftheoutsidelegsofthepotentiometertothelongrowconnectedtoGNDontheArduinoUno.
5. Useanotherjumperwiretoconnecttheotheroutsidelegsofthepotentiometertothelongrowconnectedto5VontheArduinoUno.
6. ConnectthemiddlelegofthepotentiometertopinA0ontheArduinoUno.7. Putonelegofoneoftheresistorsinashortrowonthetophalfofthebreadboard
towardstheleftsideoftheboard.Puttheotherlegoftheresistorintheshortrowacrossthegapinthemiddleofthebreadboarddirectlybelowwhereyou’veinsertedthefirstresistorleg.Therowsofthebreadboardaren’tconnectedacrossthegap,soeachresistorlegisinitsownrow—theyaren’ttouchingthesamepieceofmetalinsidethebreadboard.
8. Repeatwiththesecondandthirdresistors.Placeoneresistorinthecentreofthebreadboardandtheothertowardstherightsideofthebreadboard.Eachresistorshouldreachacrossthegapinthemiddleoftheboardandhaveoneleginashortrowabovethegapandtheotherinashortrowbelowthegap.
9. NowaddtheLEDs.ThelonglegofeachLEDconnectstotheresistor,andtheshortlegconnectstoground.InsertthelonglegofeachLEDintothesameshortrowaseachresistor.Itshouldbeplacedjustbelowtheresistor.PlacethegreenLEDontheleftsideofthebreadboard,theyellowinthemiddleandtheredontherightside.
10. InserttheshortlegofeachLEDintothelongrowsrunningtheentirelengthofthebreadboardattheverybottomthatisconnectedtoGNDontheArduinoUno.
11. Usingthreemorejumperwires,connectonewirefromPin5ontheArduinoUno(notA5,butthe5inthesectionlabelledDigital)tothetopoftheresistorontheleftsideofthebreadboardconnectedtothegreenLED.UseasecondjumperwiretoconnectPin6tothemiddleresistorconnectedtotheyellowLEDandathirdjumperwiretoconnectfromPin7tothelastresistorconnectedtotheredLED.
Whenfinished,yourprototypecircuitshouldlookliketheoneinFigure2-11.Noticeanything?Thefullcircuitforthesignisacombinationofthetwocircuitsyouwereworkedwithearlierinthischapter.ThepotentiometerisreadintoPinA0,andthethreeLEDsarecontrolledbytheoutputonPins5,6and7.
FIGURE2-11Prototypecircuitonthebreadboardforthesign
WritingtheCodeNextyouneedthecode.LaunchtheArduinoIDEandtypethefollowingsketchinanewsketchwindow.Don’tforgettosaveit!
Startyoursketchbycreatingemptysetup()andloop()functions.voidsetup(){
}
voidloop(){
}
Nextaddavariableatthetopofthesketchtokeeptrackofyourpotentiometer.//Pins
intpotPin=A0;
Inthesetup(),startserialcommunicationsoyoucanprintmessagestoSerialMonitor.Typethefollowinglinesbetweenthe{and}ofthesetup().//startserial
Serial.begin(9600);
Theloop()functioncontrolsalltheaction.ThevaluefromthepotentiometerisreadandsavedinavariablecalledpotValue.AdifferentmessageisthenprintedaccordingtothenumbersavedinthepotValuevariable.ThemessageprintsoutwhatshouldhappenwiththeLEDs.Typethefollowinglinesbetweenthe{and}oftheloop().intpotValue=analogRead(potPin);
//printwhatthepotvalueis
Serial.print("Potentiometeris:");
Serial.println(potValue);
//ifpotislessthan341
if(potValue<341){
Serial.println("Turnongreen,turnoffyellowandred");
}
//ifpotmorethanorequalto341and
//lessthan682
if(potValue>=341&&potValue<682){
Serial.println("Turnonyellow,turnoffgreenandred");
}
//ifpotmorethanorequalto682
if(potValue>=682){
Serial.println("Turnonred,turnoffgreenandyellow.");
}
//Apausetoslowdownthemessages
delay(50);
SavethesketchanduploadittoyourArduinoUno.OpentheSerialMonitorandseewhathappenswhenyouturnthepotentiometer.Youshouldseethevalueofthepotentiometer
printalongwithwhattheLEDsshouldbedoing—butyouhaven’tprogrammedtheLEDsyet.Timetodothatnow!
AddthreemorevariablestokeeptrackoftheLEDpinsatthetopofyoursketch.intgreenLED=5;
intyellowLED=6;
intredLED=7;
Insidesetup(),addthecodetoseteachpinMode().//settooutputtoLEDpins
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
Intheloop(),addthedigitalWrite()functionstoturnonandoffeachLED(showninboldinthefollowingcode).Youcanalsoremovethedelay()attheendoftheloop().Yourfullsketchshouldlooklikethis://Pins
intpotPin=A0;
intgreenLED=5;
intyellowLED=6;
intredLED=7;
voidsetup(){
//settooutputtoLEDpins
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
//startserial
Serial.begin(9600);
}
voidloop(){
intpotValue=analogRead(potPin);
//printwhatthepotvalueis
Serial.print("Potentiometeris:");
Serial.println(potValue);
//ifpotislessthan341
if(potValue<341){
Serial.println("Turnongreen,turnoffyellowandred");
//turnongreenLED
digitalWrite(greenLED,HIGH);
//turnoffyellowandredLEDs
digitalWrite(yellowLED,LOW);
digitalWrite(redLED,LOW);
}
//ifpotmorethanorequalto341and
//lessthan682
if(potValue>=341&&potValue<682){
Serial.println("Turnonyellow,turnoffgreenandred");
//turnonyellowLED
digitalWrite(yellowLED,HIGH);
//turnoffgreenandredLEDs
digitalWrite(greenLED,LOW);
digitalWrite(redLED,LOW);
}
//ifpotmorethanorequalto682
if(potValue>=682){
Serial.println("Turnonred,turnoffgreenandyellow.");
//turnonredLED
digitalWrite(redLED,HIGH);
//turnoffgreenandyellowLEDs
digitalWrite(greenLED,LOW);
digitalWrite(yellowLED,LOW);
}
}
Uploadthesketchwiththecircuitonthebreadboard.Ifyoudon’twanttotypeallthecode,youcandownloadthesketchfromthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
Ready?Timetotryitout.YoushouldbeabletochangewhichLEDturnsonbyturningthepotentiometer.OnlyoneLEDshouldturnonatatime.YoucanopentheSerialMonitorintheArduinoIDEtomakesurethecorrectvaluesarecomingfromthepotentiometer.
DIGGINGINTOTHECODE
Thereisonebitofcodeinthesketchforthestatusmessagesignthatyouhaven’tseenbefore:&&.Thosetwoampersands(&&)withoutaspaceinbetweenmeansthatboththepieceofcodebeforeitandafterneedtobetrue.
Forexample:
4<6&&10<20
istruebecauseboth4<=6and10<20aretrue.But:
3>9&&5<7
isfalsebecauseonly5<7istrue;3>9isfalse.The&&symbolisawaytocombinerestrictionsinanifstatement.Inyoursketch,it’susedtoturnontheyellowLEDonlyifpotValue>=341andalsopotValue<682.
CreatingyourSignInanyproject,thethingthatreallybringsitcometolifeisthestructureinwhichyouhousetheelectronics.Itdoesn’tjustprotectyourelectronicsandhidethepartsyoudon’twanttosee—italsogivesyouachancetogetcreative.ThecodeandcircuitareabigpartofthecreativeprocessofmakinganArduinoproject,ofcourse!Butthisisthepartwhereyoucanreallyletyourimaginationrunriotsoyoucanshowoffyourprojecttoyourfriendsandfamilybygettingitoffthebreadboardandintoastylishnewhome!
Youcanchoosewhatevermaterialsyouwouldliketousetocreateyoursign,butashoeboxworkswell.Itcaneasilybecutwithautilityknifeorscissorsanddecoratedwithpaperandglueorpaint,andyou’llbeabletomakeitaspersonalasyoulike.
Youcanwatchavideodemonstratinghowtobuildthesignandsolderthecircuitonthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
CuttingHolesforthePotentiometerandLEDsBeforeyoudecoratethebox,youneedtocutsomeholesinitwhereyouwantyourLEDsandtheknobofthepotentiometertobelocated.Makefiveholes:threefortheLEDs,onefortheknobandonefortheUSBcable.MeasurethelensesoftheLEDsandtheshaftofthecontrolknobsoyoucanmaketheholesjustbigenoughforthosecomponentstofitsnuglyintothem.(Ifyoumaketheholestoobig,theLEDsandknobwilljustfallout!)FortheUSBcable,theholeneedstobelargeenoughforyoutopasstheendoftheUSBcablethatplugsintotheArduinothroughit.
Ifyouareusingashoebox,IrecommendthatyoumaketheholesfortheLEDs,knob,andUSBcableinthebottomofthebox,asshowninFigure2-12.Thatwayyoucaneasilyremovethelidtoaccesstheelectronicsandthenquicklyhidethemallaway.
FIGURE2-12CuttingholesfortheLEDsandknob
AddingtheStatusMessagesandDecoratingtheSignNowyou’rereadytotransformyouroldshoeboxintoaslicksignboxbypaintingitorcoveringitwithpaper.Decideonyourmessages—youcanusethemessagesI’vesuggestedinFigure2-11orcreateyourown.Itdoesn’tmatterwhetheryouwriteorpaintthemontotheboxyourself,printthemfromacomputerandgluethemnexttotheLEDs,cutthemoutofmagazines—dowhateveryoulike.Therearenolimits!Expressyourcreativity—usepaint,markers,crayonsorwhateveryouhaveavailable.Inmyopinion,youcanseldomgowrongwithglitter.Orwhynotusenaturalmaterialslikefeathersordriedflowers?
SolderingtheCircuitYouknowthatyourcodeandcircuitwork(andifyouhaven’ttestedthem,gobackanddothat!),soyouarereadytomorepermanentlyassembleyourcircuit.Circuitsdependonelectricityflowingthroughconductivematerialslikemetal.Thatmeansyoucan’tusethingslikegluetoconnectcomponents—theelectricitycan’tflowthroughglue.Insteadyouusesolder.It’slikeconductiveglue.
Solderisametalthatmeltsatalowertemperaturethanmostmetals,butthatlowertemperatureisstillquitehot!Muchhotterthantheoveninyourkitchenevergets,soit’simportantthatyouaresafewhensoldering.Takeasmuchcareasyouwouldhandlinghotpotsandpanswhencooking.
Onlysolderwhenanadultisnearbytohelp!
Therearelotofresourcesonlinetohelpyougetstartedsolderingifyouhaven’tdoneitbefore.YouTubeisfullofvideos,butthetutorialsonSparkfun(https://learn.sparkfun.com/tutorials/how-to-solder---through-hole-soldering)andAdafruit(https://learn.adafruit.com/adafruit-guide-excellent-soldering)areexcellentplacestostart.
Solderingcangetdifficultwhenyoufeellikeyou’verunoutofhandstoholdthings.Youcangetatoolcalledathirdhandorhelpinghandthatcanhelpholdthingsstillforyou.Analternativeistouseabitofposterputtytoholdaniteminplacewhileyousolderit.
Whenanypaintorglueonyourboxisdry,youcanstartlayingoutyourcircuit.Beforeyoustart,youshoulddecidewhereyourArduinowillbelocatedinsideyourbox.
Here’showyoumakeyourLEDcircuit(seeFigure2-13):
1. ConnectaresistortoeachoftheLEDs.TwistthelegofaresistorwiththelonglegofanLEDsothattheydon’teasilycomeapart.Soldertheconnection.DothiswillallthreeLEDs.
2. PlacethethreeLEDsintheirholesinthebox.Bendtheshorterleg(thelegthatconnectstoground)ofthetopLEDdowntowardstheLEDbelowit.RepeatwiththemiddleLEDandbendtheshorterlegtowardsthebottomLED.
3. CutapieceofwirethatreachesfromthelegofthetopbentLEDtothemiddlebentLEDlegandthenasecondpieceofwirethatreachesfromthemiddlebentLEDlegtothebottombentLEDleg.It’sbetterforthewirestobetoolongthantooshort.Cutatleastaninchmorethanyoumeasured.Usewirestripperstostripapproximatelya½”fromeachendofthewires.
4. RemovetheLEDsfromthebox.TwistoneendoftheoneofthewireswiththeshortbentlegofthetopLED.Solderthemtogetherwithasolderingiron.
5. TwistoneendoftheotherwirewiththeshortbentlegofthemiddleLED.Solderthemtogether.
6. NowyouwillconnectthewireconnectedtotheshortlegofyourtopLEDtotheshortlegofthemiddleLED.TwisttheendofthewirehangingfromthetopLEDaroundthebentlegofthemiddleLEDandsolderthemtogether.
7. RepeatwiththewireconnectedtothemiddleLEDtoconnectittothebottomLED.8. PutyournewlyconnectLEDsintotheirholesintheboxtomakesuretheystillfit.If
theydon’t,youcancutordesolderthewiresandtryagain.9. YounowaregoingtocutthewiresthatwillreachfromtheLEDstotheArduino
Uno.YouneedtomeasureandcutthreewiresthatreachfromtheresistorsconnectedtotheLEDsandonewirethatreachesfromtheshortlegofthebottomLED.Again,cutthemaboutaninchlongerthanthemeasurementandstripa½”fromeachend.
10. SoldereachofthewirestotheirresistororLED.
Remembertoonlysolderwithanadult.Becareful;theendofthesolderingironisveryhot!
FIGURE2-13TheLEDportionofthecircuit
Nowsolderthewirestothepotentiometer(showninFigure2-14):
1. Placethepotentiometerinitshole.CutthreewiresthatreachfromthepotentiometertotheArduinoboard.
2. Stripabouthalfaninchoftheplasticfromoneendofeachofthewiresandsoldereachwiretoalegofthepotentiometer.
3. Stripabout¼”oftheplasticfromthefreeendsofeachwire.YoudothissothattheycanbeinsertedintothepinsontheArduinoboard.
FIGURE2-14Solderedpotentiometer
Atthispoint,stopandinspectyourwork.Carefullycheckthatnoneoftheexposedmetalfromthewiresorcomponentlegscantoucheachother.Iftheycan,theymightcreateaccidentalelectricalconnections.Ifthisisthecase,wrapelectricaltapearoundthemetaltopreventthathappening.
InsertingtheElectronicsWhentheglueandpaintyou’veusedtodecoratetheboxiscompletelydry,youarereadytofinishyoursignandinstallyourelectronics.
PlacetheLEDsintotheirholesinthebox.Youcanusealittleglueortapetoholdtheminplaceifyouneedto.
Thepotentiometercomeswithawasherandnutthatscrewdownonthebaseoftheshaft.Removethese,pushthepotentiometerthroughitsholeandscrewdownthewasherandnuttoholditfirmlyonthebox.Youcanmakeacontrolknobtoattachtotheendofthepotentiometerifyou’dlike.
InsertyourwiresfromyourcomponentsintotheArduinoUno.ThethreewiresconnectedtotheresistorsgotoPins5,6and7.ThewireconnectedtotheshortlegofthebottomLEDisinsertedinaGNDpin.Oneofwiresconnectedtoanoutsidelegofthepotentiometerisinsertedin5V,andtheotheroutsidelegisconnectedtoGND.TheremainingwireconnectedtothemiddlepinisinsertedinPinA0.
Younowneedtodecidehowyouwantyourprojecttobepowered.Youcan,ofcourse,leaveyourArduinoUnoconnectedtoyourcomputer,butthatcanbeinconvenient.YoucanalsostilluseyourUSBcable,butplugitintoawalladapterinsteadofyourcomputer,asshowninFigure2-15.Walladaptersoftencomewithnewmobilephones,soyoumighthaveonelyingaroundalready.AnythatletsyouconnectaUSBcableisfinetouse.
FIGURE2-15PowersupplythatyoucanusewithanArduinoboard
Congratulations!Youhavecreatedyourownstatusmessagesignthatyoucansetupandplugintodisplayamessageofyourchoice.You’vecreatedyourfirstArduinoprojectthatbreaksfreefromthecomputerandcanrunonitsown.YoursmaylookverydifferentfromtheoneinFigure2-16,andthat’sgreat!YouarewellonyourwaytobecominganArduinoexpert!
FIGURE2-16Completedstatusmessagesign
FurtherAdventureswithArduinoNowthatyoucanchangetheoutputoftheArduinoUnoaccordingtotheturnofapotentiometer,whatelsecouldyoudo?Herearesomeprojectideas:
ChangethespeedofaflashingLEDbyturningthepotentiometer.MaketheLEDsflashinasequenceandchangethespeedwiththepotentiometer.
ArduinoCommandQuickReferenceTable
Command Description
intDatatypethatcreatesanewvariablethatisaninteger(wholenumber).Seealsohttp://arduino.cc/en/Reference/Int.
Serial.begin()Startstheserialcommunicationsomessagescanbesentandreceived.Seealsohttp://arduino.cc/en/Serial/Begin.
Serial.print()Sendsamessagewithoutanewlineattheend.Seealsohttp://arduino.cc/en/Serial/Print.
Serial.println()Sendsamessagewithanewlineattheend.Seealsohttp://arduino.cc/en/Serial/Println.
analogRead()
Readsinthevoltageonthespecifiedpinandassignsitanumberfrom0(forground)to1023(for5V).Seealsohttp://arduino.cc/en/Reference/AnalogRead.
if()Usedtodeterminewhetherasectionofcodewillbeexecuted.Seealsohttp://arduino.cc/en/Reference/If.
AchievementUnlocked:Youaretakingchargeandmakingdecisions!
IntheNextAdventureYouwillstartaddingmotionandcontrollingamotorinthenextproject.
ONEWAYOFmakingyourprojectsmoredynamicisbyintroducingmovement.Whenyouaddmovementtoaprojectitcanfeelasifyou’veactuallybroughtittolife.Thisadventurewillshowyouhow,byworkingwithaservomotorandaddingswitchestoyourcircuits.
Inthisadventure,youwillstartbyfindingoutaboutthenewcomponentsyouaregoingtoworkwith,thenusethosecomponentstobuildafantasticcombinationsafe,whichonlyopenswhenyouturnallthepotentiometerstotheirsecretpositionsandpushthebutton.Ifyouknowtherightcombination,thesafeopensautomatically.Thesafeisconstructedfromcardboard,sowon’twithstandabruteforceattack,butitcanbeusedtodeterparentsfromgettinginside!
WhatYouNeedYouwillbeusinganewactuator,whichisafancywordforanobjectthattakesanelectricalsignalandthendoessomethingintherealworld.YouhavealreadyusedonetypeofactuatorinAdventures1and2:theLED.Ittakeselectricityandturnsitintolight.Inthisadventure,youuseamotorthattakeselectricityandturnsitintomotion.
Anactuatortranslatesanelectricalsignalintoareal-worldmodifiesactionsuchaslight,soundormovement.
Theoppositeofanactuatorisasensor,andyouwillbeusinganewoneofthoseaswell.Adventure2introducedthepotentiometer,whichsensesrotationandtranslatesitintoanelectricalsignal.Hereyouusepotentiometersagainandalsouseabuttontotranslateapressintoanelectricalsignal.
Asensordetectssomethingintherealworldsuchaslight,soundormovement,andtranslatesitintoanelectricalsignal.
Youneedthefollowingitems.TheelectroniccomponentsareshowninFigure3-1.
AcomputerAnArduinoUnoAUSBcableAbreadboard4jumperwiresAservomotorAtactilepushbutton110kΩresistor
FIGURE3-1TheelectroniccomponentsyouneedforthefirstpartofChapter3
UnderstandingDifferentTypesofMotorsAmotorisgeneraltermforsomethingthattakeselectricityandturnsitintomechanicalmovement,butdifferenttypesofmotorletyoucontrolthatmovementindifferentways.Whenyouthinkofamotor,thethingyouthinkofisprobablywhatiscalledaDCmotor.TheDCinDCmotorstandsfordirectcurrent.DirectcurrentisthetypeofelectricitythatyouuseinyourArduinocircuits.
Directcurrent(DC)isthetypeofelectricityusedinArduinocircuits.It’sthesamekindthatisgeneratedbyabatteryandistheoppositeofalternatingcurrent(AC),whichiswhatcomesoutofmainplugsinthewall.
ToyDCmotorsarecommoninthingslikeremotecontrolcars.WhenaDCmotorisconnectedtoDCcurrent,itspinsashaft;youcancontrolthespeedofthemotorandthedirectionitspins,butnotmuchelse.Formorecontrol,youneedsomethingthatwilldomore—eitheraservomotororasteppermotor.
Therearedifferenttypesofservomotor,butthemostcommonisknownasastandardhobbyservomotor.WithaDCmotor,theshaftspins,butyoudon’tnecessarilyknowwheretheshaftispointingwhenthemotorstops.Aservomotorknowswhichwaytheshaftispointing.Althoughyoucantellaservomotorwheretopoint,ithassomelimitations;itcanonlypointinsomedirectionsandcan’trotateafullcircle.WhereasaDCmotorcanrotatecontinuously,aservomotorcanusuallyonlyrotate180degrees.
AsteppermotorcombinesthestrengthsoftheDCandservomotorsinthatitcanrotatecontinuouslyandyoucantellitapreciselocationtorotateto.Butthatcomesataprice!Steppermotorstendtocostmorethanothertypesofmotor.There’sasolutiontothis:youcanchoosethecheaperoptionofaDCorservomotorforyourproject(seeFigure3-2)andgetroundthelimitationsbyengineeringasolutionyourself.
FIGURE3-2AservomotorandtoyDCmotor
Aservoisamotorthatcanbecontrolledtorotatetoaspecificposition.Itusuallycan’trotatemorethan180degrees.
Ifyou’dliketoreadmoreabouthowtousemotors,checkoutMakingThingsMovebyDustynRoberts(McGraw-Hill,2010).
ControllingaServowithArduinoTheArduinointegrateddevelopmentenvironment(IDE)comeswitheverythingyouneedtocontrolaservo.Itevenhasexamplesketchestogetyougoing.Inordertocontrolyourservo,youneedtoopenasketchcalledSweep.YouopenSweepbylaunchingtheArduinoIDEandclickingonFile ⇒ Examples ⇒ Servo ⇒ Sweep(Figure3-3).
FIGURE3-3OpeningtheSweepexamplesketch
Thissketchshowshowtotellaservotomove.ReadthroughthecodeintheSweepsketch.Thefirstlineofcodeafterthecommentshasn’tappearedinthecodeyouusedinAdventures1and2:#include<Servo.h>
The#includeistellingArduino’scompilerthattheSweepsketchwillbeusingsomefunctionsthataren’talwaysincludedinanArduinosketch,andthatthecompilercanfindthosefunctionsinalibrarycalledServo.ThecodetellsthecompilerthatitshouldreadthelibraryfilecalledServo.h.The<>aroundthefilenamemeansthatthefileislocatedin
thestandardlocationonthecomputerwhereallArduinolibrariesarestored.
Nowlookatthenextlineofcode:Servomyservo;
Thiscreatesanewvariablecalledmyservobutthisvariableisn’tanintegerliketheothervariablesyou’veused(suchasgreenLEDinAdventure2).Instead,itisthetypeServo(insteadofint).BecausethevariableisaServo,itholdsalltheinformationneededtocommunicatewithaservo.
ThereisjustonemorelineofcodetofinishsettinguptheservointheSweepsketch.TheArduinoUnoneedstoknowwhichpintheservowillbeconnectedto.Thisonlyneedstobedoneonce,sothatshouldhappeninthesetup()function.Afewlinesdowninthesketchyoushouldseethefollowingline:myservo.attach(9);
NowyouneedtobuildacircuittohookupyourservomotortoyourArduinoboard,whichwillenduplookinglikeFigure3-4.You’llbegladtohearthatthisneedsjustthreeconnections:5V,groundandthecontrollingpin.Unfortunatelythebadnewsisthatnotallservomotorsmakethoseconnectionsinthesameorder.Someservos(suchasthoseshowninFigures3-1and3-2)comewithalabelthatnicelyillustratestheconnections.Ifyoursdoesn’t,findoutiftheplacewhereyouboughttheservohasanyinformation.Ifthatdoesn’tprovideanyhelp,youcanjusttrywiringthecircuitindifferentcombinationsuntilitworks!
FIGURE3-4CircuittoconnectaservototheArduinoboard
Buildthecircuitfortheservo:
1. Useajumperwiretoconnectthegroundpin(maybelabelledGNDor0V)ontheservotoanyoftheGNDpinsontheArduinoUno.
2. Useasecondjumperwiretoconnectthe5Vpinontheservotothe5VpinontheArduinoUno.
3. UseathirdjumperwiretoconnecttheremainingpinontheservotoPin9ontheArduinoUno.
Afterthecircuitisbuilt,uploadtheSweepsketch(checkoutAdventure1ifyouhaven’tdonethisbefore),andwatchyourservocometolife!Itshouldstartrotatingbackandforth.Youwillhearandseeitworking.
RepeatingtheSameThingOverandOverTheArduinoboardcontrolstheservomotorthroughelectricalpulsesthattellitwheretorotate.Youdon’thavetoworryabouthowitdoesthat,asthedetailsarenicelyhandledbytheservolibrary.Allyouhavetodoistelltheservowheretogoto.Youcanchooseapositionfortheservotopointanywherebetween0and180degrees.
IntheSweepsketch,theservorotatesitsarmbackandforth.Youcouldtelltheservotodothisbycopyingandpastingmyservo.writeoverandoveragain,likethis:myservo.write(0);
myservo.write(1);
myservo.write(2);
myservo.write(3);
Thatisn’taveryefficientwaytodothings,though.Computersarereallygoodatdoingrepetitivetasks,sothere’sabetterwaytomaketheservorotatebackandforth.Ifyou’vereadthecodeintheSweepsketchtoseehowit’sdonethere,youmighthavenoticedaprogrammingtoolcalledaforloop.
Aforloopisaprogrammingdevicethatrepeatsablockofcodeforapredeterminednumberoftimes.
TheSweepsketchhastwoforloops.Here’sthefirstone:for(pos=0;pos<180;pos+=1)
{
myservo.write(pos);
delay(15);
}
Tosetupaforloop,youneedtoprovidethreepiecesofinformation:
1. Firstofall,youneedtostatewhatthestartingconditionis.InthistheSweepsketchit’spos=0.
2. Next,youneedtosaywhatneedstohappenfortheforlooptocontinue.Here,poshastostaybelow180(expressedincodeaspos<180).Whenposisequaltoorlargerthan180,theloopstopsandthecodeinbetweenthe{and}isnolongerexecuted.
3. Finally,youneedtosaywhatchangeseachtimetheloopisexecuted.IntheSweepsketch,1isaddedtoposeachtimethecodeinbetween{and}isexecuted.Thisiswrittenaspos+=1,forshort,butyoucanwriteitinanumberofways;youcouldwriteitaspos=pos+1orpos++.
Thecomputerdoesn’tnoticeindentsorspacesbetweenpiecesofcode.Sometimescodehasspacesaddedtomakeiteasiertoread.ThefollowingtwolinesofcodelookthesametotheArduino.
for(pos=0;pos<180;pos+=1)
for(pos=0;pos<180;pos+=1)
It’seasiertoseethethreepartsoftheforloopwhentherearespacesincluded.
Phew!It’sprobablytimeforarecap.Inthisexample,intheforloop,posstartsat0.Because0islessthan180,thecodeinthe{}isexecuted.Theservoissetto0andthenpausesfor15milliseconds(byusingthedelay()function).1isaddedtopos,soitnowequals1.Because1islessthan180,theservoissetto1andthenpausesfor15milliseconds.Thiskeepshappeninguntilposis179.Theservoissetto179and1isaddedtoposmakingit180.posisnolongerlessthan180,sothecodeinthe{}isskippedandtheArduinogoesontothenextlineofcodeaftertheforloop.
CHALLENGE
WhatishappeninginthesecondforloopintheSweepsketch?Thisiswhatitlookslike:
for(pos=180;pos>=1;pos-=1)
{
myservo.write(pos);
delay(15);
}
Changetheforloopsothattheservoonlyrotatesfrom0to90.
DigitalInputwithaPushButtonYoumightthinkthesimpleswitchwouldbequiteastraightforwardelectricalcomponent,butinfactswitchesaredeceptivelycomplicated.Theycomeinmanyshapesandsizes.Youhavemanyoftheminyourhousetoturnonandoffyourlights.Alltheydoiscompleteorinterruptacircuit.Sometimestheychangewherethecurrentflowsinacircuit,butthetypeofswitchthatturnsyourlightsonandoffismadefromtwopiecesofmetalthateithertouchordon’ttouch,dependingonthepositionoftheswitch.
Aswitchisacomponentthateitherdisruptsorredirectstheflowofcurrentinacircuit.
Thereisanothertypeofswitch,calledatactilepushbutton.Italsohastwopiecesofmetalinsideofit,butinthiscasetheyonlytouchwhenthebuttonisactuallybeingpressed.Atactilepushbuttonhasfourlegs,butit’sbettertothinkofthemastwopairsoflegsbecausethetwolegsineachpairarealwayselectricallyconnected—evenwhentheswitchisnotbeingpressed.Whenthebuttonispressed,allfourlegsareelectricallyconnected.SeeFigure3-5foranillustrationofhowatactilepushbuttonworks.
Atactilepushbuttonisatypeofswitch.Apush-to-breakpushbuttoninterruptstheflowofcurrentinacircuitwhenitispressed.Apush-to-makepushbuttondoestheoppositebyinterruptingcurrentonlywhenitisnotpressed.
FIGURE3-5Howatactilepushbuttonworks
Nowyou’regoingtobuildthecircuit,includingapushbutton,asshowninFigure3-6.
1. Insertthepushbuttonintofourrowsinthecentreofyourbreadboard.Thepush
buttonfitsoverthegapinthemiddle,sotwolegsareinsertedintworowsonthetophalfoftheboardandtheothertwolegsareintworowsonthebottomhalfoftheboard.
2. Useajumperwiretoconnecttherowwherethebottom-rightlegofthepushbuttonisinsertedtooneofthelongrowsalongthebottomofthebreadboard.Ifyourbreadboardislabelledwithablackorbluelineora-,connectittothatrow.Ifyourbreadboardisn’tlabelled,connectittoeitherrow.
3. UseanotherjumperwiretoconnectthelongrowconnectedtothepushbuttontooneoftheGNDpinsontheArduinoUno.
4. UseajumperwiretoconnectPin2ontheArduinoUnototherowconnectedtothetop-leftlegofthepushbutton.
FIGURE3-6Circuitwithatactilepushbutton
Nowyou’vebuiltyourcircuit,opentheexamplesketchatFile ⇒ Examples ⇒ 01.Basics ⇒ DigitalReadSerial.UploadthesketchandopentheSerialMonitorbyclickingthebuttonintheArduinoIDEorgoingtoTools ⇒ SerialMonitor.
Ready?Timetopressandreleasethebutton.WhathappensintheSerialMonitor?Whenyourfingerispressingthebutton,youshouldseea0printed;whenthebuttonisnotbeingpressed,youshouldseeamixtureof0sand1s.Thesequenceof0sand1sisrandom,soyoumightseemostly0sormostly1sratherthananevenmixtureofthetwo.Thisiswhat’scalledafloatinginput.Whenthebuttonisn’tbeingpressed,thepinisn’tconnectedtoavoltagesourcesuchasgroundor5V—it’sfloating.TheArduinoUnoisreadinginrandomvaluesfromthatpin.
Afloatinginputisapinthatisnotconnectedtoanything.Thepinreadsinrandomvaluesifitisnotconnectedtoavoltagesource,suchasground,5Vorasensor.
It’snotagoodthingtohavefloatingvalues.ThemainreasonisthatwhentheArduino
“readsin”adigitalsignalfromapin,itreadsina0whenthepinisconnectedtogroundandreadsina1whenit’sconnectedto5V.Ifthepinisn’tconnectedtoeithergroundor5Vandisrandomlyreadingin0and1,thenit’simpossibleforyourcodetomakegooddecisionsbasedontheinputfromthatpin.Ifyouwanttostartamotormovingonlywhenabuttonispressed,connectingthatpintoground,thenyoucan’thavethepinreadingin0whenthebuttonisn’tpressed.
Thewayaroundthisproblemistouseakindofresistorcalledapull-upresistor.Apull-upresistorgivesadefaultvalueof5Vtoapinbyalwaysconnectingthatpinto5V.Thepinisalsoconnectedtothepushbutton,andthepushbuttonisconnectedtoground.Theresistorusuallyhasquiteahighvalue,suchas10kΩ.Thereisnoresistancebetweengroundandthepinwhenthebuttonispressed,sothepinconnectstogroundinsteadof5Vthroughthepull-upresistor.Electricityalwayschoosesthepathwiththeleastresistance,and,inthiscase,thatisthepathbetweengroundandthepin.
Apull-upresistorisaresistorthatisconnectedtothehighvoltageinacircuit,whichsetsthedefaultstateofthepinonthatcircuittoHIGH.Theresistorisusually10kΩ.
Likemostthingswithelectronics,theeffectofapull-upresistorismucheasiertounderstandwhenyouactuallybuildacircuitandseewhathappensforyourself.That’swhatyou’regoingtodonow.ChangethecircuitonyourbreadboardtotheoneshowninFigure3-7.
1. Startwiththecircuityoujustbuiltwiththepushbuttoninthecentreofthebreadboard.
2. Useajumperwiretoconnectfromthe5VpinontheArduinoUnototheotherlongrowalongthebottomofthebreadboard(theonethatisn’tconnectedtoground).
3. Placeonelegofthe10kΩresistorinthesameshortrowasthelower-leftlegofthepushbutton.Inserttheotherlegoftheresistorintothelongrownowconnectedto5V.
FIGURE3-7Circuitwithapull-upresistor
Youdon’tneedtochangeanythinginyourArduinocode,andyoucanjustleavetheSerialMonitoropen.Now,whathappenswhenyoupressandreleasethebutton?Itshouldnowonlyshow0whenthebuttonispressedand1whenitisreleased.
TheArduinoboardhaspull-upresistorsbuiltintoitalready,soyoucanusetheseinsteadofbuildingapull-upresistorintoyourcircuitonthebreadboard.Todothis,youfirstindicatethatyouwanttouseoneofthebuilt-inpull-upresistorswhenyousetupthepinMode()insetup(),bytypinginthefollowingcode:pinMode(pushButton,INPUT_PULLUP);
Next,changetheDigitalReadSerialsketchsothatthesecondargumentofpinModeisINPUT_PULLUPinsteadofINPUT.Yoursetup()shouldlooklike:voidsetup(){
//initializeserialcommunicationat9600bitspersecond:
Serial.begin(9600);
//makethepushbutton’spinaninput:
pinMode(pushButton,INPUT_PULLUP);
}
Finally,uploadthesketchagainandchangeyourcircuitonyourbreadboardtotheoneinFigure3-8byremovingthe10kΩresistorandjumperwireconnecting5Vandoneofthelongrows.Yourbuttonshouldactthesamewayasitdidwhenyouhadthepull-upresistoronthebreadboard.
FIGURE3-8Circuitwithapushbuttonandinternalpull-upresistorontheArduinoboard
BuildingaCombinationSafeWelldone!Youhavebuiltupquiteanarsenalofsensorsandactuators.Nowyoucanstartputtingthemtogethertomakesomethingverycoolandveryuseful:acombinationsafethatopensandclosesautomatically(seeFigure3-9).Toopenthesafe,youdialinacombinationandpushabutton.Theboxwillonlyopenifthecombinationiscorrect,anditwillstayopenuntilyoureleasethebutton.Itcanbeagreatplacetokeepasecretcandystashorkeepyourfavouritepensandpencilsfrombeing“borrowed”withoutyourpermission.
FIGURE3-9Combinationsafe
WhatYouNeedYouneedtheitemsinthefollowinglisttobuildyoursafe.Itincludesthecomponentsyouneedtoprototypeyourcircuitonabreadboardandthecomponentsyouuseinyoursafe.Figure3-10showstheelectroniccomponentsyouneed.
FIGURE3-10Theelectroniccomponentsyouneedtobuildyourcombinationsafe
Youuseadifferentbuttoninyoursafethanonyourbreadboard.Youuseapanelmountpushbuttoninsteadofatactilepushbutton.Youstilluseatactilepushbuttontotestyourcircuitonabreadboard,butthepanelmountbuttonisbiggerandeasiertomountonacardboardbox.Youfindouthowtoconnectwirestothepanelmountbuttonlaterinthischapter.
Apanelmountpushbuttonisapushbuttonthatisdesignedtobemountedinsideacase.Itcomeswithanutandwashertosecureittoapanel.
Havethefollowingsuppliesonhandbeforeyoustarttheproject:
AcomputerAnArduinoUnoAUSBcableAbreadboard16jumperwiresAtactilepushbutton(push-to-make)Apanelmountpushbutton(push-to-make)
Aservomotor310kΩpotentiometersSomesolderAsolderingironSomewireApapercliporbambooskewerAsmallboxwithalidtobeyoursafeAhotgluegunScissorsorautilityknife
Yourboxcanbeanysize,butaboxapproximatelythesizeofashoeboxworkswell.Itworksbestifthelidisalreadyattachedtothebaseofthebox,butthelidisn’tattached,Iexplainhowyoucanattachityourself.
Youcanalsouseanythingyouwouldliketodecorateyourbox,suchaspaintorpaper.
Visitthecompanionwebsitetoseeavideoshowinghowthebuildingthesafe(www.wiley.com/go/adventuresinarduino).
UnderstandingtheCircuitThecircuitforthesafehasthreecomponentsaservo,threepotentiometersandapushbutton.Thethreepotentiometersarereadintothreeanalogpinsandthepushbuttonisreadintoadigitalpin.Theservomotoriscontrolledfromanotherdigitalpin.
Figure3-11showstheschematicforthesafe.Lookscomplicated,doesn’tit?Don’tworry;youwillbuilditstepbystep.Beforeyousolderthecircuitforyoursafe,you’regoingtomakeaprototypeofitonyourbreadboard.
FIGURE3-11Circuitschematicforthecombinationsafe
Incircuitschematics,lineshowingconnectionsoftencrossovereachother.Inordertomakeitlessconfusing,twolinesareelectricallyconnectedtoeachotheronlywhenthereisacircleovertheirintersection.Otherwise,theyaretwoindependentwiresthatdon’telectricallymakecontact.
PrototypingonaBreadboardYoushouldalwaysprototypeacircuitonabreadboardbeforebuildingyourfinalproject.It’smucheasiertofixanyerrorsbeforeyouhavestartedcuttingwireandsolderingconnectionstogether!BuildthecircuitonabreadboardasshowninFigure3-12.
1. Startbyplacingthetactilepushbuttonontherightofthebreadboard.Itshouldfitoverthegapinthemiddleofthebreadboard,andeachofthefourlegsshouldbepushedintothenearestrows.
2. Placethreepotentiometersevenlyacrosstherestofthebreadboard.Eachlegofthepotentiometersshouldbeinitsownrowonthebreadboard.
3. Useajumperwiretoconnectthe5VpintooneofthelongrowsalongthebottomofthebreadboardandasecondjumperwiretoconnectaGNDpintotheotherlongrow.Ifyourbreadboardislabelled(notallare),thenconnect5Vtotherowwitharedlineor+,andconnectGNDtotherowwithablueorblacklineor-.
4. ConnecttheleftlegofeachpotentiometertothelongrowconnectedtoGNDusingthreejumperwires.
5. Connecttherightlegofeachpotentiometertothelongrowconnectedto5Vusingthreejumperwires.
6. Connectthelower-rightlegofthepushbuttontoGND.7. UsethreejumperwirestoconnectthemiddlepinofeachpotentiometertoPinsA0,
A1andA2.8. Useajumperwiretoconnectthetop-leftlegofthepushbuttontoPin7.9. Makethethreeconnectionsfortheservo.Connectthegroundpinoftheservotothe
longrowonthebreadboardconnectedtoGND,connectthe5Vpinoftheservotothelongrowconnectedto5VandconnecttheremainingpinontheservotoPin9ontheArduinoUno.
FIGURE3-12Circuitforthecombinationsafe
WritingtheCodeJustlikethecircuit,thesketchforthesafelookscomplicatedatfirst.Butafteryoubuilditup,step-by-step,youwillseethatsketchisjustthecombinationofsmallersectionsofcode.Thecodedetectswhetherthebuttonisbeingpressed.Ifitis,theArduinoUnocheckswhetherthethreepotentiometersareturnedtothecorrectvaluestoopenthebox.Iftheyare,thentheboxopens;iftheyaren’t,thennothinghappens.
StartbylaunchingtheArduinoIDE.Startanewsketchwithanemptysetup()andloop():voidsetup(){
}
voidloop(){
}
Attheverytopofyoursketchbeforesetup(),addthefollowinglines:#include<Servo.h>
//Pins
intpotPin1=A0;
intpotPin2=A1;
intpotPin3=A2;
intbuttonPin=7;
intservoPin=9;
//othervariables
intopen1=0;
intopen2=1023;
intopen3=0;
intrange=10;
intboxOpen=0;
Servoservo;
Thefirstlineimportsthelibrarytocontroltheservoandtherestofthelinesarevariables.Thefirstgroup(under//Pins)arethevariablestokeeptrackofwhichpinsareconnectedtothesensorsandactuator.
Thenextfivevariablesareforcontrollingthebox.Thevariablesopen1,open2andopen3arethevaluesthatthepotentiometersneedtobeturnedtoinordertoopenthebox.Becauseitcanbedifficulttoturnthepotentiometertoaprecisenumber(especiallywhenyouaren’tusingSerialMonitortoseetheexactvaluesfromthepotentiometers),therangevariableisusedtodeterminehowcloseyouhavetobetotherightnumber.Forexample,anyvaluefromopen2-rangethroughtoopen2+rangeregistersthesecondpotentiometerasbeinginthecorrectposition.Thelargerthenumberstoredinrange,theeasieritistoopenthebox.
TheboxOpenvariableisusedtokeeptrackofwhethertheboxisopenedorclosed.Theboxstartsclosed,sothevariableissetto0.Whenitisopened,itissetto1andthenchangedbackto0whentheboxisclosed.Theloop()functionholdsthecodethat
controlsboxOpen.
Thelastvariableisafamiliarone:servo.Itisthevariablethatcommunicateswiththeservo.
Thenextstepistoaddthecodetothesetup()://setbuttonpintobeaninputwith
//withpull-upresistor
pinMode(buttonPin,INPUT_PULLUP);
//attachservotopin
servo.attach(servoPin);//attachestheservoonpin9
//totheservoobject
servo.write(90);//startwiththeboxclosed
Serial.begin(9600);//startserialcommunication
Thefirstlineofsetup()setsthepinMode()forthepushbuttonandturnsontheinternalpull-upresistor.Therestofthefunctionattachestheservotoitspin,makessuretheservohasclosedtheboxandthenstartsserialcommunication.
Finishyoursketchbyaddingthefollowingtotheloop()://checkifbuttonispressed
intbuttonValue=digitalRead(buttonPin);
//ifbuttonispressedandboxisclosed
if(buttonValue==0&&boxOpen==0){
//buttonispressed
intpotValue1=analogRead(potPin1);
intpotValue2=analogRead(potPin2);
intpotValue3=analogRead(potPin3);
Serial.print("pot1:");
Serial.print(potValue1);
Serial.print("pot2:");
Serial.print(potValue2);
Serial.print("pot3:");
Serial.println(potValue3);
//ifallvaluesarewithincorrectrange
if(potValue1<(open1+range)&&
potValue1>(open1-range)&&
potValue2<(open2+range)&&
potValue2>(open2-range)&&
potValue3<(open3+range)&&
potValue3>(open3-range)
){
//openthebox
Serial.println("opening");
for(intpos=90;pos>0;pos-=1)
{
servo.write(pos);
delay(15);
}
boxOpen=1;
}
}
//ifbuttonispressedandboxisopen
if(buttonValue==1&&boxOpen==1){
Serial.println("closing");
//closethebox
for(intpos=0;pos<90;pos+=1)
{
servo.write(pos);
delay(15);
}
boxOpen=0;
}
Younowhaveacompletesketchandyouarereadytocheckwhetheryourcircuitisworkingcorrectly.UploadyoursketchtotheArduinoUnoandopentheSerialMonitor.Turnthepotentiometersuntiltheymatchthevaluesstoredinopen1,open2andopen3,andthenpushandholdthebutton.Theservoshouldrotateandstop.Releasethebuttonandtheservoshouldreturntoitsstartingposition.
TheDiggingintotheCodesectiongoesthroughtheloopinmoredetailtoexplainhowyoursafefunctions.Here’sthefullsketch:#include<Servo.h>
//Pins
intpotPin1=A0;
intpotPin2=A1;
intpotPin3=A2;
intbuttonPin=7;
intservoPin=9;
//othervariables
intopen1=0;
intopen2=1023;
intopen3=0;
intrange=10;
intboxOpen=0;
Servoservo;
voidsetup(){
//setbuttonpintobeaninputwith
//withpull-upresistor
pinMode(buttonPin,INPUT_PULLUP);
//attachservotopin
servo.attach(servoPin);//attachestheservoonpin9totheservo
object
servo.write(90);//startwiththeboxclosed
Serial.begin(9600);//startserialcommunication
}
voidloop(){
//checkifbuttonispressed
intbuttonValue=digitalRead(buttonPin);
//ifbuttonispressedandboxisclosed
if(buttonValue==0&&boxOpen==0){
//buttonispressed
intpotValue1=analogRead(potPin1);
intpotValue2=analogRead(potPin2);
intpotValue3=analogRead(potPin3);
Serial.print("pot1:");
Serial.print(potValue1);
Serial.print("pot2:");
Serial.print(potValue2);
Serial.print("pot3:");
Serial.println(potValue3);
//ifallvaluesarewithincorrectrange
if(potValue1<(open1+range)&&
potValue1>(open1-range)&&
potValue2<(open2+range)&&
potValue2>(open2-range)&&
potValue3<(open3+range)&&
potValue3>(open3-range)
){
//openthebox
Serial.println("opening");
for(intpos=90;pos>0;pos-=1)
{
servo.write(pos);
delay(15);
}
boxOpen=1;
}
}
//ifbuttonispressedandboxisopen
if(buttonValue==1&&boxOpen==1){
Serial.println("closing");
//closethebox
for(intpos=0;pos<90;pos+=1)
{
servo.write(pos);
delay(15);
}
boxOpen=0;
}
}
DIGGINGINTOTHECODE
Let’slookattheloop()ofthecodeyou’vejustinputinalittlemoredetail.
ThevalueofthebuttonPinisreadin.Ifthevalueis0andtheboxisclosed,thenthevaluesofeachofthepotentiometersareread:
//checkifbuttonispressed
intbuttonValue=digitalRead(buttonPin);
//ifbuttonispressedandboxisclosed
if(buttonValue==0&&boxOpen==0){
//buttonispressed
intpotValue1=analogRead(potPin1);
intpotValue2=analogRead(potPin2);
intpotValue3=analogRead(potPin3);
ThevalueofeachpotentiometerisprintedtotheSerialMonitortohelpwithanydebugging:
Serial.print("pot1:");
Serial.print(potValue1);
Serial.print("pot2:");
Serial.print(potValue2);
Serial.print("pot3:");
Serial.println(potValue3);
Ifeachpotentiometeriswithinrangeofthecorrectvalue:
//ifallvaluesarewithincorrectrange
if(potValue1<(open1+range)&&
potValue1>(open1-range)&&
potValue2<(open2+range)&&
potValue2>(open2-range)&&
potValue3<(open3+range)&&
potValue3>(open3-range)
){
thentheboxisopenedbyusingaforlooptorotatetothe0position.YouknowiftheboxisclosedifboxOpenis0.Aftertheboxisopen,boxOpengetssetto1sothatyouhaveconfirmationthattheboxisopen.
//openthebox
Serial.println("opening");
for(intpos=90;pos>0;pos-=1)
{
servo.write(pos);
delay(15);
}
boxOpen=1;
}
}
IfthevalueofthebuttonPinis1andtheboxisopen,theboxisclosedbyusingaforlooptorotatetheservotoposition90.TheboxOpenvariableisthensetto0.
//ifbuttonispressedandboxisopen
if(buttonValue==1&&boxOpen==1){
Serial.println("closing");
//closethebox
for(intpos=0;pos<90;pos+=1)
{
servo.write(pos);
delay(15);
}
boxOpen=0;
}
Ifthebuttonispressedwhiletheboxisalreadyopen,orthebuttonisreleasedwhiletheboxisalreadyclosed,thennothingisdoneandtheloop()isrepeated.
CHALLENGESetyoursecretcombinationtoopenthesafeusingtheopen1,open2andopen3variables.Adjusthoweasyitistodialinthenumbersusingrange.
MakingtheSafeAtlast,you’rereadytomakeyoursafe!ThisisverysimilarinconstructiontothestatusmessagesigninAdventure2.You’regoingtouseabox(suchasashoebox)tohousetheelectronics.
1. Attachthelidtothebox.Whenyouattachthelid,makesureyouattachitalongonesidesothatithingesopenandshut.Thatway,theservomotorcandramaticallypushtheliduptoopentheboxwithoutthelidfallingoff.Onewayofdoingthisistomakeapaperhingewithastripofpaperandglue,asshowninFigure3-13.
2. Next,youneedtodecidewhereyouwanttoputyourpotentiometersandbutton.Thisisentirelyuptoyou,althoughyouprobablywantthemtobeonthefrontoftheboxforeasyaccess.Cutholessothattheshaftsofthepotentiometersandbuttonfitsnugly.CutaholethatcanpasstheUSBcableintotheboxtopowertheArduinoUno.
3. Servomotorscomewithaselectionofdifferentarms.Thesepopontotheendoftherotatingshaftoftheservomotor.Youwanttousetheonethatisasinglearmextendingfromtheshaft.(Don’tusethecrossarm.)
Thearmisn’tverylong,soyoucanextenditbyattachinganotherobjecttoit.Youcanuseanythingyoulike,butabambooskewerorpaperclipworkswell.Gluetheobjecttotheservoarmandmakesureit’sfirmlyattached(seeFigure3-14).
4. UploadthesketchforthesafeontotheArduinoUnoandsetuptheprototypecircuitonthebreadboardifyouhaven’tdonesoalready.
5. Removeanyarmattachmentsfromtheservo.IfthecodeisrunningontheArduinoboardandyouaren’tpressingthebutton,theservoshouldberotatedtothe90position.Nowattachtheservoarmsothatitisat90degrees—positionitsothatitwon’tpushthelidoftheboxup.Whenyoudialthecorrectcombinationandpressthebutton,theservoarmshouldrotatetopointstraightup.
6. Theextendedarmoftheservopushesuptheclosedlid,buthowdoesitcloseitagainafterit’sopen?CreateapaperloopthatisattachedtotheundersideofthelidasinFigure3-15.Theextendedarmoftheservogoesinthisloopandusesittopullthelidclosed.
FIGURE3-13Ifthelidisnotalreadyattachedtoyourbox,addapaperhinge.
FIGURE3-14Extendtheservo’sarmbyattachinganobjectlikeapapercliporbambooskewer.
FIGURE3-15Paperloopsotheservocanclosethesafe
SolderingtheWiresUsethefollowingstepstosolderthewires:
1. Placethepotentiometersintheirholesinthebox.MeasureandcutfourpiecesofwirethatreachfromthepotentiometerfarthestfromtheArduinoUnotothenextnearestpotentiometer.Cutthemaboutaninchlongerthanyouneed.Stripabout½”fromtheendofeachwire.RepeatandcutawirethatreachesfromthemiddlepotentiometertotheoneclosesttotheArduinoUno(seeFigure3-16).Thesewiresconnecttheoutsidelegsofthepotentiometerstoeachother.
2. CuttwopiecesofwirethatreachfromtheoutsidelegsofthepotentiometerclosesttotheArduinoUnotothe5VandGNDpinsontheboard.Cutthemaboutaninchlongerthanyouneedandusewirestripperstostripabout½”fromeachendofthewires.
3. Cutapieceofwirethatreachesfromtheclosestpotentiometertotheconnectorontheservo.Cutitaboutaninchlongerthanyouneedandusewirestripperstostripabout½”fromeachendofthewires.
Remembertosolderonlywithadultsupervision.Visitthecompanionsiteforvideosabouthowtosolder(www.wiley.com/go/adventuresinarduino).
4. SoldertheoutsidelegsofthetwopotentiometersfarthestfromtheArduinoUnotoeachotherusingthewiresasshowninFigure3-16.
5. SolderthewiresforthepotentiometerclosesttotheArduinoUno.Oneoftheoutsidelegswillhavetwowiressolderedtoit—onefromthemiddlepotentiometerandawirethatconnectstotheArduinoUno.Theotheroutsidelegsofthepotentiometerwillhavethreewiressolderedtoit—theremainingwirefromthemiddlepotentiometer,awirethatconnectstotheArduinoUnoandawirethatconnectstotheservo.
6. MeasureandcutthreepiecesofwirethatreachfromeachofthepotentiometerstoPinsA0,A1andA2ontheArduinoUno.Cutthemeachaboutaninchlongerthanyouneedandstripabout½”fromtheendofeachwire.
7. Solderoneendofeachwirethemiddlelegofeachpotentiometer.8. Placethepanelmountpushbuttoninitshole.Measureandcuttwopiecesofwire
thatreachfromthepushbuttontoPin7andaGNDpinontheArduinoUno.Cutthewireaboutaninchlongerthanyouneedandstripabout½”fromtheendofeachwire.
9. Solderonewiretoonelegofthepushbuttonandtheotherwiretotheotherleg.
FIGURE3-16Solderedcomponents
Tosummarise:
YouwillhavethreewirescomingfromthemiddlelegofeachpotentiometerthatwilleventuallyconnecttotheArduinoUno.ThepotentiometerfarthestfromtheArduinoUnowillhaveonewireconnectedtoeachoutsidelegthatconnectsthemtooutsidelegsofthenextpotentiometer.Themiddlepotentiometerwillhavetwowiresconnectedtoeachoutsideleg:awireconnectingthatlegtothefirstpotentiometerandawireconnectingittothelastpotentiometer.Thelastpotentiometerwillhavetwowiresconnectedtooneoutsidelegandthreewiresconnectedtotheotheroutsideleg.ThelegwithtwowireswillbeconnectedtothemiddlepotentiometerandtheremainingwirewilleventuallyconnecttotheArduinoUno.Thelegwiththreewiresisconnectedtothemiddlepotentiometer,toawirethatwillconnecttotheservoandtoawirethatwillconnecttotheArduinoUno.Thepushbuttonhasonewireconnectedtoeachleg.ThesewilleventuallyconnecttotheArduinoUno.
Everyboxwillbealittledifferent.Thesizeswillbedifferent,andlidswillbelooserortighter.Youmayhavetobecreativetosolveengineeringproblemssothatyourboxopensandcloses.Forexample,youmightneedtoattachapaperloopontheundersideofthelidsothattheservoarmcatchesitandpullstheliddown(refertoFigure3-15).
Whynottrymakingyourownpaperbox?Findanorigamibookinyourlibraryorlookonlineforaboxandlidpattern.
InsertingtheElectronicsThepotentiometersandpushbuttoncomewithnutsandwashersthatthreadontothebaseoftheshafts.Removethenutsandwashersandthenstickthestemsofthepotentiometersandpushbuttonthroughtheholesyou’vemadeinyourbox.Screwthewashersandnutsbackontosecurethecomponentstothecardboard.Addsomeglueiftheystillwigglearoundmorethanyou’dlike.
Insidethebox,buildyourcircuitbyconnectingthewirestotheirrespectivepinsontheArduinoUno.Oneofthewiressolderedtoanoutsidepinofapotentiometerwiththreewiressolderedtoitshouldbeinsertedin5V;theotheronefromthelegwithtwowiressolderedtoitshouldbeinsertedinaGNDpin.ConnectthethreewiresfromthethreepotentiometerstoPinsA0,A1andA2.ConnectonewirefromthepushbuttontoaGNDpinandtheotherwiretoPin7.Connectthelastwirefromthepotentiometerlegwiththreewiressolderedtoittothe5Vconnectionontheservo.UsetwojumperwirestoconnecttheservotoGNDandin9.
Goaheadandtestitout!Younowhaveaboxwithasecretcodethatautomaticallyopens.Figure3-17showsthecompletedwiring.
FIGURE3-17Completedcombinationsafe
FurtherAdventureswithArduinoNowthatyouhavesomeservoexperienceunderyourbelt,checkouttheseprojects:
http://playground.arduino.cc/ComponentLib/Servo
http://arduino.cc/en/pmwiki.php?n=Tutorial/Knob
WorkingwithservosandArduinoisjustthebeginningofwhatyoucandointhefieldofrobotics.Checkouttheseamazingrobots—manybuiltusingArduino!
http://artbots.org/2011/participants/
http://makezine.com/projects/building-a-simple-arduino-robot/
http://www.makershed.com/collections/robotics
ArduinoCommandQuickReferenceTable
Command Description
#include Commandtoimportalibrary.Seealsohttp://arduino.cc/en/Reference/Include.
Servo.h Librarytocontrolaservo.Seealsohttp://arduino.cc/en/reference/servo.
Servo Objectforcontrollingaservo.Seealsohttp://arduino.cc/en/reference/servo.
Servo.attach() AttachaServovariabletothespecifiedpin.Seealsohttp://arduino.cc/en/Reference/ServoAttach.
Servo.write()Writeavaluetotheservototellitwhatpositiontomoveto.Seealsohttp://arduino.cc/en/Reference/ServoWrite.
for Loopsoverasectionofcodeacertainnumberoftimes.Seealsohttp://arduino.cc/en/Reference/For.
AchievementUnlocked:Youaresuccessfullycombiningcircuitsandcode!
IntheNextAdventure…AfewLEDsaregood,butlotsofLEDsareevenbetter!InthenextadventureyoufindouthowtocontrollargebatchesofLEDswithsmallcircuitchipscalledshiftregisters.
YOUAREWELLonyourwaytobecominganArduinoexpert.You’vetackledallsortsofthings,frommotorstopotentiometers.You’veevenhandledthreepotentiometersatthesametime.Butwhataboutworkingwithmorethanthreeofthesamething?OneLEDisgood,threeLEDsarebetter—buthowabout24LEDs?
AsanexperiencedArduinoengineer,youmighttakealookatyourArduinoboardandquestionmycountingabilities.Therearen’t24outputpinsforLEDsonyourboard?You’reright!Butyoucanharnessthepowerofspecialchipscalledshiftregisterstoextendthenumberofoutputs,andthat’swhatyou’regoingtodointhisadventure.
Codecanstartgettingalittlemessywhenyou’reworkingwithsomanyoutputs,soI’llshowyousomewaystokeepyourcodetidyandeasiertounderstand.
Whenyouputitalltogetherattheendoftheadventure,youwillmakeacarnival-stylelight-upsignthatspellsoutyourname(oranyotherwordyouchoose).
WhatYouNeedForthestartofthisadventure,youneedabreadboard,LEDsandresistors.You’regoingtobeexploringdifferentwaystolightupacollectionofLEDsincode.Youthenfindoutwhatashiftregisterisandhowtouseit.Youneedthefollowingitems;theelectroniccomponentsareshowninFigure4-1:
AcomputerAnArduinoUnoAUSBcable1largebreadboardor2smallones38jumperwires16LEDs16220Ωresistors274HC595shiftregisterintegratedcircuits(ICs)
FIGURE4-1Whatyouneedforthefirstpartofthisadventure
Integratedcircuit(IC)namescanbequitelongandseemcomplicated,buttheyarejustholdingalotoflittlepiecesofinformation.Forthisadventure,you’reusingthe74HC595shiftregister,andthat’sthesetofnumbersandlettersthatyouneedtolookforwhenyoubuythepart.Ifyougetachipthathastwolettersinthepartnumberbefore74HC595,it’sokay.Theseareacodeforthecompanythatmakesthechip.Chipslikeshiftregistersaremadebylotsofdifferentcompanies,soyoudon’tneedtoworryifthechipyouarethinkingaboutbuyinghasthesetwoextraletters.Aslongasthechipsyoubuyhasthenextsetofnumbersandletters(74HC595),whatyouhaveisgood.Theremaybeanadditionallastlettertellsyouwhatshapeorpackagethechipis.Forbreadboardcircuits,youwantittobeNforaDIP(apackagewithtworowsoflegsthatfitsintoabreadboard).Thesection“GettingMoreOutputswithShiftRegisters”explainsmoreaboutwhatthatmeans.
OrganisingYourCodeCodeissimplywritteninstructionsthatacomputercanunderstand.Often,youhavetorepeatthoseinstructions.Insuchcases,youcansavetimebycopyingandpastingthesamepieceofcodemultipletimestogetthecomputertorepeatthesamesetofinstructions.Butwhatifyoumakeasmalltypo?Maybeyoumissasemicolon?Thetiniestmistakecanleadtoyourprogramnotworkingproperly.Itcanbehardtofigureoutwhyitworksthefirsttwotimesandthenfailsthethirdtime.Longsectionsofrepeatedcodecanalsomakeitmoredifficulttofollowwhatishappeninginyoursketch.Yourcodebecomeslessreadable.
Programmersliketojokethattheyarelazyanddon’twanttodomoreworkthannecessary!Socomputerscientistswhowriteprogramminglanguagesspendalotoftimedesigningthewayinstructionsarewrittenout,tohelpminimisetheriskofmakingsimplemistakeswhendoingthingslikecopyingandpastingcode.Thefollowingsectionsintroduceyoutosomeofthetechniquesyoucanusetosimplifyyourcode.
UsingFunctionsOneeasywaytorepeatcodeistoputthelinesofcodeyouwanttoberepeatedintosomethingcalledafunction.It’slikegivinganametoasetofinstructions.Youthenonlyneedtowriteoutthenameofthegroupofinstructionseachtimeyouwantthemtohappen,insteadwritingalloftheinstructionsindividually.
Ifyou’veworkedthroughtheearlieradventures,youhavealreadybeenusingfunctionswrittenbysomeoneelse.Forexample,digitalWrite()isafunctionthatcontrolsaDigitalPinontheArduinoUno.Thefunctionhandlesallthedetailsofturningonandoffthepin;youjusthavetocallthefunction.Nowyougettostartwritingyourownfunctions.
You’regoingtoaddfunctionstotheBlinksketchinthisadventure.YoumightrecallthatI’vetalkedaboutfunctionsbefore—inparticular,thesetup()andloop()functions.Thesearefunctionsjustliketheonesyou’regoingtouseintheBlinksketch,butyoudon’tgettogivethemyourownnames;theyhavetobecalledsetup()andloop().WhentheArduinofirststartsup,itlooksforafunctioncalledsetup()andexecutesthelinesofcodeinit.Itthenlooksforafunctioncalledloop()andrepeatedlydoeswhateverlinesofcodeareinthatfunction.
It’salwayseasiertounderstandanewconceptwhenyougettotryitoutyourself,sotakealookattheBlinksketchyoufirstworkedwithinChapter1.OpenupthesketchbygoingtoFile ⇒ Examples ⇒ 1.Basics ⇒ Blink.ThefirstthingyouneedtodoissaveacopyoftheBlinksketch.You’resavingacopyratherthanusingtheoriginalexamplebecauseyou’regoingtomakesomechangestothesketch,soyoudon’twanttooverwritetheexample.SavethesketchbyselectingFile ⇒ SaveAs.NamethefileBlinkingFunctions.ino.
TakealookatyournewBlinkingFunctionssketch(yourcopyoftheBlinkexamplesketch).Inthesketch,mostoftheactionhappensintheloop()function:
//thelooproutinerunsoverandoveragainforever:voidloop(){digitalWrite(led,HIGH);//turntheLEDon
delay(1000);//waitforaseconddigitalWrite(led,LOW);//turntheLEDoff
delay(1000);//waitforasecond}
Youcancreateyourownfunctionthatdoesthesamethingasthefourlinesofcodeintheprecedingloop()function.Butbeforeyoudothat,holdfire!ThereareacoupleofimportantthingsIwanttohighlightaboutwritingafunctionfirst.
Afunctionalwayshasthreepiecesofinformation,andyouneedtotypeallthreeofthesebeforethefirstcurlybracketofeachpair(seeFigure4-2).
FIGURE4-2Theanatomyofafunction
Thefirstpieceofinformationisthetypeofdatathatwillbeoutputorreturnedfromthefunction.Inmostofthecodeyoucreateinthisbook,thisisjustvoid,meaningthatthereisn’tanythingreturned.Ifthereisdatathatisoutputorreturnedfromthefunction,thedatatypeislistedinsteadofvoid.Forexample,ifyourfunctioncomputesananswerasaninteger,thereturndatatypeisintinsteadofvoid.
Youmighthavenoticedthatthetermvoidkeepsappearingbeforesetup()andloop().Thetermjustmeansthatthefunctiondoesn’treturnanythingwhenit’sfinished.Forexample,youmightwriteafunctionthatcalculatesthesumofthreenumbers,intendingtheanswertothecalculationreturnedtothepositionwhereyoucalledthefunctionsoyoucansavetheanswerinavariable.Thisvariablemightbeanint.Forfunctionsthatsimplyturnonandofflights,noadditionalinformationisneededwhenthefunctionfinishes,sothereturntypeisvoid.
Thesecondbitofinformationisthenameofthefunction.TherulesfornamingafunctionaresimilartonamingavariableasdescribedinAdventure2:
Youcan’thavespacesinthename,butyoucanusenumbersandletters.Youcan’tstartthenamewithanumber.Youmakethefirstletterlowercase.
Youmightfindthelastpieceofinformationalittlehardtofind;it’stheroundbrackets(alsoknownasparentheses).Whenthereisn’tanythingbetweenthefirst(andthesecond),itmeanstherearen’tanyinputarguments.Youcanpassinformationtoafunctionusinginputarguments;andyouseehowtodothatlaterinthissection.
Returntothesketchandgototheverylastlineofcode—theoneaftertheclosingbracketoftheloop()function.Addthefollowingcode,makingsureitisn’tinsideanyotherfunction.(Inotherwords,makesurethatthecodeyou’readdingisnotinsidetheparenthesesorbracketsofanyotherfunction.)
//turnontheLEDfor1second//thenofffor1secondvoidblinkOnce(){digitalWrite(led,HIGH);//turntheLEDon
delay(1000);//waitforaseconddigitalWrite(led,LOW);//turntheLEDoff
delay(1000);//waitforasecond
}
YouhavejustcreatedanewfunctioncalledblinkOnce().Itdoesn’ttakeanyinputarguments(becausethe(and)areemptyafterthefunctionname),anditdoesn’treturnanything(becauseitlistsvoidbeforethefunctionname).Insidethefunction,itblinkstheLEDonfor1secondandthenofffor1second.
It’sagoodhabittoaddacommentatthetopofyourfunctionthatexplainswhatthefunctiondoes.Youcanuse//atthebeginningoftheeachlineor/*and*/atthebeginningandendofaparagraph.Itmightseemunnecessarywhenit’sasimplefunction,butifyoualwaysdoit,thenyou’llalwaysremembertoaddcommentsformorecomplicatedfunctions.Whenyousharecodethat’swellcommented,otherswillbeabletounderstandit,too.
Next,changetheoriginalloop()functionsoitonlycallsyournewfunction:
//thelooproutinerunsoverandoveragainforever:voidloop(){blinkOnce();
}
UploadthesketchtotheArduinoboardbyconnectingyourArduinoUnoandclickingtheUploadbutton.YoushouldseetheLEDblinkonandoffjustliketheoriginalBlinksketchdidinAdventure1.
Nowyou’regoingtoseewhatfunctionscanreallydo.You’regoingtoaddalittlemorecodethataddsavariabletothefunctiontocontrolthespeedoftheblink.
ChangeyourblinkOnce()functiontothefollowing(thechangesareinbold):
//turnontheLEDfortimepassedinargument//thenofffortimepassedinargumentvoidblinkOnce(inttime){digitalWrite(led,HIGH);//turntheLEDon
delay(time);//wait
digitalWrite(led,LOW);//turntheLEDoff
delay(time);//wait}
Byaddingavariablebetweenthe(and),yourprogramissayingthatthefunctionneedssomeadditionalinformationinordertorun.Thisiscalledanargument,andwithityoucanpassinformationdirectlyfromonefunctiontoanother.
ThismeansyouneedtoincludeanargumentwhenyoucallblinkOnce()intheloop()function.Changetheloop()functionagainsoitmatchesthefollowingcode:
//thelooproutinerunsoverandoveragainforever:voidloop(){blinkOnce(1000);
}
Whenyouaddanargumentof1000,theLEDshouldblinkonandoffjustasitdidbefore—onfor1secondandthenofffor1second.
CHALLENGE
MaketheLEDblinkonfor1secondandthenofffor1second,thenonfor5secondsandofffor5seconds.You’llneedtocallthe()functiontwiceintheloop()functionwithdifferentarguments.
UsingforLoopsAnotherusefulwaytoorganiseyourcodeistorepeatsomethingacertainnumberoftimes.Forexample,insteadofgoingtoallthetroubleofwritingafunctionfivetimesinarow,youcanuseanotherpieceofcodetodoitforyou.Aforloopisonewayofdoingthat.
Aforloopneedsthreekeypiecesofinformation,asshowninFigure4-3.
FIGURE4-3Theanatomyofaforloop
Thefirstpieceofinformationisthestartingcondition.Aforloopbeginswithastartingvalueforavariable.Thisisusuallyjustatemporaryvariablethatisonlyusedintheforloop.Itcanbecalledanythingthatyouwouldlike,butprogrammerstendtocallthisvariablei.
Thesecondpieceofinformationiswhatisneededinorderforthelooptostop.Thisisphrasedasatrueorfalsequestionandisoftencheckingifthevariablehasbecometoobig.Itmightbesomethinglikei<10.
Thelastpieceofinformationiswhathappenstothevariableaftereachloop.Thevariableneedstogetfromitsstartingvaluetosomethingthatcausesthelooptoend;otherwiseitwouldjustgoonforeverandyourprogramwouldnevergetpasttheforloop.Thispieceofinformationisusuallyi++,whichsimplymeansadd1toiandsavethenewnumberiniagain.
Makeanewsketch(eitherbyclickingtheNewbuttonintheArduinoIDEorgoingtoFile ⇒ New)andtypethefollowingcode:voidsetup(){Serial.begin(9600);}
voidloop(){inti;for(i=0;i<10;i++){//forloopthatcountsfrom0to9Serial.println(i);//printthecurrentvalueofidelay(1000);//waitfor1second}
delay(3000);//waitfor3seconds}
UploadthecodetoyourArduinoboardandthenopentheSerialMonitorintheArduinoIDEbyclickingontheSerialMonitorbuttonorgoingtoTools ⇒ SerialMonitor.Youshouldseetheforloopcountingfrom0to9overandoveragain.
Trychangingi++toi+=2.Whatdoyouthinkishappening?
GettingMoreOutputswithShiftRegistersIntheearlieradventuresinthebook,youbuiltcircuitswithsomeessentialelectricalcomponents.Thingslikeresistorsarethemostbasiccomponentsbutyoucancombinethemwithotherbasiccomponentstoformmorecomplicatedcircuits.However,youdon’tnecessarilyhavetospendalotoftime(anduseupalotofspace)buildingacomplicatedcircuit.Youcansometimesbuyachipthathasalreadybeenputtogetherforyou,containingmorecomplicatedcircuits.Thesechipsarecalledintegratedcircuits,orICsforshort.
Integratedcircuits(ICs)arecircuitscontainedwithinasinglechip.Thesamecircuitcanbeputintodifferentshapedchips,calledpackages.Whenworkingwithabreadboard,youwantwhatisknownaDIPorDILpackage.That’stheshapethathaslegsthatfitintoabreadboard.
Chipscomeindifferentpackages.Thatjustmeansdifferentsizesandshapes.Whenworkingwithbreadboards,youwillwanttousecomponentsthataredualin-linepackages(shortenedtoDIPorDIL).Theyhavelegsthatfitintoabreadboard.Theothertypeofcomponentpackageisasurface-mountdevice(SMD).SMDpackagesareverysmallandaredesignedtobeeasilyplacedoncircuitboardsinfactories.Theyaremuchmoredifficulttouseincircuitsbuiltathomewithbreadboards.MostofthecomponentsonyourArduinoUno(allthosetinyblackrectanglesandeventheLEDs)areSMDpackages.
Adualin-linepackage(DIPorDIL)isonepossibleshapeofanICchip.Ithastworowsoflegsthatcanfitintoabreadboard.
Asurface-mountdevice(SMD)isonepossibleshapeofanICchiporothercomponentsuchasaresistor.Itismadeforsolderingontoaflatsurfacewithoutanylegsbeinginsertedintoholesonacircuitboard.
Youcanusemultiplechipsinthesamecircuittodothesamethingoverandover.YoucanthinkofICsasbeingthefunctionsofelectroniccomponents.
InthisadventureyouaregoingtouseanICcalledashiftregister.Theshiftregisteryou’llusetakesthreeinputsthatcontrolwhathappensoneightoutputs.SowithjustthreepinsfromtheArduinoboard,youwillbecontrollingeightdifferentLEDs.Evenbetter,youcanattachashiftregistertoanothershiftregisterinachain.SoyoucankeepaddingeightmoreLEDswhilestillonlyusingthreepinsonyourArduinoboard!
Ashiftregisterisadevicethatcancontrolmultipleoutputswithrelativelyfewinputs.ItiscommonlyusedtocontrolalargenumberofLEDs.
HowaShiftRegisterWorksThethreeinputsthatashiftregistertakesaretheCLOCK,theDATAandLATCH.
ClockTheCLOCKisthedrumbeatofthecircuit.MessagesarebeingsentfromtheArduinototheIC.YoucanthinkoftheArduinoassingingasongwiththeIC.InorderfortheICtobeabletofollowalong,theArduinoandICneedtosingatthesametempo.TheCLOCKisaseriesofHIGHandLOWvalues(seeFigure4-4)thatpulsetolettheICknowwhennewinformationisbeingtransmitted,likethedrumbeatthatletstheICfollowalongwiththeArduino.
FIGURE4-4TheCLOCKsignal
DataTheDATAiswhatyouwanteachoftheoutputs(LEDs)tobesetto,whichwillbeeitherHIGHorLOW.AshiftregistercancontroleightLEDs.TheArduinoUnosendstheshiftregisterthevalueoftheLEDsonebyonelikeso:
1. ThefirstLEDvalueissenttotheshiftregisterfromtheArduinoUno.Theshiftregisterssetsthefirstoutputpintobethatvalue.
2. ThesecondLEDvalueissenttotheshiftregister.TheshiftregistersetthesecondoutputpintothevaluethatwassavedinthefirstoutputpinandthensetsthefirstoutputpintothemostrecentvaluesentbytheArduinoUno.
3. TheArduinoUnosendsathirdLEDvaluetotheshiftregister.Thethirdoutputpinnowissettowhatthesecondoutputpinwaspreviouslysetto;thesecondoutputpinissettowhatthefirstoutputpinwassetto;andthefirstoutputpinissettothenewvalue.
4. TheArduinoUnokeepssendingnewvaluestotheshiftregister.Eachtimeanewvaluecomesin,theshiftregistershiftsallthepreviouslysavedvaluesforeachoutputpindowntothenextpin.Thenewestvaluesetsthefirstoutputpin.
Eachtimeyousendtheshiftregisteranewvalueforanoutput,thepreviousvaluegetsshiftedtothenextoutput.That’swherethenameshiftregistercomesfrom!
Whenyouhavefinishedsendingoutputvalues,youneedtotelltheshiftregisterthatyouhavefinishedsoitcanturnonorofftheoutputpinsofthechip—whichiswhatLATCH
does.
LatchThefinalinputisthesignalthattellstheshiftregistertoeitherlistenformoreinformationorgoaheadandoutputtheinformationithas.WhentheLATCHpinisLOW,theICislistening;whenitchangestoHIGH,theICstartsdoingandtheoutputvaluesaresentout.WhenLEDsareconnectedtotheshiftregister,theywillturnonoroffaccordingtothenewvaluesstoredintheshiftregisterwhentheLATCHchangestoHIGH.
Figure4-5illustrateshowthethreeinputsworktogethertocontroltheshiftregister.
FIGURE4-5Howashiftregisterworks
MakingtheConnectionsforaShiftRegisterThefirstthingtodoisbuildyourcircuit.Startbyputtingyourshiftregisterchiponyourbreadboard.Thechipfitsoverthegapinthemiddleoftheboard.Youmayneedtobendthelegsalittletogetthechiptofitnicelyintotheholes.Noticethatthere’salittledotprintedonacornerorahalfcirclecutoutfromoneendofthechip:thisisthetopofthechip,andit’sveryimportantthatthechipisinthesameorientationasthediagramshowninFigure4-6.
ThelegsoftheICcanbedelicate,sotakecarewhenbendingthem.Alsotakecarewhenremovingthechipfromthebreadboardasitcanbeeasytoaccidentallybendthelegs.
FIGURE4-6Pin-outdiagramfortheshiftregister
Youarereadytostartbuildingyourshiftregistercircuit.Figure4-6isapin-outdiagramthatshowstheshiftregisterlabelledwiththepinnumbersforthechipandshowswhatconnectstoeachpinonthechip.NotethatthecolourscorrespondtothewirecoloursinFigure4-7.Nowyouneedtomakethefirstoftheconnectionsbyfollowingthesesteps(don’tconnectyourArduinoUnotoyourcomputeryet):
1. UseajumperwiretoconnectoneofthelongrowsalongthebottomofyourbreadboardtoaGNDpinontheArduinoUno.Ifyourbreadboardisalabelledwithablueorblacklineora-,connectittothatrow.
2. Useajumperwiretoconnecttheotherlongrowalongthebottomofyourbreadboardtothe5VpinontheArduinoUno.
3. Usetwojumperwirestoconnecteachofthelongrowsalongthebottomofthebreadboardtothelongrowsalongthetop.Ifyourbreadboardislabelled,connecttheredor+totheotherrowwithredora+thenconnecttheremainingtwolongrowstoeachother.
4. UsetwojumperwirestoconnecttheshortrowsconnectedtoPin8andPin13onthe
shiftregistertothelongrowonthebreadboardconnectedtoground.5. UsetwojumperwirestoconnecttheshortrowsconnectedtoPin10and16onthe
chiptothelongrowconnectedto5V.6. UseajumperwiretoconnecttheshortrowconnectedtoPin14ontheshiftregister
toPin11ontheArduinoboard.7. UseajumperwiretoconnecttheshortrowconnectedtoPin11ontheshiftregister
toPin12ontheArduinoboard.8. UseajumperwiretoconnecttheshortrowconnectedtoPin12ontheshiftregister
toPin8ontheArduinoboard.
Whenyou’vefinished,yourcircuitshouldlooklikeFigure4-7.Noticetheshiftregisterchipinthemiddle,facinginthecorrectdirection.
FIGURE4-7Firstconnectionsfortheshiftregister
AddingLEDsNowit’stimetoaddtheLEDs.Ifyouhaveasecondbreadboard,youmightfinditeasiertohavetheshiftregisterononeboardandtheLEDsonanother,butyoucanalsofiteverythingonasinglebreadboard.
EachoftheLEDsneedsacurrent-limitingresistor,justlikewhenaLEDishookedupdirectlytoapinontheArduinoboard.Eachoutputoftheshiftregisterisconnectedtoacurrent-limitingresistorandthentoaLED,whichisthenconnectedtoground.
UsingFigure4-8asaguide,followthesestepstoaddyourLEDsandresistors:
1. Placetheshortlegsof8LEDsinthelongrowalongthetopofthebreadboardthatisconnectedtoground.
2. PlaceeachofthelonglegsoftheLEDsintotheirownshortrowsonthebreadboard—wherevertheyeasilyfitisfineaslong(asnothingelseisalreadyconnectedtotherow).
3. PlaceonelegofaresistorintothesameshortrowsasthelonglegsoftheLEDs.4. Bendtheresistorsoverthegapinthemiddleofthebreadboard,andinsertthefree
legsoftheresistorsintotheshortrowdirectlyontheothersideofthegap.5. Useeightjumperwirestoconnecteachresistortoanoutputpinontheshiftregister
—pins15and1through7.UseFigures4-6and4-8asguides.
FIGURE4-8Thefullcircuitfortheshiftregister
Double-checkthatyourconnectionsarecorrect—gothrougheachstepagain.Whenareyousureeverythingisintherightplace,youarereadytopowerthecircuitbyconnectingtheArduinoUnotoyourcomputer.
Yourchipshouldnevergethot!Ifitevergetshot,somethingispluggedinwrong,soyoumustremove
thepowerimmediately.Thechipmightbedamagedandmayneedtobereplaced.Ifitevermakesapoppingsoundandevensmokesalittle,itdefinitelyneedstobereplaced.Besuretocheckoveryourcircuitagainandfindthemistakebeforeputtinginanewchip,oryouwilljustdamagethenextchipinthesameway!
WritingtheCodeCreateanewsketchbyclickingontheNewbuttonintheArduinoIDEorgoingtoFile ⇒ Newandenterthefollowingcode:
voidsetup(){
}
voidloop(){
}
Attheverytopofyoursketch,beforethesetup()begins,addthefollowingvariables:
//Pinconnectedtolatchpin(ST_CP)of74HC595intlatchPin=8;//Pinconnectedtoclockpin(SH_CP)of74HC595intclockPin=12;//PinconnectedtoDatain(DS)of74HC595intdataPin=11;
TheyarethethreepinsfortheLATCH,CLOCKandDATAconnectionstotheshiftregister.
Next,typethefollowingcodebetweenthe{and}ofsetup():
//setpinstooutputbecausetheyareaddressedinthemainlooppinMode(latchPin,OUTPUT);pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
Eachofthoselinesofcodesetupthepinstobeoutputsthatsendoutdatatotheshiftregister(asopposedtoreadingindata).
Lastly,typethefollowingcodebetweenthe{and}ofloop():
//loopthrough0to256inti;for(i=0;i<256;i++){//turnofftheoutputsothepinsdon’tlightup//whileyou’reshiftingbits:digitalWrite(latchPin,LOW);shiftOut(dataPin,clockPin,LSBFIRST,i);
//turnontheoutputsotheLEDscanlightup:digitalWrite(latchPin,HIGH);delay(300);}
Yourcompletesketchshouldnowlooklikethis:
//Pinconnectedtolatchpin(ST_CP)of74HC595
intlatchPin=8;//Pinconnectedtoclockpin(SH_CP)of74HC595intclockPin=12;//PinconnectedtoDatain(DS)of74HC595intdataPin=11;
voidsetup(){//setpinstooutputbecausetheyareaddressedinthemain looppinMode(latchPin,OUTPUT);pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);}
voidloop(){//loopthrough0to256inti;for(i=0;i<256;i++){//turnofftheoutputsothepinsdon’tlightup//whileyou’reshiftingbits:digitalWrite(latchPin,LOW);shiftOut(dataPin,clockPin,LSBFIRST,i);
//turnontheoutputsotheLEDscanlightup:digitalWrite(latchPin,HIGH);delay(300);}}
Youcandownloadthesketchesinthischapterfromthecompanionsite(www.wiley.com/go/adventuresinarduino).
UploadthesketchtoyourArduinoUno.YourLEDsshouldstartturningonandoff.
DIGGINGINTOTHECODE
Sowhatisgoingonintheloop()function?Theloop()functionusesaforloopasdescribedearlierinthisadventure.Insidetheforloop,youcallafunctionnamedshiftOut().ThisisafunctionthattheArduinoknows,andittakesfourarguments.Inthefirstargumentitsendsoutanumberthroughthegivenpin(dataPin),usingthepingiveninthesecondargumenttosendtheCLOCKsignal(clockPin).Thethirdargumentusesakeywordtoindicatewhetherthenumberbeingsentoutstartswiththefirstdigitorthelastdigit(LSBFIRST).Thelastargumentisthenumberbeingsentout.Herethenumberbeingsentoutisstoredini,whichiscontrolledbytheforloop.Itstartsati=1andstopsafteri=255.
shiftOut(dataP0in,clockPin,LSBFIRST,i);
BeforeshiftOut()iscalled,thelatchPinissettoLOW.Thistellstheshiftregistertostopdoingandstartlistening.ThenewvaluesfortheLEDsarethensentintheshiftOut()function,andthenthelatchPinissettoHIGH.Thattellstheshiftregistertostoplisteningandstartdoing.ItthenturnsonandofftheLEDsaccordingtothenewvaluesitjustreceived.
Youmayhavespottedsomethingalittleweirdinthecode.Whydoestheforloopstartat0andcountupto256?Doesn’tthatseemalittlestrange?
Computersliketostartcountingat0.Ashumans,weusuallyskipover0andstartcountingat1,but0istypicallythestartingpointforcomputers.That’swhytheforloopstartsat0.
Andwhyareyouusing255asthemaximumvalue?TheshiftregisteriscontrollingeightLEDs.EachLEDcaneitherbeonoroff,sothat’stwopossiblestatesforeveryLED.Ifa0representsanLEDoffanda1representsanLEDon,youcandescribetheonandoffstatesofalltheLEDswithasinglenumber.11111111wouldbealltheLEDson.10000001wouldbealltheLEDsoffexceptthefirstandlastones.
Thesenumbersarespecialbecausetheydon’tuseallthepossibledigitsbetween0and9,butinsteadonly0and1.Numbersthatuseallthedigitsfrom0to9arecalleddecimalnumbers(whatyouthinkofasnormalnumbers),andnumbersthatcountusingonly0and1arecalledbinary.ThenumberbeingsentoutthedataPinisrepresentedinbinary.
Thesketchthatyoujustwroteisabinarycounter;itshowsyouinlightshowtocountfrom0to255inbinary(0to11111111).
Abinarynumberusesonlythedigits0and1,asopposedtodecimal,whichusesthedigits0through9.Binaryisalsoreferredtoasbase-2.Decimalisreferredtoasbase-10.
Figure4-9showsyouhowtoconvertbinarynumbersintodecimalnumbers.Atthispoint,youdon’tneedtoworrytoomuchaboutthisiflearningaboutdifferentwaysofrepresentingnumbersdoesn’tseemlikemuchfun,butifyoulikesecretcodesandmessages,itmaybeatopicthatyouwillfindveryinteresting.
FIGURE4-9Howtoconvertfromabinarynumbertoadecimalnumber
CHALLENGE
CalculatethedecimalnumberfromthebinarypatternshowninFigure4-10.
FIGURE4-10Howwouldthisbinarypatternberepresentedbyadecimalnumber?
Asingledigitinabinarynumberiscalledabitandagroupof8bitsiscalledabyte.Allcomputingisbasedonbitsandbytes.Ifyou’reinterestedinlearningmore,youcanstartbylookingupmoreinformationonbitsandbytesathttp://en.wikipedia.org/wiki/Bitandhttp://en.wikipedia.org/wiki/Byte.
AddingMoreShiftRegistersToaddanothershiftregister,youneedtoputasecondIConthebreadboard(ifyou’reusingabigbreadboard)oronasecondbreadboard(ifyou’reusingtwosmallbreadboards):
1. Followthestepsyoufollowedearliertoconnecttheshiftregisterto5VandGND.Ifyouareusingasecondbreadboard,besuretoconnectthelongrowsofthatbreadboardtothelongrowsofthefirstbreadboard.
2. InsteadofconnectingPins12,14and11ontheshiftregistertoPins8,11and12ontheArduinoUno,connectPins11and12ofthesecondshiftregistertoPins11and12onthefirstshiftregister.ThisconnectsLATCHandCLOCKfromthefirstshiftregistertothesecondone,asshowninFigure4-11.
3. TheDATAforthesecondshiftregisterdoesn’tcomefromtheArduinoboard,butfromPin9ofthefirstshiftregister.UseajumperwiretoconnectPin14ofthesecondshiftregistertoPin9ofthefirstshiftregister.
4. Followthesamestepsinthe“AddingLEDs”sectionforaddingtheLEDsthefirstshiftregistertoconnect8moreLEDstothesecondshiftregister.
FIGURE4-11Addingasecondshiftregister
Whenyourcircuitisbuilt,youneedtochangeyoursketchsothatitcontrolstwoshiftregistersinsteadofonlyone.Makethechangesshowninboldtotheloop()functionofyoursketch:
voidloop(){//loopthrough0to256inti;for(i=0;i<256;i++){//turnofftheoutputsothepinsdon’tlightup//whileyou’reshiftingbits:digitalWrite(latchPin,LOW);
//sendtosecondshiftregistershiftOut(dataPin,clockPin,LSBFIRST,i);//sendtofirstshiftregistershiftOut(dataPin,clockPin,LSBFIRST,i);
//turnontheoutputsotheLEDscanlightup:digitalWrite(latchPin,HIGH);delay(300);}}
UploadthesketchtoyourArduinoUnoandwatchall16ofyourLEDsturnonandoff.
BuildingYourNameinLightsDifferentelectricalcomponentscanperformthesamefunctionbutlookverydifferentfromeachother.LEDsareanexampleofthis;forexample,youcanuseLEDsindifferentcolourswithouthavingtochangethecircuit,althoughyoustillneedacurrent-limitingresistorandaconnectiontoapositivevoltageandground.
LEDsaremeasuredbytheirwidthandyoucanalsobuythemindifferentsizes.Youareprobablyusing5mmLEDsbutyoucangetthemisallsizessoyoumightliketotrythemin3mmor10mm.The10mmLEDsworknicelyinthisproject,butyoucanusewhateversizeandcolourthatyouthinklooksgood.
Inthisprojectyoucanlightupasmanyas24LEDs.YoucandecidehowyouwanttoarrangethoseLEDsandusethemtoembellishacarnival-stylelettersign.You’regoingtocreateyourowndesignforafantasticsignandputyournameinlights(seeFigure4-12).Youcanchoosewhatyou’dliketospell.Itcanbeyourname(orjustinitialsifyournameisquitelong)oranyotherword—likeLED!
FIGURE4-12Yourname(oranyotherword)inlights!
Youwillchoosewhatlettersyouwouldliketomakeandcutthemoutofcardboard.Thenyoucandecidewhereyouwanttoplacethe24LEDsandaddthemtoyourletters.
Youcanwatchavideoofhowtobuildacarnival-stylelettersignonthecompanionwebsiteat
www.wiley.com/go/adventuresinarduino.
WhatYouNeedFollowingisalistofwhatyouneedtobuildyoursign.RememberthatAppendixAlistsplacesthatyoucanbuytheelectroniccomponentsshowninFigure4-13.
AcomputerAnArduinoUnoAUSBcableAbreadboard(youmayneedseveralifyoubuildalotofletters)57jumperwires24LEDs24220Ωresistors374HC595shiftregisterICs(1forevery8LEDs)Somecardboard(cuttingupoldcardboardboxesworkswell)SomewireSomesolderPaintorcolouredpaperfordecorationAsolderingironMaskingtapeScissorsorautilityknifeApencil,screwdriverorholepunch
FIGURE4-13Theelectroniccomponentsyouneedtobuildyournameinlights
UnderstandingtheCircuitThecircuitforthisprojectisverysimilartotheoneyoubuiltearlierinthischapterusingtwoshiftregisterswith16LEDs.Youcanadduptothreeshiftregistersand24LEDs.Youneedoneshiftregisterforevery8LEDs.
Therearealotofconnectionstomake,souseFigure4-14asaguidetowhatshouldbeconnected.Remember,onlythelinesthatintersectwithacirclearethewiresthatareconnectedtoeachother.
FIGURE4-14Circuitschematicforthreeshiftregisters
PrototypingonaBreadboardAlwayscheckthatyourcircuitisworkingbeforeyoustartsoldering!Prototypethecircuitwiththreeshiftregisters.Youmayneedtousemultiplebreadboards.Followthestepsinthe“AddingMoreShiftRegisters”sectiontosetupthreeshiftregisters.Pin14ofoneshiftregisterwillbeconnectedtoPin11ontheArduinoUno.Fortheothertwoshiftregisters,Pin14onbothofthemconnectPin9ofthenextshiftregister.UseFigure4-11asaguideandaddathirdshiftregistertothesecondshiftregisterinthesamewayyouconnectedthesecondshiftregistertothefirstshiftregister.ConnecteightLEDstoeachoftheshiftregistersusingthestepsin“AddingtheLEDs”section.
WritingtheCodeCreateanewsketchbyclickingontheNewbuttonintheArduinoIDEorgoingtoFile ⇒ New.Typethefollowingcodetobeginwritingyoursketch:
voidsetup(){
}
voidloop(){
}
Atthetopofthesketch,beforethesetup(),addthefollowingvariables:
//Pinconnectedtolatchpin(ST_CP)of74HC595intlatchPin=8;//Pinconnectedtoclockpin(SH_CP)of74HC595intclockPin=12;//PinconnectedtoDatain(DS)of74HC595intdataPin=11;
//numberofshiftregistersusedintnumRegisters=3;
//firstpatterntobedisplayedintpattern1=85;//secondpatterntobedisplayedintpattern2=170;
Insidesetup(),setthepinmodesandcallafunction,setLEDs(),thatyouwillwritelater.Addthefollowingcode:
//setpinstooutputbecausetheyareaddressedinthemainlooppinMode(latchPin,OUTPUT);pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
//startwithallLEDsoffsetLEDs(0);
Insidetheloop()typethefollowingcodetosendablinkingpatterntotheLEDs:
//turnonLEDsinthepattern01010101setLEDs(pattern1);//wait1secdelay(1000);//turnonLEDsinthepattern10101010setLEDs(pattern2);
//wait1secdelay(1000);
TheonlyfunctionmissingisthesetLEDs()function.Thisisanewfunctionthatyouwriting—itisn’tincludedintheArduinoIDE.Typethefollowingcodeaftertheloop()(afterthe})andyoucanreadmoreaboutwhatitisdoingintheDiggingintotheCodesidebar:
//sendspatterntoshiftregisterfor//whichLEDstoturnonandoffvoidsetLEDs(intlightPattern){//turnofftheoutputsothepinsdon’tlightup//whileyou’reshiftingbits:digitalWrite(latchPin,LOW);
inti;for(i=0;i<numRegisters;i++){//sendsoutthepatternonceforeachshiftregistershiftOut(dataPin,clockPin,LSBFIRST,lightPattern);}
//turnontheoutputsotheLEDscanlightup:digitalWrite(latchPin,HIGH);delay(300);}
Followingisthefullsketch,butyoucanalsodownloaditfromthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
//Pinconnectedtolatchpin(ST_CP)of74HC595intlatchPin=8;//Pinconnectedtoclockpin(SH_CP)of74HC595intclockPin=12;//PinconnectedtoDatain(DS)of74HC595intdataPin=11;
//numberofshiftregistersusedintnumRegisters=3;
//firstpatterntobedisplayedintpattern1=85;//secondpatterntobedisplayedintpattern2=170;
voidsetup(){//setpinstooutputbecausetheyareaddressedinthemainlooppinMode(latchPin,OUTPUT);
pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
//startwithallLEDsoffsetLEDs(0);}
voidloop(){//turnonLEDsinthepattern01010101setLEDs(pattern1);//wait1secdelay(1000);//turnonLEDsinthepattern10101010setLEDs(pattern2);//wait1secdelay(1000);}
//sendspatterntoshiftregisterfor//whichLEDstoturnonandoffvoidsetLEDs(intlightPattern){//turnofftheoutputsothepinsdon’tlightup//whileyou’reshiftingbits:digitalWrite(latchPin,LOW);
inti;for(i=0;i<numRegisters;i++){//sendsoutthepatternonceforeachshiftregistershiftOut(dataPin,clockPin,LSBFIRST,lightPattern);}
//turnontheoutputsotheLEDscanlightup:digitalWrite(latchPin,HIGH);delay(300);}
ConnectyourArduinoUnotoyourcomputeranduploadthecode.Yourlightsshouldstartflashing.
DIGGINGINTOTHECODE
Thevariablesatthetopofthecodeandmostofthesetup()shouldlookfamiliartoyou;theyarethesameaswhatyouusedearlierinthisadventure.Thereisonenewvariable:numRegisters.Itiscurrentlysetto3,butifyouwouldliketousefewershiftregisters,youcanchangeittothenumberyouareusing.
There’salsoanewfunction:setLEDs().Thisfunctionisdefinedunderneathloop().Ittakesoneargument:thepatternofLEDstolightup(pattern1orpattern2).
Thepatternisdescribedbyadecimalnumber.Forpattern1,itisthenumber85indecimal,whichis01010101inbinary,soitturnsoneveryotherLEDofeachsetofeightLEDs.TheotherLEDpatternispattern2,whichis170indecimalor10101010inbinary.Itistheoppositeofpattern1—itturnsontheLEDsthatwereoffinpattern1andturnsofftheLEDsthatwereon.SowhentheLEDsalternatebetweenpattern1andpattern2,itcreatesaflashingpattern.
Wantyoursigntolightupinadifferentpattern?It’snottoodifficulttocreateyourown.Writeoutthepatternasasequenceofeight0sand1sandthencalculatewhatthatnumberwouldbeindecimal.Youcanalsouseanonlinecalculatortohelpconvertbetweenbinaryanddecimal;trywww.mathsisfun.com/binary-decimal-hexadecimal-converter.htmlorwww.binaryhexconverter.com/binary-to-decimal-converter.
MakingtheLightsYourfirst—andbiggest—decisionistochoosethelettersyouwillcreate.Remember,youonlyhave24LEDstodecorateyoursignswith.YouneedtodecidewhatlettersyouwouldliketomakeandwheretheLEDswillbeplaced.
1. Traceyourlettersontocardboard.Cardboardfromoldboxesworkswell.Useapairofscissorsorautilityknifetocutouttheletters.
2. Ifyouwanttodecorateyourletterswithpaintorpaper,goaheadanddothatnow.3. Whenanypaintorglueusedtodecorateyourlettersaredry,useatooltopokeahole
inthecardboardletterswhereyouwanttoplaceeachLED.Apencilorscrewdrivercanworkwell.MakesuretheholeisjustbigenoughtosnuglyholdtheLEDinplace.Atthispointyou’rejustdeterminingtheplacementoftheLEDs.Youinsertthelightsintotheholesafteryouhavethewiressoldered.YoushouldnowhaveletterssimilartotheonesinFigure4-15.
FIGURE4-15CardboardletterswithholesforLEDs
SolderingtheWiresUsethefollowingstepstosolderyourcircuit:
1. SolderaresistortothelonglegofeachLED.TwistthelegsoftheresistorandLEDtogethersothattheydon’teasilycomeapartandthensolderthem.
Alwayshaveanadultnearbywhenyouaresoldering.Adventure2hassomemoretipstohelpyoustaysafewhenyousolder.
2. PlacetheLEDsintheirholesinthecardboardletters.BendtheshortlegsofeachoftheLEDstowardsthenextLED(useFigure4-16asaguide).IftheshortlegofanLEDdoesn’treachtheLEDnexttoit,cutapieceofwirethatreachesfromthatLEDtothenext.SoldereitherthewiretoeachLEDortheshortlegofthefirstLEDdirectlytothenext.RepeatforalltheLEDs.YoushouldhaveoneshortlegofanLEDleftoneachletter.TherestoftheshortlegsoftheLEDsshouldbeconnectedtoeachother.
3. YouuseabreadboardtoconnectyourshiftregisterstotheLEDsandtheArduinoUno.DecidewherethebreadboardandArduinoUnowillbeplaced.Theycouldbetapedtothebackofaletterorcouldrestonthetablenexttotheletters.
4. Cut24piecesofwirethatreachfromeachoftheresistorssolderedtotheLEDstothebreadboard.Youmightwanttohidethewiresbytapingthemalongthebackoftheletters,sobesuretocutthemlongenoughforthatifthat’swhatyouwouldliketodo.
5. Stripabout½”fromeachendofallthewiresyoujustcut.SoldereachwiretoitsLED.
6. CutawirethatreachesfromtheremainingshortLEDlegoneachlettertothebreadboard.Youneedoneforeachletter.
7. Stripabout½”fromeachendofthewiresyoujustcut.SoldereachwiretoitsshortLEDlegoneachletter.
FIGURE4-16SolderedLEDsandresistors
InsertingtheElectronicsWhenyou’vefinishedsolderingallyourLEDs,justpopthemthroughtheholesinyourletters.Youmightneedtoaddalittleglueiftheydon’tstayput.ThenyouarereadytobuildyourshiftregistercircuitsontoonebreadboardasshowninFigure4-17:
1. Followthesamestepsyouwentthroughwhenbuildingtheprototypecircuit.Youconnectthe5V,ground,CLOCK,LATCHandDATAlinesasyouhavedonepreviously.
2. TheresistorsaresolderedtotheLEDs,sotheydon’tneedtobeplacedonthebreadboard.Insteadconnectthewiresthatyousolderedtotheresistorstothepinsontheshiftregisters.SeeFigure4-16forguidance.
3. ConnectthewiresfromtheshortlegsofeachLEDtogroundonthebreadboard.4. ConnectyourArduinoUnotoyourcomputerortoapowersupply.
PowerupyourArduinoboardandheypresto!Yournameisinlights!
FIGURE4-17Backoflights
FurtherAdventureswithShiftRegistersYounowhaveagreatdisplaytotryoutdifferentlightanimations.Trywritingyourownfunctionswithlightpatternsofyourowndesign.
Youmightwanttocheckoutsomeofthesetutorialsonline:
http://arduino.cc/en/tutorial/ShiftOut
https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds/the-
74hc595-shift-register
Intheprojectyoujustcreated,youaresendingadecimalnumbertoshiftOut(),whichthenturnsthenumberintoabinarynumbertotelleachoutputpinwhetheritshouldbeHIGHorLOW.Youcanreadmoreaboutbinarynumbersathttp://en.wikipedia.org/wiki/Binary-coded_decimal.
ArduinoCommandQuickReferenceTable
Command Description
voidTellsthecomputerthatnodatawillbereturnedbyafunctionwhenitfinishes.Seealsohttp://arduino.cc/en/Reference/Void.
shiftOut()SendsaseriesofHIGHandLOWvaluesintimewithaCLOCKsignal.Seealsohttp://arduino.cc/en/Reference/ShiftOut.
AchievementUnlocked:Skillfulengineerofshiningsigns!
IntheNextAdventureInthenextadventure,youwilllearnhowtoaddaspeakerandplaymusictotransformyourArduinointoanelectronicsynthesiser!
THEREARELOTSofwaystomakecodecontrolthingsintherealworld.YouhavealreadycontrolledmovementwithmotorsandcontrolledlightwithLEDs.Inthisadventureyou’regoingtocreatesound!
InAdventures3and4,youdiscoversomenewwaystomakeyourcodemoreefficientwhenyouneedtorepeattheinstructionsmorethanonce.Theforloopisagreattoolforrepeatingsomethingasetnumberoftimes.Whenyoucombineaforloopwithspeciallistsincode—calledarrays—youendupwithapowerfulcodingtool.
AfterlearninghowtoharnessthepowerofarraysandfiguringouthowtogetyourArduinotosingtoyou,you’regoingtoputyournewskillsintopracticebybuildinganaugmentedwindchimethatplaysbothacousticandelectronicsounds.
WhatYouNeedYouneedafewthingsforthefirstpartofthischapter(theelectroniccomponentsareshowninFigure5-1):
AcomputerAnArduinoUnoAUSBcableAbreadboard7jumperwires6LEDs6220ΩresistorsApiezo
Figure5-1Theelectroniccomponentsyouneedforthefirstpartofthisadventure
MakingaListVariablesareusefulwaysofkeepingtrackofinformationlikethenumbersofthepinsonyourArduinoUno.CreatingavariabletostorethenumberofthepintowhichaparticularLEDisconnectedmakesyourcodeeasiertoreadlateron.Whenyoucreateavariablelikethis:intledPin=12;
youcanwritethislater:digitalWrite(ledPin,HIGH);
insteadofhavingtowritethis:digitalWrite(12,HIGH);
Usingthevariablemakesyourcodeeasiertoread.YoumightnotrememberwhatisconnectedtoPin12,butthevariableledPinmakesiteasiertofigureoutwhatthecodeisdoing.
ButwhatifyouwanttokeeptrackofmorethanoneLED?Well,youcouldcreateavariableforeachpin,likethis:intledPin1=3;
intledPin2=4;
intledPin3=5;
intledPin4=6;
intledPin5=7;
intledPin6=8;
Butthatdoesn’tseemveryefficient!Whyshouldyouhavetotypethesamethingoverandoveragainwhen,asweknow,computersaregoodatdoingthesamethingmanytimes.Theremustbeabetterway,right?
Thereis!Computers,includingtheArduino,cancollectinformationinlistscalledarrays.Insteadofhavingtocreateavariableforeachpieceofinformation,youcreateavariablethatisanarray.Wheneveryouwanttorefertooneoftheitemsinthearray,yousimplygivethenumberofthatitem.Figure5-2showsexamplesoftwoarrays.
Anarrayisalistofthesametypeofthingincode.Forexample,anarraycanholdalistofints.
Figure5-2Twoexamplearrays
Theonelittletricktorememberwitharraysisthatthefirstitemisn’tnumber1;it’sactuallynumber0.So,forexample,ifyouwantedtousethefirstiteminthelistcalledledPins,youwouldtype:ledPins[0]
IfyouwanttoturnonanLEDonthepinnumberstoredinthethirditeminthearray,youwouldtype:digitalWrite(ledPins[2],HIGH);
MakingYourIntentionsKnownSo,howdoyoucreateanewarray?Youdon’tjustcreateavariablethatholdsasinglenumber,likeanintorfloat.Theprocessinvolvesmorestepsthanthat.
Afloatisadatatypefornumbersthataren’twholenumbersbutincludeadecimalplacesuchas1.3or-54.089.
Thefirststepistodeclarethenewvariablethatwillholdthearray.Declareisjustafancywordforsomethingyouhavealreadybeendoinginyoursketches.Itmeanscreatinganewvariablebygivingitanameandadatatype.ThefollowinglineofcodedeclaresanewvariablecalledledPinthatcontainsanint:intledPin;
Declaringavariableiswhereyoucreateanewvariablebygivingitanameandadatatypesuchasint.Thevariabledoesnotholdavalueuntilitisgivenitsfirstvalue.
Ifyoualreadyknowwhatvalueyouwanttostoreinthevariablewhenyoucreateit,youcaninstantiateitatthesametime.Thatjustmeansgivingitastartingvalue:intledPin=13;
Instantiatingavariableiswhereyougiveitavalueforthefirsttime.Instantiationcanhappenatthesametimeyoudeclarethevariable,oryoucandoitlater,butthedeclarationalwaysneedstocomefirst.
Youdon’thavetodeclareandinstantiatethevariableatthesametime.;youcandeclareavariableandinstantiateitlateroninyourcode:intledPin;
//somemorecodehappenshere
ledPin=13;
Becarefulifyoudecidenottoinstantiateavariableatthesametimethatyoudeclareit.Youcan’tusethatvariableuntilithasavalue,oryourArduinocodemightnotworkasyouwouldexpect.
TodeclareandcreateanewarrayofsixintegerscalledledList,usethefollowingcode:intledList[6];
Theprecedingcodeisonlyalittledifferentfromwhatyouwouldtypetocreateanewvariablethatholdsanint.AfterthevariablenameledList,thereis[6].The[]meansthatinsteadofasingleint,thevariableisgoingtoholdanarrayofints.The6isthe
numberofintsthearraywillhold.
Nowthatyouhavecreatedthearraybydeclaringit,youcaninstantiateit,andfillitwithvalueslaterinthecode:ledList[0]=3;
ledList[1]=4;
ledList[2]=5;
ledList[3]=6;
ledList[4]=7;
ledList[5]=8;
Declaringanarrayandnotinstantiatingitatthesametimeisusefulifyoudon’tknowwhatvaluesneedtogointothearraywhenyoucreateit.However,ifyoualreadyknowwhatallthevaluesshouldbe,youcaninstantiatethearrayatthesametimeyoudeclareit,asshownhere:intledList[]={3,4,5,6,7,8};
Thevaluestobestoredinthearrayarelistedbetween{and}.The[]nolongerneedsanumberinit,becausethenumberofitemsinthearrayisestablishedbythenumberofitemsin{}.
LoopingThroughanArrayIt’seasytodothesamethingwitheachiteminanarraywithoutcopyingandpastingthesamecodemultipletimes.Youcanuseaforlooptodothis.Asyoumightrememberfromearlieradventures,aforloophasthreepartsthatdeterminehowmanytimesitisrun.Anewvariable,oftennamedi,iscreatedandusedtocountthroughtheloop.Inthefollowingcode,theloopwillrunsixtimes:inti;
for(i=0;i<6;i++){
}
i++indicatesthatthevariableiincreaseseachtimethecomputerrunsthroughtheloop.Insteadofaccessingasingleiteminthearray,suchasledList[3],thevariableicanbeusedtoaccessthenextiteminthelisteachtimethroughtheloop.Here’sanexample:inti;
for(i=0;i<6;i++){
Serial.println(ledList[i]);//printthenextiteminthelist
}
Youcanalsowriteaforloopsothatitmakesachangetoeachiteminthearray:inti;
for(i=0;i<6;i++){
ledList[i]=i+2//add2toeachiteminthearray
}
DIGGINGINTOTHECODE
Thecodesnippeti++isshorthandfori=i+1,butthat’snottheonlyusefulcodesnippet.Ifi++increasesibyadding1toitandsavingthenewnumberini,youmightbeabletoguesswhati--does.That’sright;itsubtracts1fromiandsavesthenewnumberini.
Anotherwaytoincreaseiby1istowritei+=1;similarlyyoucandecreaseiby1bywritingi-=1.Youcanusetheseconventionstoincreaseanddecreaseavariablebyanynumber,sotoincreaseiby3itwouldbei+=3ortodecreaseby7itwouldbei-=7.
PuttingItIntoPracticeThat’senoughtalkingaboutwhathappensincode.It’stimetolightupsomeLEDsandactuallyseewhathappensincode!
Thiscircuitisoneyouhaveseenmanytimesbeforeinotheradventures—anLEDwithacurrentlimitingresistor.Thistime,you’regoingtosetupsixofthemondigitalPins3to8,asshowninFigure5-3:
1. StartbyusingajumperwiretoconnectaGNDontheArduinoUnotoalongrowonthebottomofthebreadboard.Ifyourbreadboardislabelledwithablueorblacklineora–,connectGNDtothatrow.
2. PlacethesixLEDsacrossthebreadboardbyinsertingtheshortlegofeachLEDintothelongrownowconnectedtoGND.Spreadthemoutevenlyacrossthebreadboard.
3. PlacethelonglegofeachLEDintoashortrowthatiseasyforthatLEDtoreach.Itdoesn’tmatterwhichrowsyouuse;theonlyimportantthingisthateachLEDisinitsownshortrow.
4. ConnectonelegofaresistortoeachshortrowthatyoujustinsertedtheLEDinto.Bendthelegsoftheresistorssothattheyreachoverthegapinthemiddleofthebreadboard,andinserttheotherresistorlegintotheshortrowacrossthegap.
5. ConnecteachresistortoanoutputpinontheArduinoUno.UsesixjumperwirestoconnectPins3through8totheresistors.
Figure5-3ThecircuitforanarrayofLEDs
Thefollowingcodeletsyouputintopracticesettingupanarrayofvalues.Here,eachoftheitemsinthearrayisapinnumberthatcontrolsanLED.SothewholearrayofLEDscanbeblinkedinthesamewayyouwouldblinkasingleLED.ThepinMode()issetforeachofthepins,andeachpinissettoHIGHandthenLOW://pinsforleds
intledList[]={
3,4,5,6,7,8};
//numberofpins
intnumPins=6;
voidsetup(){
inti;
for(i=0;i<numPins;i++){
//setpinstoOUTPUT
pinMode(ledList[i],OUTPUT);
}
}
voidloop(){
//blinktheLEDsonebyone
inti;
for(i=0;i<numPins;i++){
//turnontheled
digitalWrite(ledList[i],HIGH);
delay(500);
//turnofftheled
digitalWrite(ledList[i],LOW);
delay(500);
}
}
Whathappensifyouchangetheforloopintheloop()functiontofor(i=numPins-1;i>=0;i--)?
DIGGINGINTOTHECODE
YoursixLEDsarenowblinkingonandoff,onebyone,buthowisthecodemakingthathappen?Let’sstartatthetopofthesketch.Thereyouseethevariablesbeingused.ThefirstisanarrayledListthatholdsallthepinnumbersfortheLEDs,andthesecondisanint,numPins,thatstoresthetotalnumberofLEDpins:
//pinsforleds
intledList[]={
3,4,5,6,7,8};
//numberofpins
intnumPins=6;
Goingoninthecode,youcometoyourfirstforloopofthesketchinsetup().TheforloopisusedtosetthepinmodeofeachoftheLEDpinstoOUTPUT.Thevariableiisusedtoiteratethrougheachiteminthearray:
inti;
for(i=0;i<numPins;i++){
//setpinstoOUTPUT
pinMode(ledList[i],OUTPUT);
}
Thesecondforloopofthesketchisinloop().Thevariableiisusedagaintoiteratethroughthearray.Thistime,insteadofsettingthepinmodeforeachpin,thepinisturnedonbybeingsettoHIGH.TheArduinoUnowaitsfor500mswhendelay(500)iscalled,andthenthepinisturnedoffbybeingsettoLOW.TheArduinoUnoispausedfor500msagainbeforegoingontothenextpininthearray.
//blinktheLEDsonebyone
inti;
for(i=0;i<numPins;i++){
//turnontheled
digitalWrite(ledList[i],HIGH);
delay(500);
//turnofftheled
digitalWrite(ledList[i],LOW);
delay(500);
}
Becausetheforloopisinsideloop(),itgetscontinuouslyrununtiltheArduinoUnoisnolongerpowered.
MakingNoiseIt’snotunusualforcomputerstomakesounds.Youprobablylistentomusicstoredonamusicplayerorphone(whicharetypesofcomputers)allthetime,butyoumightnothavegivenmuchthoughttohowthecomputerphysicallycreatesthesoundyouhear.
Soundisjustvibrations(usuallyvibrationsintheair)thatourearscandetect.Thespeedatwhichsomethingvibratesdetermineswhetheritsoundsloworhigh.ThevibrationsaremeasuredinHertz(Hz),whichisequivalenttocyclespersecond.Humanscanheararound20Hzto20,000Hz,thoughaswegetolderwetendtonothearhighfrequenciesaswellaswedowhenweareyounger.Figure5-4illustrateshowsoundismade.
Figure5-4Howsoundismade
So,howdoesacomputergetairtovibrate?AcomputerorArduinoUnocanoutputachangingvoltagethatalternatesbetweenpositiveandnegative.Aloudspeakertakesthatchangingvoltageandturnsitintovibrations.Onetypeofloudspeakerusesapiezoelement.Thisusuallylookslikeagolddiscwithtwowirescomingfromit,althoughitissometimesenclosedinplastic.
Apiezoisacrystalthatexpandsandshrinkswhenelectricityisrunthroughit.Italsogenerateselectricitywhenitissqueezedorbent.
Nowthatyouknowalittlebitabouthowcomputersgeneratesound,youcanmakeyourArduinoproducesometones.YouknowthattheArduinooutputs0and5VbecauseyouhaveuseddigitalWrite()tosetapintoLOW(0V)andHIGH(5V).MakinganArduinoboardoutputavoltagebetween0and5Visactuallyatrickythingtodo.LuckilytheArduinolibraryhasabuilt-insetoffunctionsthatdoesthisandgeneratessoundwithoutyouneedingtoknowthedetails.Ofcourse,ifyouwouldliketoknowmoreabouthowsoundisgenerated,youcanreadmoreintheArduinodocumentationathttp://arduino.cc/en/Reference/Tone.
WiringtheCircuitApiezohastwowiresattachedtoit.TheblackwireconnectstoGNDontheArduinoboardandtheredwireconnectstothepinthattheaudioplaysfrom.ConnecttheblackwiretoGNDandtheredwiretoPin8now,asshowninFigure5-5.
Figure5-5Thecircuitforausingapiezoasaspeaker
WritingtheCodeThemainfunctionforcreatingsoundistone().Itcanbeusedintwoways.Thefirstistogivethreearguments:thepinthatthesoundshouldplayfrom;thefrequencyofthesound;andhowlongthesoundshouldplay.Here’sanexample://playonPin8atoneof750Hzfor1000ms(1s)
tone(8,750,1000);
delay(1000);
Noticethatrightafterthetone()functionthereisadelay()function.Evenifthetone()functionistoldhowlongtoplayasound,theArduinoboardstillneedstobetoldtowaitforthesoundtofinishplayingbeforetone()iscalledagain.Thedelay()functionspecifieshowlongthatwaitshouldbe.
Theotherwaytousethetone()functionistogiveitonlytwoarguments:thepinthatthesoundshouldplayfrom;andthefrequencyofthesound.Thesoundstartsplayingwhenthefunctioniscalled,anditdoesn’tstopuntilthefunctionnoTone()iscalled,asinthefollowingcode://playonPin8atoneof750Hz
tone(8,750);
//othercodecanhappenhere
//stopthetone
noTone(8);
Thefunctionstone()andnoTone()canbeusedinsetup()ifyouwantsoundtoplayonlyoncewhentheArduinoisfirstpowered,orintheloop()ifthesoundshouldplayrepeatedly.
AsyouhavealreadyconnectedthepiezototheArduinoboard,allthatremainsisforyoutouploadthefollowingcode:intpiezoPin=8;
voidsetup(){
//play3toneswhentheboardfirststarts
tone(piezoPin,523,200);
//delayisslightlylongerthantone
//sothatthereissilenceinbetweenthesounds
delay(210);
tone(piezoPin,784,200);
delay(210);
tone(piezoPin,1047,250);
delay(260);
}
voidloop(){
//play5moretones
tone(piezoPin,523,200);
delay(210);
tone(piezoPin,587,200);
delay(210);
tone(piezoPin,659,200);
delay(210);
tone(piezoPin,698,200);
delay(210);
tone(piezoPin,784,200);
//wait5secondsbeforestartingtheloopover
delay(5000);
}
WhentheArduinofirstrunsthecode,youshouldhearthreenotesmagicallyringingout.Thethreenotesshouldthenplayinarepeatedpattern(thatgoesonandonandonandon…).
DIGGINGINTOTHECODE
Sowhatexactlyishappeninginthesketchyoujustuploaded?Theformatofthesketchissimilartotheothersyouhaveworkedwith:Variablesarecreatedatthetop,anythingthathappensonlyonceisdoneinsetup(),andeverythingelsethathappensrepeatedlyisdoneinloop().
Thissketchonlyhasonevariable:
intpiezoPin=8;
Thesetup()inprevioussketcheshasbeenusedtosetpinmodes.Thatdoesn’tneedtohappeninthissketchbecausetheonlypinbeingusedisoutputtingsoundusingtone().Instead,youusetone()todemonstratethedifferencebetweensetup()andloop().Thesetup()playsthreetonesbeforetheloop()playsfivetones.Thetonesinsetup()onlyplayonce,whentheArduinoUnoisfirststarted,butthefivetoneskeepplayingandplayinguntilyouremovepowerfromtheboard.
Thesetup()onlycallstwofunctions.Thefirstistone(),whichtellstheArduinoUnowhatfrequencytoplayonwhatpinandforhowlong.Thendelay()iscalledtomaketheArduinoUnowaitforthetone()tofinishplayingbeforecontinuingontothenextlineofcode.
//play3toneswhentheboardfirststarts
tone(piezoPin,523,200);
//delayisslightlylongerthantone
//sothatthereissilenceinbetweenthesounds
delay(210);
tone(piezoPin,784,200);
delay(210);
tone(piezoPin,1047,250);
delay(260);
Theloop()isjustlikesetup()exceptitplaysfivetonesinsteadof
three:
//play5moretones
tone(piezoPin,523,200);
delay(210);
tone(piezoPin,587,200);
delay(210);
tone(piezoPin,659,200);
delay(210);
tone(piezoPin,698,200);
delay(210);
tone(piezoPin,784,200);
//wait5secondsbeforestartingtheloopover
delay(5000);
Ifyouknowhowtoreadsheetmusic,openFile ⇒ Examples ⇒ 02.Digital ⇒ toneMelody.Youcansee
thattherearetwotabsintheArduinoIDE:onelabelledtoneMelodyandanotherlabelledpitches.h.
Thetabpitches.hisalistofvalueslikethis:
#defineNOTE_B031
JustpayattentiontoNOTE_B0and31.ThefirstisthemusicalnoteBandthenumber(31,inthisexample)isthefrequencyforthatnote.Thenumbernexttothenote(likethe0inB0)istheoctave.Youcanusethesenumberstohelpyouwritemusicalmelodies.
CHALLENGE
Thefollowingcodeusesanarraytoplaythesamesequenceofsounds.CreateanewsketchwiththefollowingcodeanduploadittoyourArduinoUno.Trychangingthearraysoitplaysthepitchesinreverse(hightolowinsteadoflowtohigh):
intpiezoPin=8;
intpitches[]={
523,587,659,698,784};
intnumPitches=5;
voidsetup(){
//play3toneswhentheboardfirststarts
tone(piezoPin,523,200);
//delayisslightlylongerthantone
//sothatthereissilenceinbetweenthesounds
delay(210);
tone(piezoPin,784,200);
delay(210);
tone(piezoPin,1047,250);
delay(260);
}
voidloop(){
//play5moretones
inti;
for(i=0;i<numPitches;i++){
tone(piezoPin,pitches[i],200);
delay(210);
}
//wait5secondsbeforestartingtheloopover
delay(5000);
}
BuildinganAugmentedWindChimeAnaugmentedmusicalinstrumentiswhatcanbecalleda“normal”musicalinstrument—suchasatrumpetorpiano—thathaselectronicsaddedtoit.Theelectronicsletthemusicianuseacomputerormicrocontrollertoaddtothesoundthattheinstrumentnaturallymakes.
Asyouhavejustdiscovered,theArduinohasasetoffunctionsthatcangeneratesound.YouknowthattheArduinocanalsoreadininformationfromitspins,soyoucancombinereadingfrompinstotriggerdifferentsounds.Tocompletethisadventureinsound,you’regoingtoaugmentawindchime(seeFigure5-6)sothatitdoesn’tjustmaketheusualsoundswhenit’sbuffetedbythewindbutalsoplaystonesproducedbytheArduino!
Figure5-6Anaugmentedwindchime
Youcanwatchavideoonhowtomakeyouraugmentedwindchimeonthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
Therearelotsofaugmentedinstrumentsthatyoucanreadaboutandlearnfrom!Herearesomeofmyfavourites,butyoucandosomeresearchonlineandfindevenmore:
MagneticResonancePiano:www.eecs.qmul.ac.uk/~andrewm/mrp.htmlDigiDidgeridoo:http://createdigitalmusic.com/2009/12/digi-didgeridoo-augmented-wireless-digital-instrument-with-aboriginal-
roots
AugmentedBeatboxing:www.cs4fn.org/music/beatboxing.php
WhatYouNeedYouneedthefollowingitemstobuildyouraugmentedwindchime.Figure5-7showstheelectroniccomponentsyouneed.
AcomputerAnArduinoUnoAUSBcableAbreadboard12jumperwires5tactilepushbuttonsAstripof5headerpinsA9VbatteryA9Vbattery-to-DCbarreljackconnectorSomethinwireSmallpieceofsolidcorewireSomestring,ribbonoryarn10beads(plasticorglasslargeenoughtopassstringorribbon)6washersorotherconductiveobjecttoactasthechimesSomestiffcardboardorplastictouseasthebaseMaskingtapeAsolderingironSomesolderScissorsorautilityknifeApencilorholepunchAmultimeterwithcontinuitytest
Figure5-7Theelectroniccomponentsyouneedtomakethewindchime
UnderstandingtheCircuitThere’snottoomuchtothecircuitforthewindchime;itcombinesswitcheswithapiezospeaker.Thefunpartisthatthefinalcircuitusesmaterialsthatyoudon’tnormallyseeinelectronics.Beforeexperimentingwithnewmaterials,it’sagoodideatobuildaprototypeofthecircuitonabreadboardtomakesureitworksasyouexpectitto.
Figure5-8showsthecircuitschematicforthewindchime.Itlooksverydifferenttothefinishedwindchime!Thechimesactasswitches,eventhoughtheydon’tlooklikenormalswitches.
Figure5-8Circuitschematicfortheaugmentedwindchime
PrototypingonaBreadboardThecircuitconsistsoffiveswitchesondigitalpinsandonepiezoonanotherdigitalpin.Becauseyoulearnedhowtousetheinternalpull-upresistorintheArduinoUnoinAdventure3insteadofneedingtoaddaresistortotheswitchcircuits,therearen’tthatmanycomponents.
BuildthecircuitshowninFigure5-9:
1. Placefivetactilepushbuttonsacrossthegapinthemiddleofthebreadboardsothattwoofthelegsareinsertedinshortrowsabovethegapandtheothertwolegsareinsertedinrowsbelowthegap.
2. UseajumperwiretoconnectaGNDpinontheArduinoUnotoalongrowalongthebottomofthebreadboard.Ifthebreadboardislabelledwithablackorbluelineora–,usethatrow.
3. Usefivejumperwirestoconnectthebottom-rightlegofeachpushbuttontothelongrowconnectedtoGND.
4. Usefivejumperwirestoconnecttheupper-leftlegofeachpushbuttontoPins3through7ontheArduinoUno.
5. Connecttheredwireofthepiezotoanyemptyshortrowonthebreadboard.UseajumperwiretoconnectthatshortrowwithPin8ontheArduinoUno.
6. ConnecttheblackwireofthepiezotothelongrowconnectedtoGND.
Figure5-9Breadboardprototypecircuit
ThewindchimecircuitisalittledifferentfromthecircuitinAdventure3thatusedaswitch.Insteadofpushbuttonswitches,you’reusingconductivemetallicitems(suchaswashersoranythingelseyouchoose)connectedtowiresdanglingfromthewindchime’sbase.Eachoftheseconductiveitemsisconnectedtoadigitalpin.Asixthconductiveitemthat’sconnectedtoGNDhangsinthemiddle.Whenthewindcausesthemiddleconductivechimetocomeintocontactwithoneofthechimesconnectedtoapin,itiselectricallythesameaspushingthebuttononthecombinationsafeinAdventure3.
WritingtheCodeLaunchtheArduinoIDEandopenanewsketch.Typethefollowingcodeinyoursketch:intchimes[]={
3,4,5,6,7};//arrayofpinsforchimes
intnumChimes=5;//totalnumberofchimes
intpiezoPin=8;//pinforpiezo
voidsetup(){
inti;
//setpinModeonallthechimespins
for(i=0;i<numChimes;i++){
pinMode(chimes[i],INPUT_PULLUP);
}
}
voidloop(){
inti;
for(i=0;i<numChimes;i++){
//readinvalueonpin
intvalue=digitalRead(chimes[i]);
//ifLOW(meaningithasconnectedtoground
if(value==LOW){
//playthesound
tone(piezoPin,(100*i)+200,30);
delay(1);
}
}
}
UploadthesketchtoyourArduinoUnoconnectedtothetactilepushbuttonsandpiezocircuityoujustbuilt.Youshouldhearadifferentpitchplayedwheneachbuttonispressed.
Ofcourse,youcanchangewhatisplayedwheneachchimeistriggered.Comeupwithyourownmusicalalgorithm!
DIGGINGINTOTHECODE
Themainpartsofthesketchuseanarray,aforlooptoiteratethroughthatarray,andthetone()function.Thearraychimes[]storeseachpinnumberthatisconnectedtotheconductivechimes(orprototypedwithapushbutton).
intchimes[]={
3,4,5,6,7};//arrayofpinsforchimes
intnumChimes=5;//totalnumberofchimes
intpiezoPin=8;//pinforpiezo
Thesetup()thensetsthepinmodesforeachofthepinsconnectedtothepushbuttonsorchimes.Becausetheyareinputsthatusetheinternalpull-upresistorsintheArduinoUno,youusetheargumentINPUT_PULLUP.
inti;
//setpinModeonallthechimespins
for(i=0;i<numChimes;i++){
pinMode(chimes[i],INPUT_PULLUP);
}
Theforloopintheloop()checksthevalueofeachpin.WhenachimeconnectstoGND,atone()isplayed.Becauseyou’veusedaninternalpull-upresistor,youknowthatthevalueofapushbuttonorchimeisHIGHwhenit’snotconnectedtoground,andthenthevaluechangestoLOWwhenitisconnectedtoground.Thefrequencyofthetone()isdeterminedbywhichchimetriggeredthesound.
inti;
for(i=0;i<numChimes;i++){
//readinvalueonpin
intvalue=digitalRead(chimes[i]);
//ifLOW(meaningithasconnectedtoground
if(value==LOW){
//playthesound
tone(piezoPin,(100*i)+200,30);
delay(1);
}
}
MakingtheWindChimeNowthatyouknowthatyoursketchisworkingcorrectlyandyouhavebuiltatestcircuitonyourbreadboard,youarereadytomakeyourwindchime.Thewindchimeisconstructedfromabasefromwhichhangsixchimes—fiveouterchimesandagroundedinnerchime.Youcanmakethewindchimefromanymaterialsyoulike,butit’simportantthatthechimesareconductiveandthattheyareelectricallyconnectedtotheArduinoUno.Visitahardwarestoreandlookthroughallthesmallmetalfasteningstochoosewhatyouwanttouseaschimes.Washerscomeinmanydifferentsizes,butyoumightpreferhexagonalnutsovercircularwashers.
MakingtheBaseYoucanmakethebasefromanythingthatisstrongenoughtosupportyourchimesandcanalsoholdanArduinoUnoandbattery.Stiffcardboardorplasticaregoodoptions.
First,cutacirclefromthebasematerialthat’sapproximately6inchesindiameter.Pokesixsmallholesinit;thestringsandwirespassthroughtheseholes.Fiveoftheholesshouldbeevenlydistributedaroundtheoutsideofthebase,andthesixthholeshouldbeinthecenter.
Pokefourmoreholesaroundtheedgesofthebase.Theseareforthestringstohangthechime.
MakingtheChimesWhenyouchoosewhatmaterialtousetomakethechimes,youneedtoremembertwoimportantcharacteristics:youneedtobeabletosolderwirestoitanditmustconductelectricity.Totestifyoucansoldertoit,justtrytodoit!Whatevermaterialyouhavechosen,itwillprobablytakeafewmoresecondstogethotenoughtosolderthansomethingsmalllikeawire,sobepatient.
Onlysolderwhenanadultisnearbytohelp!Ittakesalotofheatfromtheirontogetyourchimehotenoughtomeltsolder.Italsotakesalongertimetocooldownafteryou’vesolderedyourwiretoit.Beverycarefulandwaitatleast5minutesbeforepickingupsomethingyou’vesoldered.
Tocheckwhetherthematerialconductselectricity,youneedamultimeter.Amultimetermeasuresmultiplethings(soit’saprettygoodname),includingvoltageandresistance.Youneedameterthatalsomeasurescontinuity.Continuityindicateswhethercurrentcanflowbetweenthetwoprobesattachedtothemeter,whichindicatesconductivity.Notallmultimetershaveacontinuitytest,sopayattentiontothelistedfeaturesofthemultimeterbeforeyoubuyit.
Testyourpotentialchimebytouchingitintwodifferentspotsonthechimewiththeprobes(seeFigure5-10).Ifthemultimeterbeeps,yourmaterialisconductive.Ifit
doesn’t,youshouldfindsomethingelsetouse.
Figure5-10Conductivitytest
Ifyouareusingverythinwirethandoesn’thaveaplasticsleevearoundit,itmaystillhaveathincoatingofinsulationonit.Ifyouhaveproblemssolderingitoritfailsacontinuitytest,youcanscrapeofftheinsulatingcoatingwithsomesandpaperoranailfile.
Afteryouhavechosenyourmaterialforyourchimes,solderawiretoeachofthem.ThewireshouldbelongenoughtoreachfromwhereyouwantthechimetohangthroughthebaseandtotheArduinoUno.Wrapthewireseveraltimesaroundyourchime(seeFigure5-11)andmakesureyouhaveastrongelectricalconnectionandthensolderittothechime.
Figure5-11Achime
Asyet,thewireistooweaktosupportthechimebyitself.Chandeliersareheldupbyastrongchainwithawirethatrunsalongittolightupthebulbs.Inthesameway,togiveyourwindchimeextrasupport,thenextsectionwillshowyouhowtousestringorribbontohangthechime.
AttachingtheChimesThemostimportantthingtorememberisthatthestringorribbonshouldbearalltheweightofthechime;thewireisjusttheretoconductthesignalfromtheArduinotothechime.Thewireshouldnotbearanyweight.
TieapieceofstringorribbonaroundthechimeasshowninFigure5-12.Bringthewireandribbonupthroughtheholetogetherandthenthreadabeadontothestringorribbon—notthewire.Tieaknotinthestringorribbontokeepthebeadinplaceandkeepthechimefrompullingthestringbackthroughthebase(seeFigure5-12).
Dothiswithallsixchimes.
FIGURE5-12Achimeattachedtothebase
ConnectingtheElectronicsYouarealmostfinished!Nowtocompletethefinalfewsteps:
1. Solderasmallsectionofsolid-corewiretothechimehangingfromthecenter.PlugthatwireintoGNDontheArduinoboard.
2. TapetheArduinoboardandpiezotothetopofthebase.ConnecttheblackwireofthepiezotoaGNDpinontheArduinoboardandconnecttheredwiretoPin8.
3. Soldereachofthewiresfromthefiveremainingchimestoapinonthesectionofheaderpins.Thisissometrickysoldering,sojusttakeyourtime.Placetheheaderpinsinabreadboardtoholdthepinsupright.Heatupaheaderpinwiththesolderingironandcoatitinsolder.Thenheatuptheendofthewireandcoatitinsolder.Placethewiresoittouchestheheaderpinandheatupbothagainsothatthesoldercoatingthemmeltsandconnectsthemtogether.Repeatthisprocessfortheremainingpins.
4. PushtheheaderpinsintoPins3through7.5. ConnectthebatterytotheArduinoboardusingthebatteryholder(seeFigure5-13)
andattachthebatterytothebaseusingtape.
Figure5-13Topofbase
Cuttwomorepiecesofstringabout24”long.Thesewillhangyourwindchime.Foldthemeachinhalfandthreadeachendofthestringsthroughoneofthefourholesonthebase.Theendsshouldstickoutfromthebottomofthebase.Tieabeadontoeachstringtokeepthestringfrompullingbackthroughthebase.Hangupyourwindchime,andenjoyyouraugmentedsounds!
FurtherAdventureswithSoundYouarenowasoundsavant!Youcancontrolsoundalongwithlightandmotionfromyourcircuitandcodeknowledge.Plus,younowknowthatyoudon’thavetogotoaspecialshoptobuymaterialsforyourcircuits.Youcantestwhethersomethingconductselectricityandstartusingeverydayhouseholditemsinyourcircuits.
Ifyou’dliketoreadmoreabouthowtousetone(),visittheArduinodocumentationathttp://arduino.cc/en/reference/tone.
Youmightwanttocheckoutsomeoftheseotherexamplesandtutorialsonline:
http://arduino.cc/en/Tutorial/Tone
http://arduino.cc/en/Tutorial/Tone2
http://arduino.cc/en/Tutorial/Tone3
http://arduino.cc/en/Tutorial/Tone4
http://itp.nyu.edu/physcomp/labs/labs-arduino-digital-and-analog/tone-
output-using-an-arduino/
https://learn.adafruit.com/adafruit-arduino-lesson-10-making-sounds
IfyouarecuriousaboutexactlyhowtheArduinomakessound,checkouttheWikipediapageonPulseWidthModulation(PWM)athttp://en.wikipedia.org/wiki/Pulse-width_modulation.Adventure6showsyouhowPWMisusedtocontrollightinsteadofsound.
ArduinoCommandQuickReferenceTable
Command Description
[]Indicatesthatthevariableisanarrayofvariablesratherthanasinglevariable.Seealsohttp://arduino.cc/en/Reference/Array.
tonePlaysasoundwithagivenfrequency.Ifadurationisgivenaswell,thesoundplaysonlyforthatlengthoftime;otherwise,thesoundplaysuntilnoToneiscalled.Seealsohttp://arduino.cc/en/Reference/Tone.
noTone Stopsthetonefromplaying.Seealsohttp://arduino.cc/en/Reference/NoTone.
AchievementUnlocked:Inspirationalengineerofsound!
IntheNextAdventureInthenextadventure,youuseevenmorematerialsthatyouwouldn’texpectinanelectricalcircuit.Youalsofindouthowtocontrolacolour-changingLED!
IT’STIMETOpushtheboundariesofyourArduino!InpreviousadventuresyouusedDigitalandAnalogPinsonyourArduinoUno,butwhat’sthedifferencebetweenadigitalandanaloguesignal?YouhaveoutputonaDigitalPininAdventures1through3,havereadinfromaDigitalPininAdventures2and5,andreadinfromanAnalogPininAdventure2,butwhataboutoutputtinganaloguesignals?Well,thatcomesnext.Butthenwhat?Afteryou’vetackledoutputtinganaloguesignals,isthatit?IsthattheendofArduinocoding?Notatall!
YoucanpushyourArduinoevenfurtherbyusinglibraries.Thisallowsyoueasilytoincorporatecleverfunctions,whichhavebeenwrittenbyotherpeople,intoyoursketches.Inthisadventureyouwillusealibrarythatletsyouturn(almost)anythingyoulikeintoatouchsensor.Youarethengoingtobuildamagicalcrystalballthatglowswhenyouwaveyourhandsoverit.
WhatYouNeedYouneedthefollowingitemsforthefirstpartofthisadventure.TheelectroniccomponentsareshowninFigure6-1.
AcomputerAnArduinoUnoAUSBcableAbreadboard4jumperwires1LED1RGBcommoncathodeLED3220Ωresistors110MΩresistor
Figure6-1Theelectroniccomponentsyouneedforthefirstpartofthisadventure
AnalogueOutIfyouhavecompletedAdventures1,2or4,youknowthatdigitalWrite()candotwothings:output5VwhensettoHIGHoroutput0VwhensettoLOW.YouthenusedigitalRead()toreadinwhetherapinisconnectedto5Vor0V.YoucancheckoutAdventure3ifyouneedarefresheronusingdigitalRead()toreadfromapushbutton.
YoualsoknowfromAdventures2and3thatifyouwanttomeasureavoltageonapinthatisbetween0Vand5V,youneedtouseanalogRead().Itreturnsanumberbetween0and1023thatcorrespondstotheinputvoltage.Soitstandstoreasonthatifyouwanttooutputavoltagebetween0Vand5V,thereisprobablyafunctioncalledanalogWrite()thatwouldletyoudothat.That’sabsolutelycorrect!
Butfirst,whatexactlyisthedifferencebetweenananalogueanddigitalsignal?Adigitalsignalisanelectricalsignalthatcanonlybeoneoftwothings—eitheronoroff.Whenrepresentedinelectricity,it’seither5V(on)or0V(off).Whenrepresentedincode,it’seitherHIGH(on)orLOW(off).
Adigitalsignalisasignalthatisonlyeitheronoroff,HIGHorLOW.OntheArduinoUno,aHIGHsignalis5VandaLOWsignalisground.
Ananaloguesignalisasignalthatcanbevaluesbetweenonandoff.Whenrepresentedinelectricity,itcanbeanyvoltagebetween0Vand5V.Whenrepresentedincode,itcanbeanynumberbetween0and1023.Figure6-2furtherillustratesthedifferencebetweenanalogueanddigitalsignals.
AnanaloguesignalisasignalthatvariesbetweenLOWandHIGH.OntheArduinoUno,ananaloguesignalcanbemeasuredasanumberbetween0forgroundand1023for5V.Ananaloguesignalcanbeoutputasavaluebetween0for0Vand255for5V.
Figure6-2Analogueanddigitalsignals
YoucanoutputadigitalsignalusingdigitalWrite()andcanuseanyDigitalPinontheboard.YoucanalsoreadinadigitalsignalusingdigitalRead()usinganyDigitalPinandreadinananaloguesignalusinganyAnalogPin.Tooutputananaloguesignal,youuseanalogWrite(),butyoucanonlyusespecialDigitalPins.OutputtingavaluebetweenHIGHandLOWistrickierforamicrocontrollerthanoutputtingadigitalsignal,sothereareonlysomeofthepinscandothat.ThesearenicelymarkedonyourArduinoboardwiththe~symbol.OntheArduinoUno,thesearePins3,5,6,10and11(seeFigure6-3).
Figure6-3ThepinsthatsupportanalogWrite()
TheotherimportantthingtoknowisthatnotallArduinopinscanuseanalogWrite().
ReadingandwritingHIGHandLOWtoandfromapinissuper-easyforamicrocontrollerliketheArduinoUnotodo.AlltheinputandoutputpinsontheArduinoboardcandothis—andareverygoodatit.Youcanevenuseanalogpinstoinputoroutputadigitalsignalwhenyouhaverunoutofavailabledigitalpins.ReadinginoroutputtingavoltagethatisbetweenHIGHandLOWishardertodoandrequiressomespecialfunctionalityinthemicrocontroller.ThisiswhyanalogRead()onlyworksonA0throughA5.AndanalogWrite()onlyworksonpinsmarkedwitha~.
JustlikedigitalWrite(),analogWrite()takestwoarguments.Thefirstargumentdefineswhichpinshouldbeusedandtheseconddetermineswhatvoltageshouldbeoutput.Thissecondargumentisalittledifferentfromotherarguments.Youdon’tuseHIGHorLOW;insteadyouuseanumberbetween0and255,with0usedfor0Vand255for5V.Thefollowingexamplecode,outputsasignalonPin6thatisroughlyonethirdof5V,sosetthesecondargumentto83:analogWrite(6,83);
Ifyouwantedtooutputalmostthemaximum(5V),youwoulduseanumberjustunder255:analogWrite(6,249);
FadinganLEDWhywouldyouwanttooutputavoltagebetween0Vand5V?Therearelotsofreasons,butonecommonuseistosmoothlyfadeanLEDonandoff.
StarttheArduinoIDEandopenFile⇒Examples⇒03.Analog⇒Fading.BuildanLEDcircuitwithacurrentlimitingresistoronPin9(seeFigure6-4):
1. UseajumperwiretoconnectaGNDpinontheArduinoUnotoalongrowalongthebottomofthebreadboard.Ifthebreadboardislabelledwithablackorbluelineor–,connectthepintothatrow.
2. InserttheshortlegoftheLEDintotherownowconnectedtoaGNDpin.3. InsertthelonglegoftheLEDintoanynearbyshortrow.Insertonelegoftheresistor
intothesameshortrow.4. Inserttheotherresistorlegintoanyothershortrow.Useajumperwiretoconnect
thatshortrowtoPin9ontheArduinoUno.
Uploadtheexampleandseewhathappens.YoushouldseetheLEDfadeonandoff.
Figure6-4LEDcircuitforfadinganLED
ThisexamplecombinesanalogWrite()withtheforloopyouhavealreadybeenusinginAdventures3through5.ThefirstforloopslowlyincreasesthevoltageoutputtotheLED://fadeinfrommintomaxinincrementsof5points:
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
//setsthevalue(rangefrom0to255):
analogWrite(ledPin,fadeValue);
//waitfor30millisecondstoseethedimmingeffect
delay(30);
}
Thesecondforloopdoestheopposite,anddecreasesthevoltage://fadeoutfrommaxtomininincrementsof5points:
for(intfadeValue=255;fadeValue>=0;fadeValue-=5){
//setsthevalue(rangefrom0to255):
analogWrite(ledPin,fadeValue);
//waitfor30millisecondstoseethedimmingeffect
delay(30);
}
CHALLENGE
IncreasethespeedatwhichtheLEDfadesonandoffbyadjustingthedelay()time.NowtryincreasingthefadingspeedbychangingfadeValue.
DIGGINGINTOTHECODE
UsingtheanalogWrite()functionactuallyrequiresalittlebitofatrick,becauseitdoesn’treallyoutputasteadyvoltagesomewherebetween0Vand5V.Infact,itusespulsewidthmodulation(PWM).YoumighthavenoticedthatitsaysPWMonyourArduinoboardnexttothe~symbol.PWMoutputsasignalthatswitchesbackandforthbetweenonandoffatdifferentspeeds.ThishappenssofastthatwhenyoulightupanLEDusingPWM,youreyesdon’tseetheswitchingbackandforth.Insteadtheyseesomethinginbetween,likeanLEDatonlyhalfpower.
Pulsewidthmodulation(PWM)ishowtheArduinoboardgeneratesanoutputsignalbetween0Vand5V.ThesignalswitchesquicklybetweenLOWandHIGHandtheresultingoutputvoltageisbetweenthetwovoltages.
Figure6-5showsthreeexamplePWMsignals.Thetoponeisasignalthatismostlyoff,sotheLEDappearsonlydimlyon.Themiddlesignalisonhalfthetimeandoffhalfthetime,sotheLEDappearsroughlyhalfasbrightasanLEDsettoHIGH.Thebottomsignalisonalmostallthetime,sotheLEDappearsalmostasbrightasonethatissettoHIGH.
Figure6-5PulsewidthmodulationexamplesTheratioofhowlongthesignalisoutputtoHIGHversusLOWdetermineshowbrighttheLEDappears.Thisratioiscalledthedutycycle.ThemoretimethesignalisHIGH,thehigherthevoltageappearstobeandthebrightertheLEDseemstoshine.
ThedutycycleistheratiooftimeasignalisHIGHversusLOWinagivencycle.InPWM,thehigherthedutycycle,thehighertheoutputvoltage.
MixingLightTherearemanydifferentkindsofLED,andtheycomeinallshapesandsizes.Thekindyou’veusedinpreviousadventuresiscalledthrough-holeLEDs—thatjustmeanstheyhavelegsandifyouwanttoattachthemtoacircuitboardtheboardhastohaveholesforthelegstogothrough.
LEDsalsocomeinmanydifferentcolours.Red,yellowandgreenarethemostcommon,butyoucanbuyothercolourssuchasblueandorange.TherearealsoLEDsthatarereallythreeLEDsputintowhatlookslikeoneLED.ThesearecalledRGBLEDs,whichstandsforred–green–blueLEDs.
AnRGBLED(red–green–bluelight-emittingdiode)isasingleLEDwithfourlegsthatcontainsthreelights:onered,onegreenandoneblue.Thethreelightsshareeitheracommonanodeoracommoncathode.
TherearetwokindsofRGBLED,andbothofthemhavefourlegs(seeFigure6-6).Threeofthelegsareforthecolours(red,greenandblue).Thefourthlegisasharedleg,eitherasharedpositiveleg(ananode)orasharednegativeleg(acathode).Forbothtypes,youneedthreecurrentlimitingresistors,asyouwouldwiththreeseparateLEDs.
Figure6-6RGBLEDs
Ananodeisthepositivelegofadirectionalcomponent,suchasthelonglegofanLED.
Acathodeisthenegativelegofadirectionalcomponent,suchastheshortlegofanLED.
ThebigdifferencebetweenthetwokindsofRGBLEDisthatthecommonanodeLEDcircuitsharesacommonpowersource,suchas5V,andthecommoncathodeLEDsharesacommonground.It’sabiteasiertothinkabouthowelectricityflowswithacommoncathodeRGBLED,sothat’stheonewe’lluse.
WiringtheCircuitThelongestlegoftheLEDisthecathode—thelegthatgoestoground.Theotherthreelegsareconnectedtothered,greenandbluelightswithintheLED.Tohavethebestcontroloverthelights,usethreeArduinopinsthatcanuseanalogWrite().Pins9,10and11aregoodchoices.BuildthecircuitshowninFigure6-7:
1. TheonlyfiddlypartwhenworkingwithRGBLEDsisfiguringoutwhichlegcontrolswhichcolour.ThebestwaytodeterminethisistoconnecteachLEDlegindividuallyto5Vandseewhatcolourlightsup.Remembertousethecurrentlimitingresistor;don’tdirectlyconnect5VtotheLED.
2. UseajumperwiretoconnectaGNDpinontheArduinoUnotoalongrowalongthebottomofthebreadboard.Ifthebreadboardislabelledwithablackorbluelineor–,connectthepintothatrow.
3. PlacetheRGBLEDinthebreadboardsothateachlegisinitsownshortrow.UseajumperwiretoconnectthelongestlegoftheLEDtothelongrowconnectedtotheGNDpin.
4. Insertonelegofa220ΩresistorintothesamerowaseachofthecolourlegsoftheLED.Bendtheresistoroverthegapinthemiddleoftheboard,andinsertthelegofeachLEDintoitsownshortrow.
5. FindtheredlegandconnecttheresistornowconnectedtoittoPin9withajumperwire;repeattoconnecttheresistorconnectedtothegreenlegtoPin10;andtheresistorconnectedthebluelegtoPin11.
Figure6-7CircuitconnectinganRGBLEDtoanArduinoboard
WritingtheCodeThecodeforcontrollinganRGBLEDlooksjustlikecodethatcontrolsthreeLEDs.CreateanewsketchintheArduinoIDEandwritethefollowingcode.
Youcandownloadallthecodeinthisbookthatisn’tfromtheexamplesthatcomewiththeArduinoIDE.Youcanfinditonthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
//LEDPins
intredPin=9;
intgreenPin=10;
intbluePin=11;
voidsetup(){
//setpinstoOUTPUT
pinMode(redPin,OUTPUT);
pinMode(greenPin,OUTPUT);
pinMode(bluePin,OUTPUT);
}
voidloop(){
//red
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(redPin,fadeValue);
delay(30);
}
for(intfadeValue=255;fadeValue>=0;fadeValue-=5){
analogWrite(redPin,fadeValue);
delay(30);
}
//green
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(greenPin,fadeValue);
delay(30);
}
for(intfadeValue=255;fadeValue>=0;fadeValue-=5){
analogWrite(greenPin,fadeValue);
delay(30);
}
//blue
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(bluePin,fadeValue);
delay(30);
}
for(intfadeValue=255;fadeValue>=0;fadeValue-=5){
analogWrite(bluePin,fadeValue);
delay(30);
}
//blue+increasingred
digitalWrite(bluePin,HIGH);
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(redPin,fadeValue);
delay(30);
}
//turnblueoffagain
digitalWrite(bluePin,LOW);
//green+increasingred
digitalWrite(greenPin,HIGH);
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(redPin,fadeValue);
delay(30);
}
//turngreenoffagain
digitalWrite(greenPin,LOW);
//turnoffred
digitalWrite(redPin,LOW);
//blue+increasinggreen
digitalWrite(bluePin,HIGH);
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(greenPin,fadeValue);
delay(30);
}
//turnblueoffagain
digitalWrite(bluePin,LOW);
//turnoffgreen
digitalWrite(greenPin,LOW);
//turnallontomakewhite
digitalWrite(redPin,HIGH);
digitalWrite(greenPin,HIGH);
digitalWrite(bluePin,HIGH);
delay(2000);
//turnalloff
digitalWrite(redPin,LOW);
digitalWrite(greenPin,LOW);
digitalWrite(bluePin,LOW);
}
UploadthesketchtoyourArduinoUnoconnectedtotheRGBLEDcircuityoujustbuilt.TheLEDshouldrepeatedlygothroughacoloursequence.
DIGGINGINTOTHECODE
Thecodegoesthroughalightsequencethatfirstlightsupthedifferentcoloursindividuallyandthenlightsupdifferentcombinationsofred,greenandbluetocreateothercolours.Thetopofthesketchstartbydefiningvariablesforeachpin:
//LEDPins
intredPin=9;
intgreenPin=10;
intbluePin=11;
Thesetup()thensetsthepinmodesforeachoftheLEDpins:
//setpinstoOUTPUT
pinMode(redPin,OUTPUT);
pinMode(greenPin,OUTPUT);
pinMode(bluePin,OUTPUT);
Theloop()thenstartsthecoloursequence.First,eachcolouroneachpinisfadedonandoff,onebyone,usingtwoforloopsforeachpin.Thefollowingcodeisjustfortheredpin,butitisrepeatedforthegreenandbluepins:
//red
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(redPin,fadeValue);
delay(30);
}
for(intfadeValue=255;fadeValue>=0;fadeValue-=5){
analogWrite(redPin,fadeValue);
delay(30);
}
Thentwopinsarelitupatatimetoshowwhattheresultinglightlookslike.Thefollowingcodeisforcombiningblueandred:
//blue+increasingred
digitalWrite(bluePin,HIGH);
for(intfadeValue=0;fadeValue<=255;fadeValue+=5){
analogWrite(redPin,fadeValue);
delay(30);
}
//turnblueoffagain
digitalWrite(bluePin,LOW);
Afterblueandredlightcomesblueandgreenlight.Finally,allthreecoloursareturnedonatthesametimeandthenturnedoffbeforethewholeloop()startsoveragain:
//turnallontomakewhite
digitalWrite(redPin,HIGH);
digitalWrite(greenPin,HIGH);
digitalWrite(bluePin,HIGH);
delay(2000);
//turnalloff
digitalWrite(redPin,LOW);
digitalWrite(greenPin,LOW);
digitalWrite(bluePin,LOW);
Youwillseethatyoucanstilltellthedifferencebetweenthered,greenandblueLEDsinsidetheRGBLEDwhentheyareallon.Itmaylookmorewhitethanwhenonlyoneortwoofthecoloursareon,butitwon’thavecompletelymixed.TheRGBLEDyouareusingisfairlycheap,andyoucanspendmoremoneyononesthatmixtheircoloursbetter,butthesearegreattousewhenyouarejuststartingout!
Asyou’llknowifyou’veeverpaintedsomething,twocolourscanbemixedtogethertocreateanewcolour.Forexample,ifyoumixblueandyellowpaintyougetgreenpaint.Mixingallthepaintcolourstogethercreatesblack—oratleastadarkcolourlikeblackorbrown.Itcanbetrickytoproduceblackwithoutbeingveryprecisewithexactlywhatcoloursyoumixtogether.
Thephysicsbehindmixingpaintcoloursiscalledsubtractivemixing.Mixinglightisdifferenttomixingpaint,however.Forexample,ifyoumixredandgreenlightitcreatesyellow;andifyoumixred,greenandbluelightitresultsinwhitelight.Thisprocessiscalledadditivemixing.SeeFigure6-8forexamplesofthetwotypesofmixing.YoucanresearchadditivemixingonlinetolearnmoreabouthowtocreatedifferentcolourswithyourRGBlight.
Figure6-8Mixinglightversusmixingpaint
CapacitiveSensingYouprobablydon’trealiseitbutyoualreadyinteractwithcapacitivesensorseveryday;forexample,mosttouchscreensonsmartphonesandmusicplayersusecapacitivesensors.What’sexcitingisthatyoucanuseanArduinotobuildyourowncapacitivesensor.
Capacitanceistheabilitytostoreanelectricalcharge.Haveyoueverwalkedacrossacarpetedroomthentouchedsomethinglikeacatorafriend’sarmandreceivedanelectricshock?Thatdemonstratesthatyoustoreelectricalcharge.Acapacitivesensordetectswhensomethingthatstoreschargeisnearby.
Capacitanceistheabilitytostoreanelectricalcharge.Electricalcomponentsbuiltespeciallytoholdchargearecalledcapacitors,butotherobjects—evenpeople—alsohavecapacitance.
Thecodethatsenseswhensomeoneistouchingorneartoacapacitivesensorisabitcomplicated.Unlessyouarereallyinterestedinthedetailsofhowitworks,youdon’tneedtodealwithalltheinsandoutsofthecode—luckily,that’swherelibrariescomein!
AddingaLibraryAlibraryisacollectionoffunctionsthatarebundledtogether.It’saneasywayofwritingbitsofcodethatotherpeoplecanuseandisalsoaneasywayofusingbitsofcodewrittenbyothers.Itmeansyoudon’thaveto“reinventthewheel”whenotherpeoplehavealreadydoneitforyou.SomelibrariesareincludedwiththeArduinoIDE,butwhenyouusealibrarythatisn’tincluded,youneedtodownloaditandputinaplacewheretheIDEknowstolook.
Alibraryisacollectionofreusablefunctionsincodethatcanbeimportedandusedinmultiplesketches.
Inthiscase,you’regoingtousethecapacitivesensinglibrarythatyoucandownloadfromhttp://playground.arduino.cc/Main/CapacitiveSensor.
1. Downloadandunzipthefolderfromhttps://github.com/arduino-libraries/CapacitiveSensor/zipball/master.Thefoldermaybecalledsomethinglikearduino-libraries-CapacitiveSensor-3e33f75—thelettersandnumbersattheendofthefilemightdiffer.InsideshouldbeafoldercalledlibrariesthatholdstwofoldersnamedCapacitiveSensorandCapacitiveSensorDue.
2. TheArduinoIDEonlylooksfornewlibrariesinoneplace:thelibrariesfolderinsideyoursketchbook.YoursketchbookisafoldercalledArduinoinsideyourDocumentsorMyDocumentsfolder,dependingonyouroperatingsystem.MovetheCapacitiveSensorandCapacitiveSensorDuefoldersandeverythinginthemintothelibrariesfolderinyoursketchbook(asshowninFigure6-9).
3. IftheArduinoIDEisalreadyopen,closeandrestartit;otherwise,justopenit.4. Tocheckwhetherthelibraryhasinstalledcorrectly,gotoSketch⇒ImportLibrary
andseeifCapacitiveSensorandCapacitiveSensorDueappearinthelistlikeinFigure6-10.AlsogotoFile⇒Examples,whereyoushouldseeCapacitiveSensorlisted.
Figure6-9PlacethedownloadedandunzippedfolderinthelibrariesfolderoftheArduinosketchbook.
Figure6-10Checkforthelibraryandexampleinthemenus.
Ifyoudon’tseetheexampleorlibrarylistedinyourmenus,tryrestartingtheArduinoIDE.Ifthatstilldoesn’tmakethemappear,gobackthroughthestepsandmakesureyouhaverenamedthedownloaded
foldercorrectlyandhaveputitinthecorrectlibrariesfolder.
WiringtheCircuitThecircuitforacapacitivesensorusestwopins.Onepinsendsoutasignaltoanantenna,thesecondpinlistenstothatsignalcomingbackin.Theantennacanbeanythingconductive.Foilworkswell,butyoucanalsoalwaysjustuseawirewithoutanythingconnectedtoit.Whenacapacitiveobject(likeyourfinger,forexample)isneartheantenna,thereceivedsignalischangedaccordingtohowclosethecapacitiveobjectis.Thelibraryreportsbackanumberthatcorrespondstohowcloseorfarawaythecapacitiveobjectis.
Youmaywanttosolderaplainpapercliptoawire(makesurethepaperclipdoesn’thaveaplasticcoating;youcanstripitwithwirestrippersifitdoes).Thenyoucanusethepapercliptoattachtoanobjectlikefoilandusethewiretoconnectthefoiltoyourbreadboard.
Thecircuitforacapacitivesensorusesaresistorbetweentheantennaandthesendingpin.Youneedtouseaverylargeresistor—atleast10MΩ(that’s10millionOhms)!BuildthecircuitshowninFigure6-11:
1. Insertonelegofa10MΩresistorinthemiddleofthebreadboard.Inserttheotherlegintoanyotherrow.
2. UseajumperwiretoconnectonesideoftheresistortoPin2ontheArduinoUnoandasecondjumperwiretoconnecttheothersideoftheresistortoPin4ontheArduinoUno.
3. ConnectanotherjumperwiretothesameshortrowonthebreadboardthatisconnectedtoPin2.Don’tconnecttheotherendofthejumperwiretoanything.Thisisnowyourantennaforyourcapacitivesensor.
Figure6-11Capacitivesensingcircuit
WritingtheCodeWhenyouareusingalibrary,thefirststepistotelltheArduinoIDEinyourcodewhatlibraryyouwanttouse.Youdothisbyusing#includeandthenthenameofthefilethatdescribesthelibrary,likethis:#include<CapacitiveSensor.h>
Thefileextensionis.h.The<and>meanthatthelibraryislocatedwheretheArduinoIDEwouldexpectittobe:thelibrariesfolderinthesketchbook.
ThelibraryusesanobjectcalledCapacitiveSensor.Thisobjecthandlesallthenitty-grittydetailsofinteractingwiththesensor.YouneedtocreateanewvariablethatisthetypeCapacitiveSensor.Itonlytakestwoarguments:thepinfromwherethesignalissentandthepinthesensorisconnectedto:CapacitiveSensorhandSensor=CapacitiveSensor(outputPin, sensorPin);
ThecapacitiveSensor()functioniscalledtoreadfromthesensor.CallthefunctiontypehandSensor.capacitiveSensor(),becausethefunctionbelongstotheCapacitiveSensorvariablehandSensor:longsensorValue=handSensor.capacitiveSensor(30);
Thereturnedvalueisstoredinalongdatatype.Alongislikeanint,butitcanholdmuchsmallerandbiggernumbers.Thereturnednumberfromthecapacitivesensormightbealargernumberthananintcanhold,soit’sbesttousethelargerdatatype.
Alongisadatatypethatcanholdwholeintegernumbersfrom–2,147,483,648to2,147,483,647.
Whenyouputallthecodetogether,itlookslikethefollowingsketch:#include<CapacitiveSensor.h>
//capSensepins
intsensorPin=2;
intoutputPin=4;
CapacitiveSensorhandSensor=CapacitiveSensor(outputPin, sensorPin);
voidsetup(){
//beginserialcommunication
Serial.begin(9600);
}
voidloop(){
//readinthevaluefromthesensor
longsensorValue=handSensor.capacitiveSensor(30);
//printthevalue
Serial.println(sensorValue);
//waitforashortwhilebeforecontinuing
delay(10);
}
UploadthesketchtoyourArduinoUnoandopentheSerialMonitorintheArduinoIDEonyourcomputer.Touchtheendofthejumperwireactingasyourantennaandwatchwhathappenstovaluesbeingprinted.
DIGGINGINTOTHECODE
Thereisn’talottothesketch—it’squiteshort,butlet’sgooveritinmoredetail.Atthetoparethevariablesforthesketch.Therearetwopinsthatthecapacitivesensorneeds:thepinconnectedtotheresistorandthepinconnectedtotheresistorandantenna:
//capSensepins
intsensorPin=2;
intoutputPin=4;
Insidethesetup(),theonlythingthathappensisthatserialcommunicationstarts:
//beginserialcommunication
Serial.begin(9600);
Theloop()isalsobrief.ItreadsinthecurrentvaluefromthecapacitivesensorandsavesitinthevariablesensorValue.ThatvariableisthenprintedtotheSerialMonitor.Adelay()isusedtopausetheloop()beforethewholeprocessrepeatsagain.
//readinthevaluefromthesensor
longsensorValue=handSensor.capacitiveSensor(30);
//printthevalue
Serial.println(sensorValue);
//waitforashortwhilebeforecontinuing
delay(10);
Whathappenswhenyoudon’ttouchtheexposedmetalpinofthejumperwireantennaandyouonlytouchtheplasticcoatingonthewire?
Tryaddingmore10MΩresistorstoincreasethesensitivityofyoursensor.Thatmeansthesensorwillbeabletodetectyourhandfromfartheraway.Addtheminseries—endtoend.Whenyoucombineresistorsinseries,thetotalresistanceisthesumoftheindividualresistors.Thisisusefulasit’spracticallyimpossibletobuyresistorswithvaluesgreaterthan10MΩ,butyoucanputmultipleresistorsinseriesandtothesensorcircuittheylooklikeonebigresistor.
BuildingaCrystalBallCapacitivetouchsensorscanappeartobequitemagical,eventhoughyouknowit’sjustelectricalengineering.Solet’sexaggeratetheexperienceandcreateacrystalballthatmysteriouslylightsupwhenyouwaveyourhandnearit,likeinFigure6-12.
Youcanmakeyourown“crystal”withpapiermachétissuepaperoveraballoon.It’sagreatwaytomakeasemi-transparentspherethatwilllightupnicelywhenyourRGBLEDisinside.
Figure6-12Atouch-sensitivecrystalball
WhatYouNeedYouwillneedthefollowingitemstomakeyourcrystalball.TheelectroniccomponentsarepicturedinFigure6-13.
AcomputerAnArduinoUnoAUSBcableAbreadboard8jumperwiresSolidcorewire3220Ωresistors410MΩresistorsAnRGBcommoncathodeLEDApaperclip9Vbattery9Vbattery-to-DCbarreljackconnector3sheetswhitetissuepaperAballoonThincardboardorthickpaperAluminiumfoilAsolderingironSolderScissorsorutilityknifePVAgluePaintbrush
Figure6-13Theelectroniccomponentsyouneedtomakethecrystalball
UnderstandingtheCircuitThecircuitforthecrystalballisacombinationoftheRGBLEDandcapacitive-sensingcircuitsyoumadeearlierinthisadventure.Itmightbeeasiertounderstandthecircuitbylookingatacircuitschematic,insteadoflookingatabreadboard,sotakealookatFigure6-14.
Figure6-14Circuitschematicforthecrystalball
PrototypingonaBreadboardIfyou’veworkedthroughtheearlieradventuresinthisbookyou’renowanexperiencedengineer,soyouknowhowimportantitistotrythingsoutonabreadboardbeforeyoustartsolderingeverythingtogether.However,Istillwanttoremindyoutodoit,justincaseyoufeellikerushingthroughthisstep.BuildthecircuitshowninFigure6-15:
1. UseajumperwiretoconnectaGNDpinontheArduinoUnotoalongrowalongthebottomofthebreadboard.Ifthebreadboardislabelledwithablackorbluelineor-,connectthepintothatrow.
2. PlacetheRGBLEDinthebreadboardsothateachlegisinitsownshortrow.UseajumperwiretoconnectthelongestlegoftheLEDtothelongrowconnectedtotheGNDpin.
3. Insertonelegofa220ΩresistorintothesamerowaseachofthecolourlegsoftheLED.Bendtheresistoroverthegapinthemiddleoftheboard,andinsertthelegofeachLEDintoitsownshortrow.
4. FindtheredlegandconnecttheresistornowconnectedtoittoPin9withajumperwire;repeattoconnecttheresistorconnectedtothegreenlegtoPin10;andrepeatasecondtimetoconnecttheresistorconnectedthebluelegtoPin11.
5. Attheotherendofthebreadboard,insertthelegsofa10MΩresistorintotwodifferentrowsinthemiddleofthebreadboard.
6. Insertthelegofasecond10MΩresistorintothesamerowasoneofthelegsofthefirstresistor.Insertthelastlegintoanemptyrow.
7. ConnectajumperwirefromPin2tooneoftheresistors(justdon’tconnectittotherowwheretheresistorsareconnectedtoeachother).Connectanotherjumperwireintothissamerow.Thisactsasyourantennaforyourprototypecircuit.
8. ConnectajumperwirefromPin4totheremainingresistorlegthatisn’tconnectedtoanythingelse.
Figure6-15Breadboardprototypecircuit
Afteryouhavebuiltyourbaseforyourcrystalballfrompaperandfoil,youusethebreadboardedcircuittodeterminehowmanyresistorsyouwouldlikeforyourcapacitivetouchsensor.Somewherebetweenoneandfourshouldberight.Youcanaddmoreresistorstoyourtworesistorsonthebreadboardendtoendthewaythetworesistorsarealreadyconnected.
WritingtheCodeThefirstfewlinesofthesketchareamash-upoftheRGBLEDsketchandcapacitivesensingsketchfromearlierinthisadventure.Inthiscode,thevariablesforthepinsandthesensoraresetup.Youwillbebuildingyourbaseinthenextsection.Itwillbecoveredinfoilandwillbetheantennaforyourcircuit,butfirstcreateanewsketchintheArduinoIDEwiththefollowingcode:#include<CapacitiveSensor.h>
//LEDpins
intredPin=9;
intgreenPin=10;
intbluePin=11;
//capSensepins
intsensorPin=2;
intoutputPin=4;
//touchthreshold
intthreshold=1000;
CapacitiveSensorhandSensor=CapacitiveSensor(outputPin,@@ta
sensorPin);
voidsetup(){
pinMode(redPin,OUTPUT);
pinMode(greenPin,OUTPUT);
pinMode(bluePin,OUTPUT);
Serial.begin(9600);
}
voidloop(){
longsensorValue=handSensor.capacitiveSensor(30);
Serial.println(sensorValue);
//ifabovethethreshold
if(sensorValue>threshold){
//calculatecolorvaluebasedonsensorreading
intredValue=map(sensorValue,threshold,90000,0,255);
intgreenValue=map(sensorValue,threshold,20000,0,255);
intblueValue=map(sensorValue,threshold,30000,0,255);
//turnonled
analogWrite(redPin,redValue);
analogWrite(greenPin,greenValue);
analogWrite(bluePin,blueValue);
}
else{
//otherwiseturnoffled
digitalWrite(redPin,LOW);
digitalWrite(greenPin,LOW);
digitalWrite(bluePin,LOW);
}
}
UploadthesketchtoyourArduinoUno,andtouchthejumperwireactingastheantenna.Youshouldseethelightturnonandchangecolours.OpentheSerialMonitorintheArduinoIDEtomonitorthevaluesbeingreadbythetouchsensor.
DIGGINGINTOTHECODE
Themainvariableyouusetoadjustyourinteractionwithyourcrystalballisthreshold.Thisvariableplaysinanimportantroleintheloop().ItdetermineshowsensitiveyourcrystalballisbykeepingtheLEDturnedoffuntilabig-enoughvalueisreadfromthesensor:
//touchthreshold
intthreshold=1000;
AdjustthisnumesensorintheSerialMonitor.Youmayhavetoadjustthisnumbermultipletimesasyourantennachangesfromaprototypejumperwiretoyourcrystalball.
Intheloop(),thresholddetermineswhenthelightsturnon:
//ifabovethethreshold
if(sensorValue>threshold){
Withinthatifstatement,therearethreelinesofcodeusinganewfunction:map().Thisfunctiontakesanumberwithinarangeofvaluesandtranslatesittoanewrangeofvalues.Thisisusefulbecausetherangeofnumbersthatcanbereadinfromthesensorcangetverylarge,butanalogWrite()can’thandleanythinglargerthan255.Themap()functionhelpsbyscalingthevaluefromthesensortoanewnumberthat’swithintheacceptablerange.Figure6-16illustrateshowthisworks.
Figure6-16MappingavaluetoanewrangeThefirstargumentofmap()isthenumbertobemapped.Thesecondandthirdargumentsarethecurrentlowestandhighestvaluesthosenumberscanbe.Thefourthandfifthnumbersarethenewlowestandhighestvaluesthemappednumberscanbe:
intredValue=map(sensorValue,threshold, 90000,0,255);
intgreenValue=map(sensorValue, threshold,20000,0,255);
intblueValue=map(sensorValue,threshold,30000,0,255);
Inthesketch,themaximumofthestartingrangeisdifferentforeachcolour.Thisistomakeeachofthecoloursrespondslightlydifferentlytothesamesensorvalue.Forexample,avalueof3000createsaredValueof6,greenValueof28andablueValueof18.Tryoutsomedifferentvaluesinthethreemap()functionstogetthecoloursyoulikebest.
MakingtheCrystalBallNowtomakethecrystalballitself.Youaregoingtousepapiermachétocreateathinspherethatwillletthroughlight.Thebaseonwhichtheballsitsisthincardboardorthickpapercoveredinaluminiumfoil.Thebaseservesasthecapacitivesensor.Theelectronicsfitnicelyinsidethebaseand,ifyouuseabatterytopowertheArduino,itwillcreateaperfectmagicalillusion.
MakingaPapierMachéBallThe“ball”ofthecrystalwillbepapiermachéthatgetsitshapefromaballoon.YouusetissuepaperinsteadofathickerpapersothatthelightfromtheRGBLEDisstillvisible.
1. Blowupaballoontothesizethatyouwantyourcrystalball.RememberthatifyouwanttheArduinoboardtofitinsidethebase,yourballoonneedstobebigenoughtorestinabasethatcanholdtheboard.
2. Waterdownaboutatablespoonor25mlofwhitePVAgluewithahalftofulltablespoonor15–25mlofwater.
3. Cutupthreesheetsofwhitetissuepaperintoapproximatelyone-inchbyone-inchsquares.
4. Useapaintbrushtoapplythegluemixturetoasmallsectionoftheballoonstartingatthetopoppositeoftheknot.
5. Placeatissuepapersquareonthegluedareaandbrushmoreglueontopofthepaper.6. Repeatsteps4and5workingtowardstheknotoftheballoon,takingcaretooverlap
thesquaresonlyatinybit,untilthetoptwo-thirdsoftheballooniscovered.7. Leavetheballoontodryforatleasthalfadayorovernight.8. Repeatwithanotherlayeroftissuepaper.Youmayneedtoapplyuptothreelayersof
tissue.Youwantthedriedpapiermachétofeelfirmenoughtosupportitsshapeafteryouhavepoppedandremovedtheballoon.
9. Whenthepapiermachéisdryandfeelsfirmenoughtoholditsshape,poptheballoon.Carefullypeelawaytheballoonfromtheinsideofthepapiermaché.Ifneeded,trimthepapertocreateaneatedgetothe“crystal”.YouwillendupwithanobjectliketheoneshowninFigure6-17.
10. Cutastripofthickerpaperorthincardboardabout2”wide.Wrapitinaluminiumfoil.
11. Curlthefoil-coveredpaperintoaringjustbigenoughtoresttheballonandwillalsofitaroundtheArduinoUno(seeFigure6-18).Securetheringwithastapleortape.
12. Attachtheballtotheringwithtapeorglue.
Figure6-17Papiermachécrystalball
Figure6-18Aluminiumfoil–coveredbase
SolderingtheElectronics
Therearen’tmanypartstothiscircuit,butbesuretoprototypeitonabreadboardfirstoryouwon’tknowhowmanyresistorstouseforyoursensor.
Solderingcanbedangerousastheirongetsveryhot.Onlysolderwhenanadultisnearbytohelp.
Soldera220ΩresistorontoeachoftheshorterthreelegsoftheRGBLED.Cutapieceofsolid-corewirethesamelengthasaresistorandsolderittothecathodeoftheRGBLED(seeFigure6-19).
Figure6-19SolderedLEDcircuit
Soldertogetherthenumberof10M-ohmresistorsyouneedforyourcircuit.
Cutapieceofsolid-corewireabout3”long.Solderoneendtoapaperclipandtheotherendtothelast10M-ohmresistorinyourchainofresistors(seeFigure6-20).
Figure6-20Solderedsensorcircuit
ConnectingtheElectronicsInserttheendoftheresistorsnotsolderedtothewireintoPin4andthewireconnectedtothepaperclipintoPin2.Inserttheresistorsconnectedtothered,greenandbluepartsoftheRGBLEDintoPins9,10and11(seeFigure6-21).Attachthepaperclipontothealuminiumfoilbaseofthecrystalball.
Figure6-21Completedcrystalballcircuit
PowertheArduinoboardusinga9VbatteryandDCbarreljackconnector.Tryoutyourcrystalballbywavingyourhandsoverit!Thecrystalballshouldonlylightupwhenyourhandisnearandchangecolourswhenyourhandgetsclosertothealuminiumbase.Remember,youmayneedtoadjustthethresholdvalueuntilyougettheinteractionthatyouwant.
FurtherAdventureswithLibrariesYouhavelearnedhowtostrikeoutonyourownandstartusingotherlibrarieswithyourArduino.Awholeworldofpossibilitieshasopenedup!ExploretheArduinoPlayground(http://playground.arduino.cc/)toseewhatotherlibrariesareavailable.
Ifyou’dliketoreadmoreonhowtousecapacitivesensing,visittheArduinoPlaygrounddocumentationathttp://playground.arduino.cc/Main/CapacitiveSensor.
ArduinoCommandQuickReferenceTable
Command Description
analogWrite()Outputsavoltagebetween0and5Vonaspecifiedpin.Avalueof0outputs0Vand255outputs5V.Seealsohttp://arduino.cc/en/Reference/AnalogWrite.
CapacitiveSensorLibraryforcreatingcapacitivesensors.Seealsohttp://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense.
longAlongisadatatypethatcanholdwholeintegernumbersfrom–2,147,483,648to2,147,483,647.Seealsohttp://arduino.cc/en/Reference/Long.
map()Takesavaluewithinaninitialrangeandmapsittoanewrange.Seealsohttp://arduino.cc/en/Reference/Map.
AchievementUnlocked:Youhaveexpandedyourknowledgewithlibraries!
IntheNextAdventureInthenextadventure,youstartexploringothertypesofArduinoboardstocreateacustomcomputergamecontroller!
WHENYOUSELECTyourArduinoUnoboardfromTools⇒BoardintheArduinoIDE,youmightnoticethatthatitisjustoneiteminaverylonglistofboardnames.Alltheotherssoundjustasexciting.So,whatmakesthemdifferentfromyourUno?There’snotroominthisbooktodescribeallofthembutinthisadventureyouwillgettoknowoneofthem—theArduinoLeonardo.TheLeonardohasaspecialskillthattheUnodoesn’thave:itcanmakeacomputerbelievethattheArduinoboardisaUSBkeyboardormouse.
Forthisadventure,youalsouseasensorthatdetectswhetherit’sinbrightlightorshadow.YouusethistocreateaUSBgamecontroller.Thesensormeansyouwillbeabletowaveyourhandsintheairabovethecontrollertoplaycomputergames!
WhatYouNeedYouneedthefollowingitemsforthefirstpartoftheadventure(seeFigure7-1):
Figure7-1Theelectroniccomponentsyouneedforthefirstpartofthisadventure
AcomputerAnArduinoLeonardoAUSBMicrocableAbreadboard4jumperwiresAlight-dependentresistorA10kΩresistor
IntroducingtheArduinoLeonardoOneofthemanygreatthingsabouttheArduinoplatformisthatyoucanchooseadifferentboardforyourprojectwithouthavingtochangethecode.YoucanusealmostallthecodeyouhavelearnedtowritefortheArduinoUnowiththeArduinoLeonardoaswell.YouevenusethesameArduinointegrateddevelopmentenvironment(IDE)touploadthecode.
ThemainthingyouhavetododifferentlyisthatwhenyouselectwhichboardyouareusingfromTools⇒BoardintheIDE,youneedtoselectArduinoLeonardo,asshowninFigure7-2.
Figure7-2SelectingtheArduinoLeonardofromTools⇒BoardintheArduinoIDE
ConnectingYourLeonardofortheFirstTimeThefirstthingyoumightnoticewhenconnectingyourArduinoLeonardotoyourcomputerforthefirsttimeisthatitdoesn’thavethesamekindofUSBconnectorasyourArduinoUno.Youcan’tusethesameUSBcableforbothboards.
TheconnectorsonUSBcablescomeindifferentsizesandshapes,asshowninFigure7-3.Whatyoumightthinkofasa“normal”USBcablehasaTypeAconnectoratoneend,whichgoesintoyourcomputer,andaTypeBconnectorattheotherend,whichgoesintoyourArduinoUno.TheArduinoLeonardousesaUSBMicroconnectorinsteadofaTypeBconnector.Thisdoesn’tdoanythingdifferentfromanormalUSBcable;itstillletstheLeonardogetpowerfromacomputerandcanbeusedtotalkwiththecomputer.Theonlydifferenceisthattheconnectorhasadifferentshape.ThatmeansyouhavetokeeptrackoftwodifferentkindsofUSBcable!
Figure7-3USBconnectors
OneofthefeaturestheLeonardohasthattheUnodoesn’tisthat,tothecomputer,theboardcanseemlikeaUSBkeyboard.Becauseofthis,whenyouconnectyourLeonardo,yourcomputermightpopopenawindowthatsaysthecomputerhasdetectedanewkeyboard.Justclosethewindow.Youdon’tneedtoclickContinueorsetupanewdevice;youprogramyourArduinoLeonardousingtheArduinoIDEjustlikeyouhavebeendoingwithyourArduinoUno.
IfthecomputeryouareusingtoprogramyourArduinoLeonardorunsonWindows7,youmayneedtoinstallsomeadditionaldrivers.ConnectyourLeonardoandwaitfortheautomaticdriverinstallationprocess.Ifnothinghappensafterafewminutes,gotohttp://arduino.cc/en/Guide/ArduinoLeonardoMicro?from=Guide.ArduinoLeonardoforinstructionsabouthowtoinstallthedriversyourself.
DIGGINGINTOTHECODE
Mostofthetime,thecodethatyouwriteforyourUnoworksthesamewayontheLeonardo,butit’sgoodtoknowwhatmightbealittledifferent.
WithyourArduinoUno,everytimeyouopentheSerialMonitorintheArduinoIDE,theUnoresets.Thesetup()functionthenrunsoncebeforegoingintoloop().Thesameisn’ttrueforyourLeonardo.TheLeonardodoesn’tresetwhentheSerialMonitorisopened.ThatmeansthatifyouwanttoprintsomethingtotheSerialMonitorfromthesetup()function,itdoesn’tappear;bythetimetheSerialMonitoropens,theprintstatementfromthesetup()functionwouldalreadyhavepassedandyou’donlyseemessagesfromtheloop.
IntheArduinoIDE,createanewsketchwiththefollowingcode.UploadittoyourLeonardoandthenopentheSerialMonitor:
voidsetup(){
Serial.begin(9600);
Serial.println("Hellofromthesetup!");
}
voidloop(){
Serial.println("Andhellofromtheloop!");
delay(1000);
}
Youonlyseethemessage“Andhellofromtheloop!”printedoverandoveragain.
NowtrypressingtheresetbuttonontheLeonardoboard(it’snexttotheUSBMicroconnector).ThemessagesstopprintingtotheSerialMonitorcompletely!ThisisbecausetheconnectionbetweentheSerialMonitorandtheLeonardowasbrokenwhenyoupressedreset.YouneedtocloseandreopenSerialMonitortolettheArduinoLeonardoknowthattheSerialMonitoristhereandwaiting.
Sowhatdoesthatallmean?Doesthatmeanyoucan’teverprintmessagesfromthesetup()functionofanArduinoLeonardotoreadintheSerialMonitor?Thatwouldbefrustrating!Itcanbereallyusefultoprintmessages,asithelpsyoutoknowwhatisgoingoninsidetheboardandfixanyproblemswithyourcode.Well,thegoodthingisthereisawayaroundthis.
YoucantelltheLeonardotowaitandnotdoanythinguntilaserialconnectiontosomethinglikeSerialMonitorisopened.
TryuploadingthefollowingcodetoyourLeonardo,andthenopentheSerialMonitor:
voidsetup(){
Serial.begin(9600);
while(!Serial);//sitandwaitforaserialconnection
Serial.println("Hellofromthesetup!");
}
voidloop(){
Serial.println("Andhellofromtheloop!");
delay(1000);
}
Youshouldnowseethe“Hellofromthesetup!”messagebeforethe“Andhellofromtheloop!”messages.Ifyoutrypressingresetontheboard,youseethatyoustillneedtocloseandreopentheSerialMonitortoseetheprintingmessagesagain.
ActingLikeaKeyboardYoucansendmessagestothecomputerfromyourArduinoUnousingfunctionslikeSerial.println(),butyouneedaspecialprogramliketheSerialMonitorintheArduinoIDEtobeabletoreadthosemessages.TheArduinoLeonardocansendmessagesthatdon’tneedaspecialprogramforthecomputertounderstand.Itcansendmessagesthatlooklikekeysbeingpressedonakeyboard.Anyprogramthatrespondstokeypresses(likeawordprocessingprogramoracomputergame)canunderstandthosemessages.
StartbycreatinganewsketchintheArduinoIDE.Writeoutthefollowingcodetocreateanemptysetup()andloop():voidsetup(){
}
voidloop(){
}
BeforeyoustartturningyourArduinoLeonardointoakeyboard,it’sveryimportantthatyougiveitanoffswitch.YourLeonardooverridesyourcomputer’skeyboardthesamewayaspluggingaUSBkeyboardintoyourcomputerdoes.IfyourLeonardoisconstantlytypingmessagesatyourcomputer,itcanbedifficulttotellyourcomputertodoanythingelse—includinguploadinganewsketchtoyourLeonardo.
Topreventthisfromhappening,intheloop()youaregoingtofirstchecktoseeifaninputpinissetto0.Ifitis,thendon’tprintanykeyboardmessages.Youdon’tevenneedtowireupaswitchlikeyoudidinAdventure3;youcanjustuseajumperwire!Here’show.
First,atthetopofyoursketch,beforethesetup(),createanewvariabletostoreyourswitchpinnumber:intswitchPin=4;
Insidethe{and}ofsetup(),setthatpintobeaninputwiththepull-upresistorturnedon:pinMode(switchPin,INPUT_PULLUP);
Theninloop(),addthefollowingcodetocheckifswitchPinhasbeenconnectedtoground.Ifithas,continueontoprintthemessage;otherwisedonothing://readthepushbutton:
intswitchState=digitalRead(switchPin);
//iftheswitchisopen(notconnectedtoground),
if(switchState==LOW){
//addkeyboardcodehere
}
delay(500);
Thepurposeofdelay()attheendistoslowdownhowoftenthelooprepeats.Thatway,
whenmessagesarebeingsent,theyaren’tsenttoofast.
NowifyouconnectawirebetweenswitchPin(Pin4)andGND,thecodethatyouputinsidetheifstatementisrun.Ifyoudon’tconnectanythingtotheswitchPin,thepull-upresistorcausesthevaluereadfromswitchPintobe1andthecodeinsidetheifstatementisskipped.
Timetostartaddingsomekeyboardmessages!
TheKeyboardfunctionslookalotliketheSerialfunctions.Inthesetup()functionyouneedtostarttheLeonardo’skeyboardmessagingbycalling:Keyboard.begin();
YoucanthenwritemessagesusingKeyboard:Keyboard.println("ThisisyourLeonardoactinglikeakeyboard.");
Whenthecodeisallputtogether,yougetthefollowingsketch:intswitchPin=4;//inputpinforswitch
voidsetup(){
//maketheswitchPinandinput
//withaninternalpull-upresistor
pinMode(switchPin,INPUT_PULLUP);
//initializecontroloverthekeyboard:
Keyboard.begin();
}
voidloop(){
//readthepushbutton:
intswitchState=digitalRead(switchPin);
//iftheswitchisopen(notconnectedtoground),
if(switchState==LOW){
Keyboard.println("ThisisyourLeonardoactinglikeakeyboard.");
}
delay(500);
}
UploadthecodetoyourLeonardoandthenopenanywordprocessingprogram.UsethejumperwiretoconnectyourswitchPintoGND.YoushouldseeyourLeonardotypingoutmessageslikethoseinFigure7-4!
Figure7-4TheLeonardotypinginawordprocessingprogram
Don’tcreatearunawaykeyboard!IfyoufindyouarehavingproblemsuploadinganewsketchtoyourLeonardo,thereissomethingyoucantry.YoucanmanuallyresettheArduinoLeonardoandtellittolistenforasketchtobeuploaded.HolddownthebuttonontheLeonardoandthenclickontheUploadbuttonintheArduinoIDE.WaituntiltheIDEsays“Uploading…”andthenreleasethebutton.Yoursketchshouldthenfinishuploadingontoyourboard.
DidyouknowyoucancomeupwithanewideausinganArduino,thenmakeandsellyourideaasaproductinastore?TheMaKeyMaKeyisoneexampleofanArduinoprojectyoucanbuyinastore.TheMaKeyMaKeyisbasedontheLeonardoArduino—itsnamecomesfrom“Makeanythingintoakeyboard”.Younowknowalotaboutthecodebehindhowitworks.Ifyou’dliketolearnmoreabouttheMaKeyMaKey,gotohttp://makeymakey.com,whereyoucandownloadtheArduinocodeusedtoprogramtheMaKeyMaKeyandreadhowitworks.YoucaneventurnyourArduinoLeonardointoaMaKeyMaKey!
ThisisallbecausetheArduinoisopensourcehardwareandtheArduinoisopensourcesoftware.Youcanreadmoreaboutwhatthatmeansonlineathttp://en.wikipedia.org/wiki/Open-source_softwareandhttp://en.wikipedia.org/wiki/Open-source_hardware.
SensingLightInAdventure2youwereintroducedtoanalogueinputs,usingthepotentiometertocontrolastatusmessagesign.Here’salittlerefresherabouthowanalogueinputswork.
AnanalogueinputonanArduinoboardisaninputthatcanreadinvoltagesbetweengroundand5V.Adigitalinputcanreadineithergroundor5V,anditcan’ttellifaninputisonly2.3Voranyothervaluebetweengroundand5V(seeFigure7-5).
Figure7-5Analogueanddigitalsignals
Therearealotofdifferentsensorsthatoutputanaloguesignalsandnotdigitalsignals—thatistheydon’tdetectonlywhethersomethingisonoroff;theyalsomeasurehowmuchthereisofsomething.Microphonesmeasuresound,accelerometersmeasuremovementandlightsensorsmeasurelight.Allofthesesensorsoutputananaloguesignal,whichwouldbereadintoanArduinoboardasananalogueinput.Thetypeoflightsensoryouworkwithinthisadventureisalight-dependentresistor(LDR).AnLDRisaresistorthatchangesitsresistanceaccordingtohowmuchlightitisexposedto.SometimesLDRsarealsocalledphotoresistors.IlikethenameLDRbecauseisdescribesexactlyhowtheresistorworks—itdependsonthelight.
Alight-dependentresistor(LDR)changesitsresistanceaccordingtohowmuchlightitisexposedto.Itisalsosometimescalledaphotoresistor.
UseamultimetertomeasuretheresistanceofyourLDR.ConnectoneprobetoonelegoftheLDRandtheotherprobetotheotherleg.Setthemultimetertomeasureresistanceandseewhatvalueyouget.Try
shiningalightontheLDRtoseewhathappens.WhathappenswhenyoucovertheLDRandblockoutlight?
BuildingtheCircuitAnArduinoboardcanonlymeasurevoltage,butanLDRonlychangesitsresistance,whichmakesforabitofapuzzle.HowcanyougettheArduinotoseehowtheLDRisrespondingtobrighterordarkerenvironmentsiftheLDRonlychangesresistanceandnotvoltage?Thetrickistousesomeclevercircuitdesign.
Voltage,currentandresistanceareallconnected.Youcan’tchangeoneofthosethingsinacircuitwithoutchangingtheothers.ThewaytheyareallrelatedisdefinedbyOhm’sLaw,whichisshowninFigure7-6.
Figure7-6Ohm’sLawdefineshowvoltage,currentandresistancearerelated.
Ohm’sLawisthemathematicalrelationshipbetweenvoltage,currentandresistance.Voltageequalscurrentmultipliedbytheresistance—or,putanotherway,V=IR.
Youdon’thavetoworrytoomuchaboutthedetailsofthatequationrightnow.Theimportantthingtoknowisthatyoucandesignacircuitthatchangesthevoltagewhenyouchangetheresistance.Thetypeofcircuityouaregoingtobuildtodothisiscalledavoltagedivider.
Avoltagedividerisacircuitthatoutputsafractionoftheinputvoltage.Itisausefulcircuitfortranslatingachangeinresistanceintoachangeinvoltage.
Thevoltagedivideryouaregoingtomakehastwodifferentresistors.Oneoftheresistorsisa“normal”fixed-valueresistor;theotherisavariableresistorthatchangesitsvalue.YouaregoingtouseanLDRasthevariableresistorhere,butinafutureprojectyoucouldbuildthiscircuitwithanothersensorthatisavariableresistor.
WhentheresistanceoftheLDRgoesupordown,theoutputvoltagegoesupordown.SowhenmoreorlesslightisshownontheLDRinthevoltagedividercircuit,theoutputvoltagegoesupanddown.WhetheryouputtheLDRinthetoporbottompositionaffectswhetherthevoltagegoesupordownwhenyoublockoutlightfromtheLDR.Figure7-7showstwowaysthatanLDRcanbebuiltintoavoltagedividercircuit.
Figure7-7Twovoltagedividercircuits,onewithanLDRasthetopresistanceandtheotherwithanLDRasthebottomresistance
Somepeoplefinditeasiertounderstandhowsomethingworkswhenitisdescribedwithamathematicalequation.Ifyouwouldliketoworkouthowthevoltageoutputfromthecircuitchangeswhenyouchangetheresistorvalues,youcanusetheequationshowninFigure7-8.Ifyoudon’tenjoyworkingwithnumbersandequations,thenyoucanjustignorethatfornowandinsteadhaveagoatbuildingthecircuitsoyoucanactuallyseewhatishappening.
Figure7-8Theequationtocalculatehowdifferentresistorvaluesinavoltagedividerchangetheoutputvoltage
WritingtheCodeOneofthegreatthingsaboutworkingwithArduinoboardsisthattheboarddoesn’tcarewhatsensorisconnectedtoitsinputpins.Itonlycaresifitisoutputtingananalogueordigitalsignal.Ifyou’veworkedthroughAdventure2,youalreadyhaveseenalltheArduinocodetoreadinthevaluesfromyourLDR—it’sthesamecodeyouwouldusetoreadfromapotentiometer.OpentheexamplecodeatFile⇒Examples⇒01.Basics⇒AnalogReadintheArduinoIDEtoseeanexamplesketchthatreadsinthevaluefromanalogueinputA0andthenprintsthatvaluetotheSerialMonitor.
IntheAnalogReadsketch,thesetup()functionstartstheserialcommunication://thesetuproutinerunsoncewhenyoupressreset:
voidsetup(){
//initializeserialcommunicationat9600bitspersecond:
Serial.begin(9600);
}
Theloop()functionreadsinthevalueonAnalogPinA0andsavesitinavariablecalledsensorValue.ThatvariableisthenprintedtotheSerialMonitor://thelooproutinerunsoverandoveragainforever:
voidloop(){
//readtheinputonanalogpin0:
intsensorValue=analogRead(A0);
//printoutthevalueyouread:
Serial.println(sensorValue);
delay(1);//delayinbetweenreadsforstability
}
CHALLENGE
BuildthevoltagedividercircuitwiththeLDRinthetoppositionanduploadtheAnalogReadSerialsketchtoyourArduinoboard.OpenSerialMonitorandobservewhathappenswhenyoushineorblocklightfromthesensor.
SwaptheLDRandfixedvalueresistorsotheLDRisnowinthebottomposition.WatchwhatvaluesareprintedintheSerialMonitor.Whenmightyouwanttousethefirstcircuit,andwhenmightyouprefertousethesecondone?
BuildingaGameControllerYounowknowhowtogetanArduinoLeonardotoactlikeaUSBkeyboard.Doyoualsoliketoplaycomputergames?Ifyoudo,youprobablycanthinkofsomegamesyoucanplayusingonlythekeyboardasinput.Ifyoudon’tplayalotofcomputergames,that’sokay;Icanpointoutsomethatyoucantry!
IfyoucangetyourLeonardotoactlikeakeyboardthatcontrolsacomputergame,thenyoucanstartdesigningyourowngamecontrollerliketheoneinFigure7-9.Thatopensupawideworldofdifferentsensorsthatyoucanusetoplayagame.Boringbuttonsareathingofthepast!You’regoingtobuildacontrollerthatuseslighttocontrolkeypresses,butyoucoulduseanysensoryoulike!
Figure7-9ArduinoLeonardogamecontroller
Youwatchavideoonhowtobuildyourcontrolleronthecompanionsite(www.wiley.com/go/adventuresinarduino).
WhatYouNeedYouneedthefollowingsuppliestomakeagamecontroller(Figure7-10showstheelectroniccomponentsyouneed):
Figure7-10Theelectroniccomponentsyouneedtomakethegamecontroller
AcomputerAnArduinoLeonardoAUSBMicrocableAbreadboard10jumperwires410kΩresistors4light-dependentresistorsApieceofpaperorcardtocoverthebreadboardSomemarkersorcolouredpencilsApairofscissorsorautilityknife
BuildingtheCircuitThecircuitforthegamecontrollerdoesn’tneedtohaveanyextensionwiressolderedtoit,soyoucanbuilditdirectlyonyourbreadboard.
Thegamecontrollercircuitconsistsofthesamecircuitrepeatedfourtimes.TherearefourLDRs;eachonecontrolsadifferentarrowkey.EachLDRisinitsownvoltagedividercircuitwithafixedvalueresistor.Figure7-11showsthecircuitschematicforthegamecontroller.
Figure7-11Circuitschematicforthegamecontroller
UsethefollowingstepstobuildthecircuitinFigure7-12onyourbreadboard.It’sgoodtospaceouttheLDRssotheyaren’ttooclosetoeachother.Youdon’twanttoaccidentallyblockthelightfromaLDRwhenyouaretryingtoblocktheLDRnexttoit:
Figure7-12Thegamecontrollercircuit
1. PositionthefourLDRsbyspanningthegapinthemiddleofthebreadboard.2. Connecteachoftheresistorsbetweenoneofthelongrowsalongthetopofthe
breadboardandtheLDRs.3. ConnectajumperfromthebottomlegofeachoftheLDRstoalongrowonthe
bottomofthebreadboard.4. Connectthelongrowalongthetop,connectingtheresistorstothe5Vpinonthe
ArduinoLeonardo.5. Useajumperwiretoconnectthelongrowalongthebottomofthebreadboardwith
theotherjumperwirestoaGNDpinontheArduinoLeonardo.6. Usingfourjumperwires,connectpinsA0,A1,A2andA3toeachoftheLDRs.One
endofthejumperwireplugsintothepinontheArduinoLeonardoandtheotherendplugsintothesamerowastheresistorlegandLDRleg.
WritingtheCodeInordertomakesureyourcircuitisworkingproperly,youfirstprogramtheLeonardotoprintmessagestotheSerialMonitorbeforeprogrammingittoactlikeakeyboard.Afteryouknoweverythingisokaywiththecircuitandyou’vefiguredoutthethresholdsforwhenthesensorshouldtriggeramessage,youreplacetheserialmessageswithkeyboardmessages.
StartbycreatinganewArduinosketchandcreatinganemptysetup()andloop():
voidsetup(){
}
voidloop(){
}
Atthetopofthesketchbeforesetup(),declareandinitialisethevariablesfortheinputpins.Therearefiveinputs:theswitchpinandoneinputforeachofthefourLDRs:intswitchPin=4;
intleftSensor=A0;
intrightSensor=A1;
intupSensor=A2;
intdownSensor=A3;
Insidesetup()startserialcommunicationandsetthepinmodefortheswitchPin://maketheswitchPinaninputwithaninternalpull-upresistor
pinMode(switchPin,INPUT_PULLUP);
//initializecontroloverthekeyboard:
Serial.begin(9600);
Insidetheloop(),checkthestateofswitchPinandcreateanifstatementthatistrueifswitchPinisLOW://readthepushbutton:
intswitchState=digitalRead(switchPin);
//iftheswitchisopen(notconnectedtoground),
if(switchState==LOW){
}
delay(50);
Thedelay()makessuremessagescan’tbesenttooquickly.
Atthetopofyourcodewithyourothervariables,addthefollowinglinesofcode:intrightThreshold=400;
intleftThreshold=400;
intupThreshold=400;
intdownThreshold=400;
ThesevariableskeeptrackofwheneachLDRcircuitwilltriggeramessage.
Youprobablyneedtouseavalueotherthan400foryourLDRs.Youmayneedtomakethevalueshigherorlower,andeachLDRmightevenrequireadifferentvalue!Lateryouwillfigureoutthebestvaluesforyourcontrollerbytryingoutdifferentvalues,butyouaren’treadytodothatyet!Youneedtofinishthesketchfirst.
Insideyourifstatement,addthefollowingcode.Eventhoughit’slong,it’sjustthesamethingrepeatedfourtimes—onceforeachLDR://RIGHTARROW
intrightValue=analogRead(rightSensor);
//Serial.println(rightValue);
if(rightValue>rightThreshold){
Serial.println("rightarrow");
}
//LEFTARROW
intleftValue=analogRead(leftSensor);
//Serial.println(leftValue);
if(leftValue>leftThreshold){
Serial.println("leftarrow");
}
//UPARROW
intupValue=analogRead(upSensor);
//Serial.println(upValue);
if(upValue>upThreshold){
Serial.println("uparrow");
}
//DOWNARROW
intdownValue=analogRead(downSensor);
//Serial.println(downValue);
if(downValue>downThreshold){
Serial.println("downarrow");
}
Ineachofthefourblocksofcode,thevaluefromtheanalogpinisreadinandsavedtoavariable.IfthatvariableislessthanthethresholdvaluefortheLDR,thenthemessageisprinted.
Insideeachblockofcodeisalineofcodecommentedout.Ifyouuncommentthatline(bydeleting//)thenthevalueofthatpinisprinted.Thiscanbeusefultohelpsetyourthresholdvalues,butitalsoprintsalotofnumbersandcanbeconfusing.Youprobablywanttouncommentonlyoneofthematatime.
Whatfollowshereisthefullcodefortryingoutprintingserialmessages.BuildyourcircuitanduploadthecodetoyourArduinoLeonardo.
Rememberthatyoursketchwon’tcheckthevaluesofthepinsunlessyouhaveconnectedPin4toGND!
intswitchPin=4;
intleftSensor=A0;
intrightSensor=A1;
intupSensor=A2;
intdownSensor=A3;
//adjustthesevariablestovaluesthat
//workforyourcontroller
intrightThreshold=400;
intleftThreshold=400;
intupThreshold=400;
intdownThreshold=400;
voidsetup(){
//maketheswitchPinaninput//withaninternalpull-upresistor
pinMode(switchPin,INPUT_PULLUP);
//initializecontroloverthekeyboard:
Serial.begin(9600);
}
voidloop(){
//readthepushbutton:
intswitchState=digitalRead(switchPin);
//iftheswitchisopen(notconnectedtoground),
if(switchState==LOW){
//RIGHTARROW
intrightValue=analogRead(rightSensor);
//Serial.println(rightValue);
if(rightValue>rightThreshold){
Serial.println("rightarrow");
}
//LEFTARROW
intleftValue=analogRead(leftSensor);
//Serial.println(leftValue);
if(leftValue>leftThreshold){
Serial.println("leftarrow");
}
//UPARROW
intupValue=analogRead(upSensor);
//Serial.println(upValue);
if(upValue>upThreshold){
Serial.println("uparrow");
}
//DOWNARROW
intdownValue=analogRead(downSensor);
//Serial.println(downValue);
if(downValue>downThreshold){
Serial.println("downarrow");
}
}
delay(50);
}
Asthesketchesgetlonger,youmayprefertodownloadthemfromthecompanionsite(www.wiley.com/go/adventuresinarduino)insteadoftypingthemout.
NowopentheSerialMonitorandtryoutyourLDRsonebyone,byholdingyourhandovereachone.Adjustthethresholdvaluesuntiltheyprintamessageonlywhenyouwantthemto.
Afteryouknowwhatyourthresholdsshouldbe,youcanchangeyoursketchtooutputkeypressesinsteadofserialmessages.
Saveyoursketchandthencreateanewemptysketch.Copyandpastethesketchthatyoujustsavedintothenewsketch.YouaregoingtokeepmostofwhatyouhavealreadywrittenandreplacethelinesofcodethatuseSerialfunctionswithKeyboardfunctions.
Inthesetup(),replacethelinethatstartsserialcommunicationwiththefollowing://initializecontroloverthekeyboard:
Keyboard.begin();
Ineachofthefourblocksofcodethatprinttheserialmessageaboutwhichsensorwastriggered,replacetheSerial.println()withthefollowingline,usingKEY_RIGHT_ARROW,KEY_LEFT_ARROW,KEY_UP_ARROWandKEY_DOWN_ARROW:Keyboard.press(KEY_RIGHT_ARROW);
Insteadofprintingamessage,theLeonardoissendingamessagethatakeyhasbeenpressed.Attheendoftheloop,thefollowinglineofcodesendsthemessagethatallthekeyshavebeenreleased:Keyboard.releaseAll()
Whenyouputitalltogether,youhavethefollowingsketch:intswitchPin=4;
intleftSensor=A0;
intrightSensor=A1;
intupSensor=A2;
intdownSensor=A3;
//adjustthesevariablestovaluesthat
//workforyourcontroller
intrightThreshold=400;
intleftThreshold=400;
intupThreshold=400;
intdownThreshold=400;
voidsetup(){
//maketheswitchPinandinput//withaninternalpull-upresistor
pinMode(switchPin,INPUT_PULLUP);
//initializecontroloverthekeyboard:
Keyboard.begin();
}
voidloop(){
//readthepushbutton:
intswitchState=digitalRead(switchPin);
//iftheswitchisopen(notconnectedtoground),
if(switchState==LOW){
//RIGHTARROW
intrightValue=analogRead(rightSensor);
//Serial.println(rightValue);
if(rightValue>rightThreshold){
Keyboard.press(KEY_RIGHT_ARROW);
}
//LEFTARROW
intleftValue=analogRead(leftSensor);
//Serial.println(leftValue);
if(leftValue>leftThreshold){
Keyboard.press(KEY_LEFT_ARROW);
}
//UPARROW
intupValue=analogRead(upSensor);
//Serial.println(upValue);
if(upValue>upThreshold){
Keyboard.press(KEY_UP_ARROW);
}
//DOWNARROW
intdownValue=analogRead(downSensor);
//Serial.println(downValue);
if(downValue>downThreshold){
Keyboard.press(KEY_DOWN_ARROW);
}
}
delay(50);
Keyboard.releaseAll();
}
Buildthecircuitanduploadthesketch.Openaspreadsheetprogram,suchasMicrosoftExcel,andtestthatyoucanuseyourcontrollertomovetodifferentsquaresjustasyoucouldwiththearrowkeys.
Doesyourgameusekeysotherthanthearrows?Ormaybeitneedsthearrowkeysandthespacebar?YoucanreadmoreaboutallthekeystheArduinoLeonardocanpressontheArduinowebsiteathttp://arduino.cc/en/Reference/KeyboardModifiers.
MakingtheControllerCoverUsingpaperorcard,cutoutashapeforyourgamecontroller.Itcanbearectangleoranyothershape.Itdoesn’thavetolooklikeanygamecontrolleryou’veeverseenbefore!Itjustneedstobebigenoughtocoveryourbreadboard.
Decorateyourcoverhoweveryou’dlike.ItwouldbeagoodideatolabelwhichkeyistriggeredbywhichLDR.Whenyou’reatatrickypartinyourgame,youdon’twanttoforgetwhichsensoriswhichkeyandaccidentallyloseyourgame!
Usingscissors,pokeaholewhereeachLDRwillbeplaced(seeFigure7-13).ThisiswherethewirelegsoftheLDRwillpassthroughthecoversothatthetoppartofthesensorisabovethecover,butthelegsareconnectedtothecircuitunderneathonthebreadboard.
Figure7-13Coverwithoutanycircuitry
PuttingItAllTogetherSinceyou’vealreadytestedyourcontrollerwithaspreadsheetprogram,thelaststepistoaddyourcontrollercoverbeforeplayingyourgameswithyournewcontroller.
Onebyone,removeanLDRfromthebreadboardandpokeitslegsthroughtheholesinthepapercover.ThenconnectthatLDRbackintothecircuitonthebreadboard.YoucanalwayssolderlongerwiresontotheLDRsifyoufindittootrickytoconnecttheLDRsbackintocircuitonthebreadboard.
Testyourcontrolleragainwiththespreadsheetprogramjusttomakesureyou’veconnectedeverythingcorrectly.Afteryou’veconfirmedthatit’sallokay,loadupyourfavoritegamethatusesthearrowkeysandstartplaying!
Ifyouarelookingforsomegamestoplaywithyournewcontroller,2048athttp://gabrielecirulli.github.io/2048isagoodonetotry.It’sanumberpuzzlegame.Ialsolikethemazegameatwww.primarygames.com/puzzles/mazes/mazerace.It’smuchharderthanitlooks!
FurtherAdventureswiththeLeonardoYouhavenowstartedworkingwithmoreadvancedcircuitscalledvoltagedividers.Ifyouwouldliketolearnevenmoreaboutvoltagedividers,youcanstartbycheckingoutSparkfun’stutorialathttps://learn.sparkfun.com/tutorials/voltage-dividers.
FormoreinformationabouttheArduinoLeonardoandwhatyoucandowithit,visittheArduinoLeonardopageontheArduinowebsiteathttp://arduino.cc/en/Guide/ArduinoLeonardoMicro?from=Guide.ArduinoLeonardo.
YoucanalsoexploremoreexamplesusingtheKeyboardfunctionsintheArduinoIDEbygoingtoFile⇒Examples⇒09.USB.Here,youwillalsofindexamplesthatturnyourArduinoLeonardointoamouse.
BoardsliketheArduinoLeonardoandUnoareopensourcehardware.ThatmeansthatyoucanmakenewprojectsandevennewboardsthatusethefeaturesofArduinos,justliketheMaKeyMaKey.Ifyouwouldliketolearnmoreaboutopensourcehardware,checkouttheOpenSourceHardwareAssociation(OSHWA)atwww.oshwa.org/.
ArduinoCommandQuickReferenceTable
Command Description
While(!Serial); CausestheLeonardotowaitanddonothinguntilaserialconnectionisopened.
Keyboard.begin() Beginskeyboardfunctionality.Seealsohttp://arduino.cc/en/Reference/KeyboardBegin.
Keyboard.println()Sendsamessagetothecomputerasifitwastypedonthekeyboard.Seealsohttp://arduino.cc/en/Reference/KeyboardPrintln.
Keyboard.press()Sendsamessagetothecomputerthatakeyispressed.Seealsohttp://arduino.cc/en/Reference/KeyboardPress.
Keyboard.releaseAll()Sendsamessagetothecomputerthatallkeyshavebeenreleased.Seealsohttp://arduino.cc/en/Reference/KeyboardReleaseAll.
AchievementUnlocked:Expertconstructorofagamecontroller.Wellplayed!
IntheNextAdventureInthenextadventure,youcontinueyourexplorationofothertypesofArduinoboardstocreateanamazingwearablecircuit!
YOUHAVEONLYjustbeguntoexploreallthedifferentwaystomakeaprojectwithanArduino!InAdventure7youlearnedhowtodesignandbuildyourowngamecontrollerusingtheArduinoLeonardo.TheArduinoboardstilllookedexactlylikeanArduinoUno,however,andyoustillbuiltcircuitsthesamewayyouwouldbuildyourcircuitforanArduinoUnoproject—usingbreadboards,wireandsolder.
Butwhatif,forexample,youwantedtobuildanArduinoprojectthatyoucouldwear?Youcan’tusestiffwiresandhardsolderifyouwantsomethingtobendlikefabricandbecomfortabletowear.Luckily,conductivemetalscanbemadeintothread,whichmeansyoucansewacircuitwithaneedleand(conductive)thread.It’scalledmakingasoftcircuit.Andthere’saparticulartypeofArduinoboardthathasbeenbuilttomakeiteasytosewamicrocontrollerintoyourproject:theLilypadArduinoUSB!
Inthisadventureyou’regoingtocreateahoodiewithanArduinoandLEDsembeddedinitssleeve.TheLEDswilldisplayasecretmessagethatyouprogramintoyourLilypadArduinoUSB.ThesecretmessageisstoredontheLilypadArduinoUSBusingarrays,sobeforeyoustartwritingthecodeforthisadventure’sproject,Iremindyouhowarraysworkandshowyouhowtopushthemtoaseconddimension.
WhatYouNeedYouneedthecomponentsshowninFigure8-1forthefirstpartofthisadventure.
AcomputerALilypadArduinoUSBAUSBMicrocable10alligatorclips5LilypadLEDs(or5LEDsand568Ωor100ΩresistorsifnotusingLilypadLEDs)
Figure8-1Theelectroniccomponentsyouneedforthefirstpartofthisadventure
IntroducingtheLilypadArduinoUSBTheLilypadArduinoUSBisamemberofafamilyofLilypadArduinos.AlthoughyoucoulduseanyoftheLilypadArduinos,theLilypadArduinoUSBshowninFigure8-2hassomefeaturesthatmakeitabitnicertouse,suchasnotneedingasecondboardtouploadsketches.ButbecausetheyareallArduinos,yourcoderemainsthesame,sothecodeyouwriteherewillstillworkonaLilypadArduino,LilypadArduinoSimpleorLilypadArduinoSimpleSnap.
Figure8-2TheLilypadArduinoUSB
TheLilypadArduinoUSBhasthesamemicrocontrollerchipastheArduinoLeonardo.ThatmeansyoucanturnitintoamouseorkeyboardjustlikeyoucanwithanArduinoLeonardo,butitalsomeansitiseasiertoprogramthantheotherLilypadArduinos.TheLilypadArduinoUSBhasaUSBMicroconnectoronit—thesameconnectorthatisontheArduinoLeonardo.ProgrammingtheLilypadArduinoUSBisjustlikeprogramminganyoftheotherArduinoboardsyouhaveusedsofar:ConnecttheboardtotheUSBcableandthenconnecttheUSBcabletothecomputer.
TheothertypesofLilypadArduinodon’thaveaUSBMicroconnectoronthem.Insteadtheyhavesixpinsonthetopoftheboard.ThesepinsconnecttoaFTDIboard(seeFigure8-3),whichhasaUSBconnectoronit.Toprogramthoseboards,youfirstconnecttheFTDIboardtotheLilypadArduino,thenconnecttheUSBcabletotheFTDIboardandthenconnecttheUSBcabletothecomputer.SoifyoualreadyhaveaLilypadArduinoorcan’tfindaLilypadArduinoUSB,don’tworry!YoucanstilluseadifferentLilypad
Arduinoboard;justmakesureyoualsogetanFTDIprogrammingboard.
FTDIstandsforFutureTechnologyDevicesInternational,acompanythatmakesachipthatwasusedinmostArduinoboards.AnFTDIchiptranslatestheelectricalsignalssentbythecomputeroveraUSBcableintosignalstheArduinocanunderstand.TheArduinoUnousesachipsimilartotheFTDIchiptodothistranslationforthemicrocontrollerchip.ItcomesalreadyincludedontheArduinoUno’sboard.
TheLilypadArduinodoesn’thavethisextrachiponitsboard,soyouhavetoconnecttheLilypadArduinotoanFTDIboardthathasthechiponitwheneveryouwanttouploadnewsketches.TheLilypadArduinoUSBhasadifferentmicrocontrollerchipthantheArduinoUnoorLilypadArduino.ItschipcanhandlethetranslationfromtheUSBsignalonitsownwithoutasecondchip,soyoudon’tneedtouseanFTDIboard.
IfyouareinterestedinthedesigndetailsthatmaketheArduinoboardsdifferentfromeachother,checkoutSparkfun’scomparisonguideathttps://learn.sparkfun.com/tutorials/arduino-comparison-guide/introduction.
Figure8-3AnFTDIprogrammingboard,whichyouneedifyouareusingatypeofLilypadArduinootherthanaLilypadArduinoUSB
BlinkingfromaLilypadArduinoThefirstandvitallyimportantdifferencebetweentheArduinoUnoandLeonardoandtheLilypadArduinoisthatithasanONswitch!Theboardwon’tautomaticallyturnonifyougiveitpower,whichcanbeconfusingandfrustratingifyoudon’tknowabouttheswitch.Youmighteventhinkyourboardisbroken!Butdon’tfret.Theswitchisonthetopoftheboard,ontheoppositesideofthemicrocontrollerchipfromtheresetbutton.Figure8-4showswhereitis.
Figure8-4TheArduinoLilypadArduinoUSBONswitch
OneofthethingsthattheLilypadArduinoUSBcandothatotherboardscan’tdoischargeabattery.Thisisconvenientforwearableprojectsastheyalmostalwaysneedtobebatterypowered.Theswitchhastwopositions:ONandCHG.CHGisforchargingabatteryfromtheUSBcable.Youcan’tchargethebatteryandturnonthemicrocontrolleratthesametime.Youwillfindoutmoreabouthowtopowertheboardwithbatterieslater,whenyoubuildyourhoodie.
WheneveryoustartusinganewmicrocontrollerorArduinoboard,it’salwaysgoodtobeginwitha“HelloWorld”programthatdemonstratesthatyourboardisworkingcorrectlyandyouknowhowtoprogramit.YoufirstdidthiswithyourArduinoUnoinAdventure1.ForArduino,theBlinksketchisthe“HelloWorld”program.
OpentheBlinksketchbylaunchingtheArduinoIDEandgoingtoFile⇒Examples⇒01.Basics⇒Blink.Youdon’tneedtochangeanyofthecodeandcanimmediatelyuploadittotheboard.
Touploadit,youneedtoconnecttheboardtoyourcomputerandthentelltheArduinoIDEwhichboardyouareusing.GotoTools⇒BoardandselectLilypadArduinoUSBfromthelist,asshowninFigure8-5.ThenclicktheUploadbutton.
Figure8-5SelectLilypadArduinoUSBfromthelistofboards
AlightontheLilypadArduinoUSBstartsblinking,turningonforonesecondthenoffforonesecond.
CHALLENGE
NewArduinoboardsoftencomewithBlinkalreadyrunningonthem,soyourboardmightalreadyblinkitsLEDonandoffonPin13foronesecondattime.ChangethetimingintheBlinksketchsothattheLEDisoffforonlyhalfasecondinsteadofafullsecond.UploadittotheboardandmakesuretheLEDnowblinksaccordingtothenewsketch.
PrototypingSoftCircuitsNowthatyouknowhowtouploadasketchtoyourLilypadArduinoUSB,youcanstartconnectingsensorsandactuators.Thepuzzlingthingishowareyousupposedtodothat?TheLilypaddoesn’thavepinsthatyoucanplugjumperwiresinto.Ithasbigpadswithholesthatarelargeenoughtoallowyoutosewconductivethreadeasilytocreatesoftcircuits,butyoudon’twanttoseweverycircuit.Thattakesalotoftime.Sohowdoyouprototypewithsoftcircuits?Theanswerisalligatorclips(sometimesalsocalledcrocodileclips).
Asensorisadevicethatdetectssomethingintherealworldsuchaslight,soundormovementandtranslatesitintoanelectricalsignal.Examplesincludepotentiometersandlight-dependentresistors.
Anactuatorisadevicethattranslatesanelectricalsignalintoareal-worldactionsuchaslight,soundormovement.Examplesincludemotors,lightsandspeakers.
Softcircuitsarecircuitsbuiltwithflexiblematerialslikeconductivethreadandfabric.Theyareoftenusedinprojectsthataregoingtobeworn.
Alligatorclips,showninFigure8-6,arewireswithspring-loadedclipsthatresemblethejawsofanalligator.YouattachoneendoftheclipontotheLilypadArduinoUSBpadandtheothertothenextpartofthecircuit,suchasanLED.
Figure8-6Insteadofjumperwirestoconnectcomponents,usealligatorclipswhenprototypingsoftcircuits.
Alligatorclipsarewireswithspring-loadedclipsthatresemblethejawsofanalligator.Theyareusefulforprototypingsoftcircuitsorconnectingcomponentsthatdon’tusejumperwires.
TheLilypadArduinoUSBoperatesatalowervoltagethantheArduinoUnoandLeonardo.WhenyousetapintoHIGH,itoutputs3.3Vinsteadof5V.Youdon’thavetoworryaboutwhyituses3.3Vinsteadof5V,butitdoesmeanthatyourLEDdoesn’tneedacurrent-limitingresistorwithashigharesistancevalue.Youcanusearesistorthat’sanywherefrom68to100Ω.
YoucanalsobuyLilypadLEDsliketheonesinFigure8-7foryoursoftcircuitprojects.TheseareLEDsonpurpleboards(thatmatchtheLilypadArduinoboards),andtheyalreadyhavecurrent-limitingresistorsontheboardwiththem.Asabonus,youdon’thavetosewasmanycomponents!
Figure8-7LilypadLEDsaresewableLEDsthatalreadyhavecurrent-limitingresistors.
CHALLENGE
UsealligatorclipstobuildacircuitwithyourLilypadArduinoUSBandanLED.IfyouhavearegularLED,besuretouseacurrent-limitingresistorthatiseither68or100Ωaswell;otherwise,youcanuseaLilypadLED.
ChooseoneofthepadstoconnecttoyourLEDcircuit.Notethatyoudon’thaveasmanytochoosefromasyoudowithotherArduinoboards.Youroptionsfordigitalpinsare2,3,9,1011.ChooseapinandthenmodifytheBlinksketchtouseyourchosenpininsteadofPin13.UploadyoursketchandblinkyourLED!
GettingCleverwithArraysInAdventure5,youwerefirstintroducedtoarraysforstoringalistofvalueswithoutneedingtocreateanewvariableforeachone.Tocreatealistofints,createavariablethatisthedatatypeint[]andthenlistthenumbersinside{},asshowninFigure8-8.
Figure8-8Alistofintegers,alsocalledaone-dimensionalarray
Listsareone-dimensionalarrays,butarrayscanhavemorethanonedimension.Theycanhaveanynumberofdimensionsyoulike,butitcanbedifficulttopicturesomethingwithmorethanthreedimensions.Two-dimensionalarraysaresomethingyouprobablyarealreadyusedto—theyaredataarrangedinrowsandcolumnslikeaspreadsheet.Figure8-9showsonewayyoucanpictureatwo-dimensionalarray.
Atwo-dimensionalarrayisdatastoredinrowsandcolumnslikeinaspreadsheet.
Figure8-9Atwo-dimensionalarrayofintegersstoredinrowsandcolumns
Youwillbeusingtwo-dimensionalarraystostorethemessagesthatyourhoodiewilldisplay.Eachletterofyourmessagewillbeanarray.PictureanLEDsignatabusstoportrainstationthatdisplayslettersandnumbers.Youcanthinkofeachcharacterastakinguparectangleofspace—eachletterornumberhasawidthandheight.Withinthatrectanglethelightsareturnedoninapatterntoshowthatletterornumber.ThoserectanglesofLEDsforeachletterornumberaretwodimensionalarrays.
Tocreateatwo-dimensionalarrayrequiresalittlemoreworkthancreatingaone-dimensionalarray.Inaone-dimensionalarray,youdon’thavetosayhowmanyitemsareinyourlist.Youcanjustlistthembetweenthe{andthe},andtheArduinoIDEcountsthemforyou.Whencreatingatwo-dimensionalarray,however,youhavetocounttheitemsyourself.
ThefollowingcodecreatesavariablecalledtwoDArraythathasthreecolumnsandtworows:inttwoDArray[2][3]={{1,2,3},
{4,5,6}};
Youmightwanttostorethenumberofcolumnsandrowsinvariablesasitisusefulinformationtorefertolater.Ifyouwanttodothis,youneedtoaddconstinfrontofthevariables.Thatmeansthevariable’svaluewon’teverchange.constnumRows=2;
constnumCols=3;
inttwoDArray[numRows][numCols]={{1,2,3},
{4,5,6}};
Itmightnotyetbeclearwhyyouwouldeverwanttousetwo-dimensionalarrays,solet’s
buildacircuitthatusesthem.BuildthecircuitinFigure8-10withanLEDattachedtoPins2,3,9,10and11.StartbyconnectingeachpintothepositivesideofoneoftheLilypadLEDs.ThenconnectallthenegativesidesoftheLilypadLEDstoeachother.ConnectthenegativesideoftheLEDconnectedtoPin2totheGNDpadoftheLilypadArduinoUSB.
Figure8-10CircuitforanarrayofLEDs
Ifyoudon’thaveLilypadLEDs,replacethemwithcurrent-limitingresistorsthatare68or100ΩandnormalLEDs.
You’renowgoingtoanimatetheLEDsandstoreeachframeoftheanimationinatwo-dimensionalarray.StartbyopeningtheArduinoIDEandcreatinganewsketch.Createanemptysetup()andloop():voidsetup(){
}
voidloop(){
}
Createtwovariablesthatholdthenumberofrowsandcolumnsinthearrayatthetopofthesketch.ThearrayhasonecolumnforeachLED(fivecolumns)andonerowforeachframeoftheanimation.Thesimpleanimationfortheexamplehasnineframes(ninerows):constintnumLEDs=5;
constintnumFrames=9;
NextcreatethearraythatholdseachofthepinnumbersthathaveLEDs:intledPins[]={
2,3,9,10,11};
Thentypeoutthetwo-dimensionalarrayoftheanimation:intframes[numFrames][numLEDs]=
{
{1,0,0,0,0},
{0,1,0,0,0},
{0,0,1,0,0},
{0,0,0,1,0},
{0,0,0,0,1},
{0,0,0,1,0},
{0,0,1,0,0},
{0,1,0,0,0},
{1,0,0,0,0}};
Addthefollowinglinesofcodeinsidesetup()tosetthepinmodeforeachLEDpin:inti;
for(inti=0;i<numLEDs;i++){
pinMode(ledPins[i],OUTPUT);
Insideloop()iswhereyoustarttoseeunfamiliarcode!Addthefollowingcodetoyoursketch,andthenyoucangooveritinmoredetail://variablestokeeptrackofcurrentframeandLED
intframe;
intled;
for(frame=0;frame<numFrames;frame++){
//iteratethrougheachframestoredinarow
for(led=0;led<numLEDs;led++){
//turnonorofftheeachLEDintheframe
digitalWrite(ledPins[led],frames[frame][led]);
}
delay(300);//pausebetweeneachframe
}
Youhaveusedforloopsbefore,togothrougheachiteminalistonebyone.Becausetherearetwodimensionstotheframesarray(youcanthinkofitasalistoflists),twoforloopsareneeded.
Thefirstforloopgoesthrougheachrow,whichholdsaframeofdatadescribingwhatalltheLEDsshoulddo.ThesecondforloopgoesthroughthatframeandsetstheLEDtobeonoroff.AfterthesecondforloophasturnedeachoftheLEDsonoroff,thesketch
pausesbeforecontinuingtothenextframe.Ifitdidn’tdothis,theanimationwouldbetoofasttosee!Figure8-11showshowthearrayisiteratedover,rowbyrow.
Figure8-11Iteratingoverframesofananimationstoredinatwo-dimensionalarray
Thefollowingcodeisthefullsketch.Buildthecircuitanduploadthesketchtoseetheanimationinmotion:constintnumLEDs=5;
constintnumFrames=9;
//pinsthathaveLEDs
intledPins[]={
2,3,9,10,11};
//framesoftheanimation
intframes[numFrames][numLEDs]=
{
{1,0,0,0,0},
{0,1,0,0,0},
{0,0,1,0,0},
{0,0,0,1,0},
{0,0,0,0,1},
{0,0,0,1,0},
{0,0,1,0,0},
{0,1,0,0,0},
{1,0,0,0,0}};
voidsetup()
{
//setpinmodestoOUTPUT
inti;
for(inti=0;i<numLEDs;i++){
pinMode(ledPins[i],OUTPUT);
}
}
voidloop()
{
//variablestokeeptrackofcurrentframeandLED
intframe;
intled;
for(frame=0;frame<numFrames;frame++){
//iteratethrougheachframestoredinarow
for(led=0;led<numLEDs;led++){
//turnonorofftheeachLEDintheframe
digitalWrite(ledPins[led],frames[frame][led]);
}
delay(300);//pausebetweeneachframe
}
}
PassingDataBetweenFunctionsIfyouwanttodootherthingsinloop()besidesrunningtheanimation,it’susefultoputtheanimationcodeintoitsownfunction.Thenextexampleshowsyouhowdothat.
CreateafunctioncalleddisplayAnimation()andcutandpastetheanimationcodefromloop()intothefunction:voiddisplayAnimation(){
//variablestokeeptrackofcurrentframeandLED
intframe;
intled;
for(frame=0;frame<numFrames;frame++){
//iteratethrougheachframestoredinarow
for(led=0;led<numLEDs;led++){
//turnonorofftheeachLEDintheframe
digitalWrite(ledPins[led],frames[led][frame]);
}
delay(300);//pausebetweeneachframe
}
}
Rememberthatyounowneedtocallyournewfunctionfromloop()oritwillneverruntheanimation.ThenewfunctiondisplayAnimation()shouldbeafterloop()andloop()shouldlooklikethefollowingvoidloop()
{
displayAnimation();
}
Nowthatthecodecontrollingtheanimationisnicelycontainedwithinonefunction,youcantakeadvantageofhowfunctionswork.Youcanpassdatatothefunctionandthenhavethefunctionchangewhatitdoesaccordingtothatdata.
Inordertopassdata,youneedtocreateanargument.Thisisdoneinthesamelineofcodewhereyougivethefunctionaname.Youalsogiveyourargumentanameandsaywhatdatatypeitwillhave.
Changeyourfunctiontothefollowing:voiddisplayAnimation(intanimationSpeed){
ThedisplayAnimation()functionnowhasoneargumentthatisanint;thisisanimationSpeed.ThefunctionnowneedstodosomethingwithanimationSpeed.Itwillcontrolthelengthoftimetheanimationpausesbetweeneachframe.Usethisvariabletosetthedelay()aftereachframe.
Changethelineofcodethatsetsthedelayinthefunctiontothefollowing:delay(animationSpeed);//pausebetweeneachframe
NowyoucancallthefunctiondisplayAnimation()withdifferentvaluesfortheargument,toplaytheanimationatdifferentspeeds!Thefollowingcodeisthefullsketch.UploadittoyourLilypadArduinoUSBwithfiveLilypadLEDsconnectedandwatchthe
animationdescribedbythetwo-dimensionalarray://constmeansthevaluewon’tchange
constintnumLEDs=5;
constintnumFrames=9;
//pinsthathaveLEDs
intledPins[]={
2,3,9,10,11};
//framesoftheanimation
intframes[numFrames][numLEDs]=
{
{1,0,0,0,0},
{0,1,0,0,0},
{0,0,1,0,0},
{0,0,0,1,0},
{0,0,0,0,1},
{0,0,0,1,0},
{0,0,1,0,0},
{0,1,0,0,0},
{1,0,0,0,0}};
voidsetup()
{
//setpinmodestoOUTPUT
inti;
for(inti=0;i<numLEDs;i++){
pinMode(ledPins[i],OUTPUT);
}
}
voidloop()
{
displayAnimation(100);
displayAnimation(500);
displayAnimation(1000);
}
voiddisplayAnimation(intanimationSpeed){
//variablestokeeptrackofcurrentframeandLED
intframe;
intled;
for(frame=0;frame<numFrames;frame++){
//iteratethrougheachframestoredinarow
for(led=0;led<numLEDs;led++){
//turnonorofftheeachLEDintheframe
digitalWrite(ledPins[led],frames[frame][led]);
}
delay(animationSpeed);//pausebetweeneachframe
}
}
CHALLENGE
BuildthecircuitfortheLEDanimationshowninthesectionheaded“PassingDataBetweenFunctions.”Modifythecodeinthesketchtouseaforlooptocyclethroughspeedsfortheanimationfrom50to500.
Rememberthatyoucanincrementinstepshigherthanone,forexamplebycreatingthefollowingforloop:
inti;
for(i=0;i<100;i+=5){
}
BuildingaPOVHoodieHaveyoueverwavedasparkleraroundandnoticedthatitseemedtoleaveatrailoflight?Ormaybeyou’veseentoyswithasetofLEDsthatdisplayawordorimagewhenyoumovethemquickly.Bothareexamplesofpersistenceofvision(POV)whereyoureyesandbrainkeepseeingalightpathafterthelightsourceismovedorturnedoff.Inthecaseofthesparkler,theglowingsparklermovesbutyourbrainstillseeswhereitusedtobe,soitlookslikeit’sleavingatrail.Withthetoys,theLEDsareblinkingonandoffquicklyinapattern.Yourbrainputsallthedifferentpatternstogetherwhenthetoyismovedandinterpretsthepatternsasawordorimage.
Excitingly,youcanmakeyourownPOVdisplaywiththeLilypadArduinoUSBand,becauseyouareusingaLilypad,youcansewthecircuitintoclothesandwearit.YoucanthenprogramyourLilypadtodisplayasecretmessagethatcanbeseenbytakingalongexposurephotograph(seeFigure8-12).Sewingthecircuitontheshoulderofahoodieworkswell,butyoucansewitonanypieceofclothing!
Figure8-12Persistence-of-visionhoodie
WhatYouNeedYouneedthefollowingitemstobuildaPOVhoodie.Figure8-13showstheelectroniccomponentsthatyouneed:
AcomputerALilypadArduinoUSBAUSBmicrocableAbreadboard14alligatorclips7LilypadLEDs(or7LEDsand768Ωor100ΩresistorsifnotusingLilypadLEDs)Alithiumionpolymer(LiPo)batterySomenormalsewingthreadSomeconductivethreadAhoodieAsewingneedleScissorsSomewhitePVAgluePliers(ifnotusingLilypadLEDs)
Figure8-13TheelectroniccomponentsyouneedforthePOVhoodie
UnderstandingTheCircuitThecircuitforthePOVhoodieissimilartotheLEDanimationcircuityoumadeearlierinthisadventure.TheonlychangeisthatyouusesevenLEDsinsteadoffive.Figure8-14showsthecircuitschematicforthePOVhoodie.
Figure8-14CircuitschematicforthePOVhoodie
PrototypingwithAlligatorClipsThePOVhoodieisasoftcircuit,soyoushouldprototypethecircuitwithalligatorclipsbecausetheLilypadArduinoUSBandLilypadLEDsdon’tfitintoabreadboard.BuildthecircuitshowninFigure8-15.
Figure8-15Prototypingthecircuitwithalligatorclips
StartbyconnectingeachpintothepositivesideofoneoftheLilypadLEDs.ThenconnectallthenegativesidesoftheLilypadLEDstoeachother.ConnectthenegativesideoftheLEDconnectedtoPin2totheGNDpadoftheLilypadArduinoUSB.
Ifyoudon’thaveLilypadLEDs,replacethemwithcurrent-limitingresistorsandnormalLEDs.
ChargingtheBatteryTheLilypadArduinoUSBincludesaconnectorforarechargeablelithiumionpolymer
(LiPo)batteryandevenhasachargerbuiltin.LiPobatteriesareflat,silverbatteries.Youdon’tneedabigbatteryforthisproject.Batteriesaremeasuredinmilliamp-hours(mAh),whichisameasureofhowmuchcurrenttheycanoutputforhowlong.A500mAhbatteryprovidesagoodbalance—it’snottoobiganddoesn’tneedtobechargedtoofrequently—butyoucanusewhateversizebatteryyoucanbuyeasily.
Tochargethebattery,connectittotheLilypadArduinoUSBandconnecttheLilypadtoapowersourcesuchasacomputerwithaUSBcable.MakesuretheswitchontheLilypadboardisintheCHGposition.TheLEDaboveCHGontheboardlightsupwhenthebatteryischarging;thebatterystopschargingautomaticallywhenit’sfullycharged.
LiPobatteriescanbedangerousifyoudon’ttakecareofthemproperly.Neverleavethemontheirownwhilethey’recharging!It’salsobesttobuythemfromatrustedmanufacturerlikeAdafruitorSparkfun,oroneoftheirdistributors.OnlybuyLiPosthathavebuilt-inprotectioncircuitry,andneveruseabatterythatlooksswollenordamaged.AdafruithasaniceguideonhowtoworkwithLiPobatteriesathttps://learn.adafruit.com/li-ion-and-lipoly-batteries.
WritingtheCodeThecodefordisplayingthePOVmessageissimilartothecodefortheLEDanimationearlierinthisadventure.TheframesfortheLEDsarestoredintwo-dimensionalarrays:oneforeachletterandoneforaspace.Becausetherearesomanyarrays,tohelporganisethecodetheyareallstoredinaheader(.h)file.Thecodeisavailableatwww.wiley.com/go/adventuresinarduino.
OpenthedownloadedsketchintheArduinoIDE.Thesketchshouldhavetwotabs:onenamedpov_hoodieandtheotheralphabet.h.
Clickthepov_hoodietab.Changethemessageintheboldlineofcodeinloop()towhatyouwanttobewrittenonthehoodie,anduploadittoyourLilypadArduinoUSB.Yourmessagecanonlyconsistofuppercaselettersandspaces.voidloop()
{
Stringmessage="HELLO";//putmessageinallcapshere
printText(message);
}
Waveyourcircuitintheair(adarkroomandafriendtomovewiththecircuitmakesthiseasier),ortakealong-exposurephototoseethemessageasshowninFigure8-16.
Figure8-16Persistenceofvisionmessagecapturedwithalong-exposurephotograph
DIGGINGINTOTHECODE
OpenthesketchyoujustdownloadedintheArduinoIDE,andclickthealphabet.htabtoseethecodeintheheaderfile.
ThefollowingisthecodefortheletterA.Ifyouturnyourheadsideways,youmightbeabletoseetheshapeoftheletterAwrittenoutin1s:
intA[numFrames][numLEDs]={
{1,1,1,1,1,1,0},
{0,0,1,0,0,0,1},
{0,0,1,0,0,0,1},
{0,1,1,0,0,1,1},
{1,1,1,1,1,1,0}};
Inthemainsketch,theheaderfiledescribingallthelettersisimportedattheverytopofthefile:
#include"alphabet.h"
ThentherearethreevariablesdescribinghowlongtheLEDsareturnedoffbetweenletters,howlongtheyareonwhendisplayingaframeofaletterandwhatpinshaveLEDs.BecausetheLilypadArduinoUSBonlyhasfivedigitalpins,twoanalogpinsarealsoused:
intletterSpace=6;//timeLEDsoffbetweenletters
intdotTime=3;//timeLEDsareon
intledPins[]={
2,3,9,10,11,A2,A3};
Insidesetup(),eachpinMode()issettobeOUTPUTandserialcommunicationisstarted.TheserialcommunicationisusedfordebuggingtoseewhatisbeingoutputintheSerialMonitor:
//setpinmodestoOUTPUT
inti;
for(inti=0;i<numLEDs;i++){
pinMode(ledPins[i],OUTPUT);
}
Serial.begin(9600);
Theloop()iskeptquitesimpleasmostoftheworkisdoneinotherfunctions.ThemessagetobedisplayedisstoredinmessageandthensenttothefunctionprintText()asanargument.Becausetheheaderfileonlydescribeshowtodisplaycapitalletters,themessageneedstobewrittenonlyincapitallettersorspaces—thereshouldbenolowercaselettersorpunctuation:
Stringmessage="ABCD";//putmessageinallcapshere
printText(message);
ThefunctionprintText()isalongone,butitisjustdoingasimpletaskmanytimes.Itreadsinthemessage,letterbyletter,andthentellsthefunctionprintLetter()todisplaythatletterinthemessage.ThefollowingcodeisforonlyA,BandC,butyoucangettheideaforhowtherestofthealphabetworks:
for(inti=0;i<text.length();i++)
{
switch(text[i])
{
case'A':
printLetter(A);
break;
case'B':
printLetter(B);
break;
case'C':
printLetter(C);
break;
ThefunctionprintLetter()isjustlikethedisplayAnimation()functionyouwroteearlier.Itgoesframebyframethroughtheletterthatisbeingdisplayed.ItalsoprintswhatitisbeingsenttotheLEDstotheSerialMonitortohelpshowwhatisgoingon.Ithasanextraforloopattheendofthefunctiontopausebetweeneachletter;otherwise,itwouldbehardtoreadtheindividuallettersandtheywouldallblurtogether:
intframe;
intled;
//printletter
for(frame=0;frame<numFrames;frame++){
for(led=0;led<numLEDs;led++){
digitalWrite(ledPins[led],letter[frame][led]);
Serial.print(letter[frame][led]);
}
Serial.println();
//delaybetweeneachcolumndisplayed
delay(dotTime);
}
Serial.println("-------");
//printspaceafterletter
for(led=0;led<numLEDs;led++){
digitalWrite(ledPins[led],0);
}
//delayforspacebetweenletters
delay(letterSpace);
MakingthePOVHoodieAfteryouhavebuilttheprototypecircuitwithyouralligatorclipsanduploadedthecodetotestthatitallworks,youarereadytostartsewing!Usingconductivethread,youaregoingtostitchtheLilypadArduinoUSBpadstoeachoftheLEDs.Rememberthatconductivethreadisjustlikewire,butitdoesn’thavetheinsulatingplasticprotectingit.Thatmeansifanypiecesofthreadtoucheachother,theywillconductelectricitybetweenthemandmayshortyourcircuit.Useaseparatepieceofthreadforeachconnectionandmakesuretheydon’taccidentallytouchanotherpartofthecircuit.
MakingSewableLEDsIfyoudon’thaveLilypadLEDs,youcanstillusetheLEDsyouwoulduseinabreadboard.Usingpliers,twistthelegsoftheLEDsandresistorsintoloopsthatyoucansewthrough.YoucantwistthelongandshortlegsoftheLEDsintotwodifferentshapestokeeptrackofwhichisthepositiveandwhichisthenegative.Iliketotwistthepositiveintoacircleandthenegativeintoasquare(becauseitremindsmeofanegativesign)asshowninFigure8-17,butyoucanmakeanyshapesthathelpyoukeeptrackofthelegs.
Figure8-17Bendingthelegsofcomponentstomakethemsewable
SewingtheElectronicsSewthecircuitbygoingthroughthefollowingsteps:
1. StartbydecidingwhereyouwanttoplaceyourLEDsontheupperrightsleeveofyourhoodie.YoumaywanttomarkthelocationsoftheLEDswithpinsortailor’schalk.
2. StartwiththebottomLED.Usingconductivethread,stitchPin9tothepositivesideoftheLED.KeepthestitchesfirmagainstthefabricofthehoodieandstitchthepadsoftheLilypadArduinoUSBandtheLilypadLEDaboutfivetimestosecurethemtothefabric.Knotandcutthethread.SeeFigure8-18forguidance.
3. Alternatively,ifyouareusingregularLEDsandresistors,stitchtheArduinopadtotheLEDandthenuseaseparatepieceofconductivethreadtostitchtheLEDtotheresistor.
4. Withaseparatepieceofconductivethread,stitchPin10tothepositivesideofthenextLEDabovetheoneyoujustsewed.Again,firmlystitchthepadstothefabricandthenknotandcutthethread.
5. ContinuewitheachoftheremainingLEDs.Takecarethatthestitchedthreadsnevertoucheachother(seeFigure8-19).
6. ThenegativesidesoftheLEDs(orresistorsifyouarenotusingLilypadLEDs)canalltoucheachother,sotheycanbesewnwithasinglepieceofthread.StartatthenegativepadoftheLilypadArduinoUSBandthenstitchthebottomLED.AftersecuringthenegativepadoftheLED,continuestitchinguptothenextLED.
7. Repeatstep6,sewingthenegativepadofthenextLEDuntilyouhavesewnonalltheLEDsasinFigure8-20.
8. SecureeachoftheknotswithalittlewhitePVAglue.Theconductivethreadcansometimesunknotitselfovertime,sothegluehelpstopreventthis.
9. Usingnormalthread,stitcharoundthebatterytosecureittothehoodie.
Figure8-18FirstconnectionsforsewingtheLilypadcircuit
Figure8-19ContinuingtosewtheLEDsintothecircuit
Figure8-20ThesewnPOVcircuit
YoumightnotwanttosewyourLilypadArduinoUSBdirectlyontoyourhoodie,especiallyifyouwanttousethesameboardinmultipleprojects.TheLilypadArduinoSimpleSnap(http://arduino.cc/en/Main/ArduinoLilyPadSimpleSnap)comeswithfemalesnapssolderedtoeachofthepads.Youcanthensewthematchingmalesideofthesnapsintothehoodieusingconductivethread.Becausethesnapsaremetal,theyconductelectricity,butthesnapsletyouremovetheboardfromthehoodiewithoutharmingthehoodie.
YoucanmodifyyourLilypadArduinoUSBtoworkthesamewaybysolderingsnapsontothepadsyourself.Youcanfindmetalsnapsatanysewingorcraftstore.
FurtherAdventureswiththeLilypadIfyouwouldliketolearnmoreabouttheLilypadArduinoUSB,visititspageontheArduinowebsiteathttp://arduino.cc/en/Guide/ArduinoLilyPadUSB.
YoucanalsolearnmoreaboutusingtheLilypadandfindmoreprojectsathttp://lilypadarduino.org.
Therearealotbooksaboutsoftcircuitsforyoutochoosefrom.Herearejustafew:
FashioningTechnologybySyuziPakhchyan(MakerMedia,2008)Make:WearableElectronicsbyKateHartman(MakerMedia,2014)SwitchCraftbyAlisonLewisandFang-YuLin(PotterCraft,2008)SewElectricbyLeahBuechley,KanjunQiandSonadeBoer(HLTPress,2013)Make:WearableElectronicsbyKateHartman(MakerMedia,Inc.,2014)
ArduinoCommandQuickReferenceTable
Command Description
int[][] Indicatesthatthevariablewillbeatwo-dimensionalarrayofvariablesstoredinrowsandcolumns.
const Indicatesthatthevariablewillnotchangeitsvalue.
AchievementUnlocked:BrightlightofArduinofashionandmanipulatorofmultipledimensions!
IntheNextAdventureInthenextadventure,youputallyournewskillstogethertocreateapinball-inspiredgame!
YOU’VECOMEAlongway,andnowyou’vereachedyourfinaladventure—thebiggestyet!Inthisadventure,youaregoingtocombinedigitalinput,digitaloutput,analogueinputandanalogueoutputtocreateamarblemazegameliketheoneinFigure9-1.Inspiredbyretropinballmachines,yourgameknowswhenyou’vescoredpointsandtellsyouifyou’veachievedanewhighscore.Itcountsdowntowhenthenextgamebeginsandkeepstrackofthetimeremaininginthegame.Itevenhasitsownsoundeffects!
Figure9-1Acompletedbigadventuremarblemazegame
Thegamebringstogetheralotofthedifferentskillsyou’velearnedfromtheearlier
adventures,butthereareacoupleofotherthingsforyoutolearnbeforeyoucanbuildyourgame.Thefirstishowtouseapiezoasasensor.You’vealreadyusedapiezoasaspeakerbutitisamultitalentedcomponentandyoucanalsouseittosensevibrations,whichisavitalskillforyourmarblemazegame!
WhatYouNeedYouneedthefollowingitemsforyourmarblemazegame.TheelectroniccomponentsthatyouneedareshowninFigure9-2:
AcomputerAnArduinoUnoAUSBcableAbreadboardSomejumperwires6piezos61MΩresistor1redLED1yellowLED1greenLED3220Ωresistors1panelmountpush-to-makebutton1tactilepushbutton19Vbattery19VbatteryconnectorSomewireAmarbleAcardboardboxSomethickpaperorcardWhitePVAglueMaskingtapeorducttapePaintormarkersScissorsorautilityknifeAsolderingironSolder
Figure9-2Theelectroniccomponentsyouneedtobuildyourmazegame
PartOne:ScoringPointsInAdventure5youwereintroducedtopiezosasactuatorsthattranslateavaryingvoltageintoavibrationthatyoucanthenhearasasoundwave.Butthat’snotalltheycando!Piezosarecleverlittlecomponentsthatcanalsotranslatevibrationsintovaryingvoltage.
Inthisadventure,youusepiezostodetectwhichholeinthemazeyourmarblehasfallenthrough.Eachholeisworthadifferentnumberofpoints,sopartofyourgamedesignistomaketheholesthatarehardertoreachworthmorepoints.
SensingVibrationswithPiezosPiezoshavetheabilitytoproducevoltagespikesthatcoulddamageyourArduino,soyouneedareallybigresistortohelpprotectyourArduino.Aresistorvalueof100MΩ(that’s100millionOhms)istypicallyused.
Aspiezosoutputavaryingvoltage,youwillwanttomeasurenotjustLOWorHIGHvoltagesbutalsovoltagesinbetween.YouwillthereforewanttouseanAnalogPinandanalogRead()tomeasurethevoltage.
BuildthecircuitshowninFigure9-3:
1. Placetheredwireofthepiezoinanyoftheshort,middlerowsofthebreadboardandplacetheblackwireinoneofthelongoutsiderows.
2. Putonelegofa1MΩresistorinthesameshortrowastheredwireandtheotherleginthesamelongrowastheblackwire.
3. UseajumperwiretoconnecttherowwiththeredwireandresistorlegtoPinA0.4. Useanotherjumperwiretoconnecttherowwiththeblackwireandtheotherresistor
legtoGND.
Figure9-3Circuittouseapiezoasasensor
LaunchtheArduinoIDE.GotoFile ⇒ Examples ⇒ 06.SensorandopenthesketchKnock.UploadittoyourArduinoandopentheSerialMonitor.Tryoutthesketchbytappingonthepiezo.WatchwhathappenstotheLEDnexttoPin13andseewhatisprintedintheSerialMonitor.YoushouldseetheLEDturnonandoffwithyourknocksonthepiezo.
SettingaPointsThresholdYounowhavethebasicsofhowtoreadinavaluefromapiezo—butyouneedmorethanonepiezotomakeyourgamechallenging!Thenextstepistoaddfourmorepiezossothatyouhavefiveintotal.
OnthesamebreadboardwhereyouhaveonepiezoconnectedtoPinA0,setupfourmorepiezosinthesameway.ConnectthemtoPinsA1,A2,A3andA4asshowninFigure9-4.Ignorethelastpiezofornow(theoneconnectedtoPin9).
Figure9-4Circuitforfivepiezosassensorsandonepiezoasaspeaker
LaunchtheArduinoIDEandstartanewsketch.Beginbycreatinganemptysetup()andloop():voidsetup(){
}
voidloop(){
}
Becauseyouhavefivepiezostokeeptrackof,it’sbesttostorethemallinanarray.Atthetopofthesketch,addanarraythatstoresallthepinswiththepiezosassensorsandavariablethatstoreshowmanypiezosyouareusing:intpointsPins[]={
A0,A1,A2,A3,A4};
//numberofpiezosforpoints
intnumPointsPins=5;
Youdon’tneedtosetthepinmodeofAnalogPinswhenyouareusingthemasinputs,sotheonlylineofcodetoaddtoyoursetup()isforbeginningserialcommunication:Serial.begin(9600);
Insideloop(),readinthevalueofeachofthepiezos.Becausethepinsareallstoredinanarray,youcanuseaforloop.FornowyoujustprintthosevaluestotheSerialMonitor.
Addthefollowinglinesofcodetoyourloop,thenuploadittoyourArduinoUnoandopenSerialMonitorintheArduinoIDE://variablesforpins
inti;
for(i=0;i<numPointsPins;i++){
intcurrPinValue=analogRead(pointsPins[i]);
//printwhichpininarrayandvalue
Serial.print("Piezo:");
Serial.print(i);
Serial.println("Value:");
Serial.println(currPinValue);
}
Taponthepiezosandnotewhatvaluesarebeinggenerated.Dropthemarbleyouwilluseinyourmazegameontoapiezoandwatchthevalues.
Nowyouneedtochangeyoursketchsothatamessageisonlyprintedwhenapiezogoesaboveathresholdvalue.Inotherwords,amessageisonlyprintedwhenthepiezosaretriggeredwithastrongenoughforce.
Atthetopofyoursketchbeforesetup(),withyourothervariables,addavariabletosetthethresholdofwhenapiezoshouldtriggerscoringpoints.Setittoavaluethatmakessensefromyourtestswithyourmarble:intpiezoThreshold=800;
Insideofloop(),addanifstatement.Theifstatementcheckswhetherthecurrentpiezobeingreadhasgoneabovethethresholdthatyouset.Whenthecurrentgoesabovethethreshold,thepiezonumberandvalueareprintedtoSerialMonitor.inti;
for(i=0;i<numPointsPins;i++){
if(currPinValue>piezoThreshold){
//printwhichpininarrayandvalue
Serial.print("Piezo:");
Serial.print(i);
Serial.println("Value:");
Serial.println(currPinValue);
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
}
Uploadthechangestoyoursketchandcheckthateachpiezoonlyprintsamessagewhenyoudropthemarbleonit.Hereisthesketchasitstands://variablesforpins
intpointsPins[]={
A0,A1,A2,A3,A4};
//numberofpiezosforpoints
intnumPointsPins=5;
//---setup---------------------------
//runsoncewhenboardfirstpowered
//orreset
voidsetup(){
//startserialcommunication
Serial.begin(9600);
}
//---loop----------------------------
//runscontinuouslyaftersetup()
voidloop(){
inti;
for(i=0;i<numPointsPins;i++){
intcurrPinValue=analogRead(pointsPins[i]);
//ifabovethethreshold
if(currPinValue>piezoThreshold){
//printpointsandnewscore
Serial.print("Piezo:");
Serial.print(i);
Serial.println("Value:");
Serial.print(currPinValue);
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
}
}
AddingSoundEffectsNowit’stimetoseewhatthatsixthpiezoissupposedtodo!Intheprevioussectionyouworkedwiththefivepiezosthatareactingassensors;thesixthpiezoactsasaspeaker.InFigure9-4,thecircuitforthesixthpiezolooksjustlikethecircuitsfortheotherfivepiezos,whichmightbeconfusing.TheonlydifferenceisthatitisconnectedtoPin9insteadofanAnalogPin.
YouusePin9sothatyoucancalltone()tomakesoundthroughthepiezo.However,justbecausethepiezoisbeingusedasaspeaker,itdoesn’tpreventitfrompotentiallyproducingavoltagespikeasasensor.Ifthemarblehitsthespeakerpiezo,itcouldproduceavoltagespikethatcoulddamageyourArduinoUno.Soyouusethesameprotectioncircuitonthespeakerpiezo.
GoaheadandaddthelastpiezoonPin9asshowninFigure9-3.
Inyourcode,addavariableatthetopbeforesetup()tokeeptrackofthespeaker:intspeakerPin=9;
Rightafteryouhaveprintedyourmessagesintheforloopandbeforethedelay(),addthefollowinglinesofcodeinboldtoplayasoundwheneverapiezoistriggeredabovethethreshold://ifabovethethreshold
if(currPinValue>piezoThreshold){
//printpointsandnewscore
Serial.print("Piezo:");
Serial.print(i);
Serial.println("Value:");
Serial.print(currPinValue);
//playscoringmusic
tone(speakerPin,659,300);
delay(300);
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
UploadyoursketchtoyourArduinoUnoandtestthatyouhearatonewheneverapiezoistriggered.
KeepingScoreNowthatyouhavefivepiezosthatsensewhenthemarbledropsonthemandanotherthatactsasaspeaker,youcanstartassigningpointvaluestoeachofthesensorsandkeeptrackofyourscore.
Firstyouneedtocreateanewvariabletostoreyourscore.Atthetopofyoursketch,withyourothervariables,addthefollowingline:intcurrentScore=0;
Insidetheifstatementintheforloopinloop(),youaregoingtodothreethings.Firstyoucreateavariablethatcalculateshowmanypointshavejustbeenscoredandthenaddsittocurrentscore.ThenyouprintthenumberofpointsthathavejustbeenscoredandthenewtotalcurrentscoretotheSerialMonitor:if(currPinValue>piezoThreshold){
//addpoints
intnewPoints=(i+1)*10;
currentScore+=newPoints;
//printpointsandnewscore
Serial.print("Score!");
Serial.print(newPoints);
Serial.println("points");
Serial.print("Currentscore:");
Serial.print(currentScore);
Serial.println("points");
//playscoringmusic
tone(speakerPin,659,300);
delay(300);
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
Thenumberofpointsisdeterminedbyadding1tothepininthearraythatwastriggered(thevariablei)andthenmultiplyingthatnumberby10.Forexample,thepiezoonPinA3isitem3inthearray,sothescorefortriggeringthatpiezois(3+1)*10,or40points.
Thefollowingcodeisthefullsketchwiththechangesinbold.UploadittoyourArduinoUnoandopentheSerialMonitor.Checkthatthesoundeffectsandpointsmessagesallworkasyouwouldexpect://variablesforpins
intpointsPins[]={
A0,A1,A2,A3,A4};
intspeakerPin=9;
//numberofpiezosforpoints
intnumPointsPins=5;
//whenpointstriggered
intpiezoThreshold=800;
intcurrentScore=0;
voidsetup(){
//startserialcommunication
Serial.begin(9600);
}
voidloop(){
inti;
for(i=0;i<numPointsPins;i++){
intcurrPinValue=analogRead(pointsPins[i]);
//ifabovethethreshold
if(currPinValue>piezoThreshold){
//addpoints
intnewPoints=(i+1)*10;
currentScore+=newPoints;
//printpointsandnewscore
Serial.print("Score!");
Serial.print(newPoints);
Serial.println("points");
Serial.print("Currentscore:");
Serial.print(currentScore);
Serial.println("points");
//playscoringmusic
tone(speakerPin,659,300);
delay(300);
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
}
}
Youcandownloadallthesketchesfromthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
PartTwo:DesigningYourMazeGameAtlastyou’rereadytostartworkingonyourmaze!First,youneedtofindaboxthatyoucanturnintoyourgame.Theexactsizeisn’timportant—itjustneedstobebigenoughtoholdallthesensorsandtheArduinoUno,butit’sbestnottohaveaboxthat’ssobigthatyoucan’teasilyholditinyourhands.Aboxthatisapproximately10×13×3inches(26×33×8cm)workswell.
Ifyoucanonlyfindaboxthatistherightlengthandwidthbutistootall,usescissorsorautilityknifetomakeitshorter.Youmayneedhelpfromanadultifit’stoughtocut!
DrawingtheMazeWhenyouhaveyourboxready,makeasketchofwhatyouwantyourmazetolooklike.Hereareafewrulestokeepinmindwhenyoudothis(seeFigure9-5):
Makeyourgameintofivecolumnsanddecidewhereineachcolumnyouwillplacetheholes.Therewillonlybeonepiezoforeachcolumn,soyoucanonlyhaveoneholepercolumn.Decidehowmanypointsyouwanteachholetobeworth,withoneworth10points,oneworth20,oneworth30,oneworth40andoneworth50.Makethemostdifficultholeworththemostandtheeasiestoneworththeleast.It’simportanttoleaveanemptyspaceatthebottomofthemaze.Thisiswherethemarblerollsoutwhenyouhavescored.Youneedtoleaveenoughspacethatyoucaneasilyretrievethemarbleandplayagain.Reserveasectionintheupper-rightcornerforthreeLEDsandthebutton.Thesetellyouwhentostart,whenyourtimeisupandwhetheryouhaveachievedanewhighscore.LeaveenoughroomfortheLEDs,buttonandlabels.Approximately2×3inches(5×8cm)shouldbeenough.Decidewhereyouwillplacethemarbleatthestartofeachgame.
Figure9-5Guidelinesfordesigningyourmaze
Afteryouhavelaidoutwheretheholesandothercomponentswillbelocated,youarereadytodesignyourmaze!Drawthepathofyourmazeonapieceofpaper.Don’tlosethatpieceofpaper—you’llneeditlaterwhenyouactuallybuildthemaze.
DesigningtheGameCodeHere’showthemarblemazegameisplayed:
1. Theplayerpressesthestartbutton.TheredLEDlightsup,thentheyellowLEDandfinallythegreenLED.Thestartingmusicplaysandthegamestarts.Theplayerplacesthemarbleinthestartingpositiononthemaze.
2. Theplayertriestorollthemarblealongthemazeandintothedifferentholestoscorepoints.
3. Atoneplayswheneverpointsarescored.4. Eachtimetheplayerscores,themarblerollstothebottomofthebox.Theplayer
placesthemarblebackatthestartingpositionandtriestoscoreagain.5. Thestepsarerepeateduntilthetimerunsout.6. Iftheplayerhasjustachievedanewhighscore,atuneplaysandthegreenLED
blinks.Iftheydidn’tachieveanewhighscore,adifferenttuneplaysandtheredLEDblinks.
7. IftheArduinoUnoisresetorturnedoff,thehighscoreiscleared.Otherwiseplayerscanplaymoreroundsandtrytobeattheprevioushighscore.
Allofthesestepscanbebrokendownintofunctionsforthecode.Thenthosefunctionscanbecalledattherighttimeinthegame.Figure9-6showshowallthefunctionsinteractintheArduinosketchthatyouwillwritelater.
Figure9-6Howthecodeworkswhenagameisplayed
PrototypingtheCircuitYouhavealreadybuiltmostofthecircuitforthemazegame—youhavebuiltthecircuitforthefivesensorpiezosandthespeakerpiezo.TheremainingcomponentsarethethreeLEDsandbutton.Figure9-7showsthecircuitschematicforthefullmazegame.
Figure9-7Circuitschematicofthemazegame
Youshouldtestyourcircuitonabreadboardbeforebuildingyourfullmazegame—butyouknowthatbynow!Buildthecircuitnow(showninFigure9-8):
1. Startwiththepiezocircuitsthatyouhavealreadybuilt.2. AddthreeLEDstothebreadboard—onered,oneyellowandonegreen.Connectthe
negativelegstothelongrowconnectedtoGND.3. Placea220Ωcurrent-limitingresistorbeforeeachLED.4. UseajumperwiretoconnecttheresistorbeforetheredLEDtoPin6,theresistor
beforetheyellowLEDtoPin5andtheresistorbeforethegreenLEDtoPin4.5. Placeyourtactilepushbuttonacrossthegapinthemiddleoftheboard.Useajumper
wiretoconnectonesideofyourbuttontothelongrowconnectedtoGND.ConnecttheothersidetoPin7.
Figure9-8Mazegameprototypecircuitonabreadboard
PartThree:WritingtheCodeYou’reabouttowritethelongestArduinosketchofalltheadventures.Don’tworry—youareready!Youhaveseenallthedifferentpartsofthecodebefore.You’reabouttoputittogetherintoamorecomplexsketch,butthesketchisjustmadeupofsmallerchunksofcode.Youstartwiththepiezo-scoringsketchthatyouwroteearlierinthisadventureandaddnewfeatures,littlebylittle.Youshouldtestwhatyouhavewrittenafteryouaddeachnewfeature;I’lltellyouwhenyoushoulddothat.
StartingtheGameTheLEDsneedtoshowthecountdowntobeginwheneveranewgameisstarted.YoucanalsoprintserialmessagesthatshowextrainformationifyourArduinoUnoisconnectedtoyourcomputer.ThefirstlinesofcodearethevariablesfortheLEDpins.Atthetopofyoursketchaddthefollowinglines:intgreenLED=4;
intyellowLED=5;
intredLED=6;
Tohelporganiseyoursketch,youcreateafunctionthatperformsallthetasksthatneedtobedonewhenanewgamebegins.Addthefollowingcodetotheendofyoursketchafterloop():voidstartGame(){
//makesureallLEDsstartoff
digitalWrite(redLED,LOW);
digitalWrite(yellowLED,LOW);
digitalWrite(greenLED,LOW);
Serial.println("****NEWGAME****");
Serial.print("Startinggamein…");
//turnonredLED
digitalWrite(redLED,HIGH);
Serial.print("ready…");
delay(1000);
//turnoffredLED
digitalWrite(redLED,LOW);
//turnonyellowLED
digitalWrite(yellowLED,HIGH);
Serial.print("set…");
delay(1000);
//turnoffyellowLED
digitalWrite(yellowLED,LOW);
Serial.println("go!");
//turnongreenLED
digitalWrite(greenLED,HIGH);
//resetscore
currentScore=0;
}
ThestartGame()functionmakessurealltheLEDsareoffatthestartofthegameandthenturnsthemononebyone.Italsoprintscountdownmessages.Attheendofthefunctionthevariableholdingthecurrentscore,currentScore,isresetto0.
Insetup(),setthepinMode()toOUTPUTforeachoftheLEDsandcallthefunctionyoujustwrotesothatanewgamestartsautomaticallywhenyouturnontheArduinoUno.Thenewcodeyoushouldaddisinbold:voidsetup(){
//setuppinmodeforbutton
pinMode(buttonPin,INPUT_PULLUP);
//setuppinmodesforLEDs
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
//startserialcommunication
Serial.begin(9600);
//startcountdowntostart
startGame();
}
Uploadyoursketch,openSerialMonitorandtestthatitworks.YourLEDsshouldlightupintherightorderandcountdownmessagesshouldappearinSerialMonitor.
EndingtheGameToturnyourmarblemazeintoagame,youneedatimersotheplayercanscoreasmanypointsaspossiblewithinagiventime.
Tomakeatimerinyourcode,beginbyaddingthefollowingvariablestothetopofyoursketch.Youdon’tuseallofthemrightawaybuttheywillallbeusedinyourcompletedgame:intbuttonPin=7;
intmaximumTime=10000;
longgameStartTime;
booleanplayingGame=false;
ThefirstvariableyouuseisgameStartTime.Youmightnoticethatitisn’tanint—it’salong.YoufirstencounteredlonginAdventure6.Alongcanstoreabiggernumberthananint,whichwasneededforthecapacitivesensinglibrarythatyouusedtomakeyourcrystalball.HerethegameStartTimevariablestoresthetimecountedinthenumberofmillisecondssincetheArduinosketchbegan.Thatcouldbeaverybignumber,sothevariableshouldbealonginsteadofanint.
Inordertostorethetimethatagamestarts,youuseanewfunction:millis().Thisisabuilt-infunctionforArduinosoyoudon’tneedtoimportalibrarytouseit.Itreturnsthecurrentnumberofmillisecondsthathavepassedsincethesketchstarted.Youwanttosavethisnumbersothatyoucancheckandseehowmuchtimehasgonebysinceagamewasstarted.
AddthefollowinglineofcodetotheveryendofyourstartGame()function:gameStartTime=millis();
Inloop(),youthencheckandseeiftimehasrunout.ThevariablemaximumTimestoreshowlongagamecanrun.It’scurrentlysetto10,000milliseconds(10seconds),butyoucanmakethatshorterorlonger.
Addthefollowingifstatementtothetopofloop().Allthecodeyouhavewrittensofarinyourloopthatreadsinfromthepiezosandkeepstrackofthescoreshouldgoinsidetheifstatement.Thatway,newpointscanonlybescoredifthetimehasn’trunout:if((millis()-gameStartTime)<maximumTime){
//codeyouhavealreadywrittenthatkeepstrackofpointsbeing
scored
}
TheifstatementchecksthatthetimesincethegamewasstartedisstilllessthanmaximumTime.
ThevariableplayingGameisoneofthevariablesyoujustaddedtothetopofyoursketch.IthasaBooleandatatype.Thatmeansthevariablecanonlybeequaltotrueorfalse.Youareusingthevariableasaflag.Wheneveragameisbeingplayed,thevariableissettotrue,andwhenagameisn’tbeingplayedthevariableissettofalse.Youcanthenmakedecisionsincodebasedonwhetheragameisbeingplayed.
Aflagisavariableinaprogramthatkeepstrackofthestateofsomeotherpartofthecode.ItisusuallyaBoolean.
InstartGame(),addalineattheendofthefunctionthatsetstheflagplayingGametotrue:playingGame=true;
NowcreateanewfunctionattheendofyoursketchcalledendGame().Thisfunctioniscalledwhenthetimehasrunout.ItthensetstheplayingGameflagtofalse:voidendGame(){
Serial.println("GameOver!");
Serial.print("Score:");
Serial.println(currentScore);
//setflagthatnotcurrentlyplayingagame
playingGame=false;
}
Theifstatementchecksifagameiswithinthetimelimit.Ifthatisn’ttrue,youwantsomethingotherthanscoringpointstooccur.Ifthegameisbeingplayedandthetimehasrunout,youneedtoendthegame.Ifthetimehasrunoutandthegameisn’tbeingplayed,thenyouneedtodisplaywhetheranewhighscorewasachieved.Youcodethenewhighscorepartinthenextsection.Fornow,focusonendingthegame.
Inthecodethatrunsonlywhenthegameisn’tbeingplayedorthetimehasrunout,youuseanelsestatement.Anelsestatementcontainsthecodethatshouldberunonlywhentheconditionsintheifstatementarefalse.Itwon’trunthatcodeatanyothertime,andithastobepairedwithanif.
Insideyourloop,aftertheclosing}ofyourifstatement,addthefollowinglines:else{
//elseifplayingagamebuttimehasrunout
if(playingGame){
//endthegame
endGame();
}
}
Thecodeinintheelsestatementisrunonlyifthetimehasrunout.Theifstatementinsidetheelsestatementchecksifthegameflagisstillsettotrue.Ifitis,thenthegameisendedbycallingendGame.
UploadthesketchtoyourArduinoUnoandtestthatitworks.Itshoulddoeverythingthatithasbeendoingsofar—startingagameandkeepingtrackofthescore.NowitshouldalsoendthegameaftermaximumTime,whichissetto10seconds.
StartingaNewGameNowthatyourgameendsafteratimelimit,youneedawaytostartanewgametotryandbeatyourscore!Thenextstepistoaddabuttonthatstartsanewgame.Youalreadyhavethebuttoninthecircuitonyourbreadboard,soyouonlyneedtoaddthecode.
Insidetheelsestatementyoujustaddedintheprevioussection,addanotherelsestatementtotheifstatementthatischeckingwhethertheplayingGameflagistrue:else{
intbuttonValue=digitalRead(buttonPin);
if(buttonValue==0){
//buttonispressed,startnewgame
startGame();
}
}
NowiftheplayGameflagissettofalse,thebuttonischeckedtoseeifitisbeingpressed.Ifitis,thenanewgameisstartedbycallingthestartGame()function.
Theloop()nowhasthefollowingcode.UploadyoursketchtoyourArduinoUnoandtestthateverythingworks.AnewgameshouldstartwithitscountdownLEDswhenyoufirststarttheArduinoUno,anditshouldendafter10seconds.Ifyoupushthebutton,anewroundofthegamebegins:voidloop(){
//ifplayingagameandstillwithintime
if((millis()-gameStartTime)<maximumTime){
//readineachpointspin
inti;
for(i=0;i<numPointsPins;i++){
intcurrPinValue=analogRead(pointsPins[i]);
//ifabovethethreshold
if(currPinValue>piezoThreshold){
//addpoints
intnewPoints=(i+1)*10;
currentScore+=newPoints;
//printpointsandnewscore
Serial.print("Score!");
Serial.print(newPoints);
Serial.println("points");
Serial.print("Currentscore:");
Serial.print(currentScore);
Serial.println("points");
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
}
}
else{
//elseifplayingagamebuttimehasrunout
if(playingGame){
//endthegame
endGame();
}
//elseifnotplayingagame
else{
//checkifbuttonhasbeenpressedtostartnewgame
intbuttonValue=digitalRead(buttonPin);
if(buttonValue==0){
//buttonispressed,startnewgame
startGame();
}
}
}
}
Bynowtheloop()isgettingalittlecomplicated!Figure9-9illustrateshowitallworks.Italsoshowswhatyouwillbeaddingnext—keepingtrackofthehighscore.
Figure9-9Howaloop()works
KeepingTrackoftheHighScoreAtthetopofyoursketch,addthreemorevariables:booleannewHighScore=false;
intcurrentScore;
inthighScore=0;
Youhaveaddedonemoreflag:newHighScore.Thisflagkeepstrackofwhetherthelastgameplayedresultedinanewhighscore.Ifitdid,thenthegreenLEDflasheswhenagameisn’tbeingplayed.Ifitdidn’t,thentheredLEDflashes.
InendGame(),addthefollowingcode.Itcomparesthelatestscorewiththesavedhighscore.Ifit’sanewhighscore,thentheflagissettotrue.Otherwiseitissettofalse:if(currentScore>highScore){
//ifanewhighscore
highScore=currentScore;
Serial.println("NewHighScore!");
newHighScore=true;
}
else{
//elsenewnohighscore
newHighScore=false;
}
NowyouneedtoaddthecodetomaketheLEDsflash.Inloop(),insidetheelsestatementwhereyoucheckthebutton,addthefollowingcode:if(newHighScore){
digitalWrite(greenLED,HIGH);
delay(200);
digitalWrite(greenLED,LOW);
delay(200);
}
//blinkredifflagisfalse
else{
digitalWrite(redLED,HIGH);
delay(200);
digitalWrite(redLED,LOW);
delay(200);
}
Uploadthesketchandcheckthatitworks.YoushouldbeabletostartagamewhentheArduinoUnoisturnedonorreset,thenwhenthegameendsthegreenLEDflashesifyougetanewhighscore.Ifyoudidn’tachieveanewhighscore,theredLEDflashesuntilyoustartanewgame.
Ifyouarehavingproblemsgettingyoursketchtocompilebecauseofatypo,trydownloadingthesketchfromthecompanionsite(www.wiley.com/go/adventuresinarduino).Readingthroughhowthecodeworksbeforetryingtotypeitallwillhelpyoubetterunderstandwhatisgoingon.
AddingSoundsYoualreadyhavewrittenthecodethatplayssoundswhenpointsarescoredinPartOneofthisadventure.Theonlythinglefttodoistoputitinitsownfunction.Thatmakesthecodeeasiertoreadandmakesiteasiertounderstandwhatisgoingon.
Cutthetwolinesofcodeinloop()thatplayasoundwhenapiezoistriggeredandputitinitsownfunctioncalledplayScoreMusicattheendofthesketch:voidplayScoreMusic(){
tone(speakerPin,659,300);
delay(300);
}
Nowyouneedtocallthefunctionyoujustwrote.Inloop(),callthefunctionrightafteryouhaveprintedthecurrentscore:playScoreMusic();
Therearejustthreemoretonesequencestocode.Thefirstisthemusicthatwillbeplayedwhenanewgamestarts.Attheendofthesketch,addanewfunctioncalledplayStartMusic()withthefollowinglinesofcode:voidplayStartMusic(){
tone(speakerPin,523,300);
delay(300);
tone(speakerPin,659,300);
delay(300);
tone(speakerPin,784,300);
delay(300);
tone(speakerPin,1047,500);
delay(600);
}
AttheendofstartGame,callthefunctionyoujustwrote:playStartMusic();
Oneoftwodifferenttonesequencesareplayedattheendofthegame.Whichoneisplayeddependsonwhetheranewhighscorewasjustachieved.Thesequencefornewhighscoresoundshappierthanthetonesplayedwhenyoudidn’tgetanewhighscore.
Attheendofyoursketch,addtheplayNewHighScoreMusic()andplaySadEndMusic()functions:voidplayNewHighScoreMusic(){
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(500);
}
voidplaySadEndMusic(){
tone(speakerPin,698,300);
delay(300);
tone(speakerPin,622,300);
delay(300);
tone(speakerPin,587,300);
delay(300);
tone(speakerPin,523,500);
delay(600);
}
BothfunctionsarecalledwithintheendGamefunction.playNewHighScoreMusiciscalledinsidetheifstatementthatcheckswhetheranewhighscorewasachieved,andplaySadEndMusiciscalledinsidetheelse:if(currentScore>highScore){
//ifanewhighscore
highScore=currentScore;
Serial.println("NewHighScore!");
newHighScore=true;
//playnewhighscoremusic
playNewHighScoreMusic();
}
else{
//elsenonewhighscore
newHighScore=false;
//playendmusic
playSadEndMusic();
}
CHALLENGE
Trychangingthestartandendtone()sequencestocustomiseyourgame!
Andthat’sit!Younowhavethefullsketch.Thefullcodeisshownheresothatyoucancheckwhatyou’vewrittenagainstit.UploadthesketchtoyourArduinoUnoandtestitoutwithyourbreadboardcircuit.Afteryouarehappywithhowyourgameworks,youarereadytofinishbuildingyourmazegame!//variablesforpins
intpointsPins[]={
A0,A1,A2,A3,A4};
intbuttonPin=7;
intgreenLED=4;
intyellowLED=5;
intredLED=6;
intspeakerPin=9;
//numberofpiezosforpoints
intnumPointsPins=5;
//whenpointstriggered
intpiezoThreshold=800;
//gametimervariables
intmaximumTime=10000;
longgameStartTime;
booleanplayingGame=false;
//highscorevariables
booleannewHighScore=false;
intcurrentScore;
inthighScore=0;
//---setup---------------------------
//runsoncewhenboardfirstpowered
//orreset
voidsetup(){
//setuppinmodeforbutton
pinMode(buttonPin,INPUT_PULLUP);
//setuppinmodesforLEDs
pinMode(greenLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(redLED,OUTPUT);
//startserialcommunication
Serial.begin(9600);
//startcountdowntostart
startGame();
}
//---loop----------------------------
//runscontinuouslyaftersetup()
voidloop(){
//ifplayingagameandstillwithintime
if((millis()-gameStartTime)<maximumTime){
//readineachpointspin
inti;
for(i=0;i<numPointsPins;i++){
intcurrPinValue=analogRead(pointsPins[i]);
//ifabovethethreshold
if(currPinValue>piezoThreshold){
//addpoints
intnewPoints=(i+1)*10;
currentScore+=newPoints;
//printpointsandnewscore
Serial.print("Score!");
Serial.print(newPoints);
Serial.println("points");
Serial.print("Currentscore:");
Serial.print(currentScore);
Serial.println("points");
//playscoringmusic
playScoreMusic();
//pausesothatsamemarbledoesn’tscoretwice
delay(300);
}
}
}
else{
//elseifplayingagamebuttimehasrunout
if(playingGame){
//endthegame
endGame();
}
//elseifnotplayingagame
else{
//checkifbuttonhasbeenpressedtostartnewgame
intbuttonValue=digitalRead(buttonPin);
if(buttonValue==0){
//buttonispressed,startnewgame
startGame();
}
//blinkgreenifnewHighScoreflagistrue
if(newHighScore){
digitalWrite(greenLED,HIGH);
delay(200);
digitalWrite(greenLED,LOW);
delay(200);
}
//blinkredifflagisfalse
else{
digitalWrite(redLED,HIGH);
delay(200);
digitalWrite(redLED,LOW);
delay(200);
}
}
}
}
//---startGame---------------------------
//setsupvariablesforanewgameandstarts
//countdown
voidstartGame(){
//makesureallLEDsstartoff
digitalWrite(redLED,LOW);
digitalWrite(yellowLED,LOW);
digitalWrite(greenLED,LOW);
Serial.println("****NEWGAME****");
Serial.print("Startinggamein…");
//turnonredLED
digitalWrite(redLED,HIGH);
Serial.print("ready…");
delay(1000);
//turnoffredLED
digitalWrite(redLED,LOW);
//turnonyellowLED
digitalWrite(yellowLED,HIGH);
Serial.print("set…");
delay(1000);
//turnoffyellowLED
digitalWrite(yellowLED,LOW);
Serial.println("go!");
//turnongreenLED
digitalWrite(greenLED,HIGH);
//playstartmusic
playStartMusic();
//startgametimer
gameStartTime=millis();
//setflagthatcurrentlyplayingagame
playingGame=true;
//resetscore
currentScore=0;
}
//---endGame---------------------------
//setsupvariablesforanewgameandstarts
//countdown
voidendGame(){
Serial.println("GameOver!");
Serial.print("Score:");
Serial.println(currentScore);
//turnoffgreenLED
digitalWrite(greenLED,LOW);
//calculatehighscore
if(currentScore>highScore){
//ifanewhighscore
highScore=currentScore;
Serial.println("NewHighScore!");
newHighScore=true;
//playnewhighscoremusic
playNewHighScoreMusic();
}
else{
//elsenewnohighscore
newHighScore=false;
//playendmusic
playSadEndMusic();
}
Serial.print("HighScoreis:");
Serial.println(highScore);
Serial.println();
//setflagthatnotcurrentlyplayingagame
playingGame=false;
}
//---playStartMusic-----------------------
//playsstartingtonesequence
voidplayStartMusic(){
tone(speakerPin,523,300);
delay(300);
tone(speakerPin,659,300);
delay(300);
tone(speakerPin,784,300);
delay(300);
tone(speakerPin,1047,500);
delay(600);
}
//---playScoreMusic-----------------------
//playsscoringtone
voidplayScoreMusic(){
tone(speakerPin,659,300);
delay(300);
}
//---playSadEndMusic-----------------------
//playssadtonesequence
voidplaySadEndMusic(){
tone(speakerPin,698,300);
delay(300);
tone(speakerPin,622,300);
delay(300);
tone(speakerPin,587,300);
delay(300);
tone(speakerPin,523,500);
delay(600);
}
//---playNewHighScoreMusic-----------------------
//playshappynewhighscoretonesequence
voidplayNewHighScoreMusic(){
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(200);
tone(speakerPin,440,500);
delay(200);
tone(speakerPin,880,300);
delay(500);
}
PartFour:BuildingtheMazeGameNowthatyouhaveyourcodeandcircuittestedandworking,it’stimetofinishbuildingyourmaze.Youaregoingtouseaboxwithnolid—sothreesidesandbottom,butnotop.Youwillbemakingapartialtopfortheboxthatcontainthemazeandholesforthemarbletodropthrough.Ifyouwanttocovertheboxwithpaintorpapertodecorateit,youmightfinditeasiertodobeforecuttingholesandassemblingtheelectronicsinsideit.
Youcanwatchavideoofhowtobuildyourmazegameonthecompanionsiteatwww.wiley.com/go/adventuresinarduino.
MakingtheMazeUsethefollowingstepstocreatethemaze:
1. Cutfourstripsofverythickpaperorcardthatarethelengthofyourmazeandapproximately3”(8cm)high.Foldoverabouthalfaninch(1cm)ofthecardsothatyoucangluethestripsofpapertotheinsideofthebox.Thesestripsstopthemarblefromrollingontoanotherpiezoandaccidentallytriggeringmorepointsafterithasdroppedfromthemaze.GluethestripsofpaperintoplaceasshowninFigure9-10.
2. Cutanotherpieceofcardboardabout2”(5cm)widerthanthebottomofyourboxwidthandabout2”(5cm)shorterthanthelengthofyourmaze.Youcanfoldtheextrainchoneachsideintoflapstohelpkeepthemazefirmlyinplaceinthebox.SeeFigure9-11asaguide.
3. Now’sthetimetofindthepieceofpaperonwhichyoucreatedyourdesignforthemazeearlierinthisadventure.Usingthisasyourguide,markthemazeandholelocationsonthepieceofcardboardthatyoujustcut.MarktheholesfortheLEDsandbutton.
4. Maketheholesinthecardboardforthemarble,LEDsandbutton,asshowninFigure9-12.
5. Create“walls”frompapertoformyourmaze.Cutstripsofpaperandfoldanedgetogluetothecardboardalongyourmazelines.
6. Usepaintormarkerstodecoratethecardboardinanywayyoulike—here’swhereyoucanletyourimaginationrunwild!Youprobablywanttoincludesomeindicationofthenumberofpointsthatcanbescoredateachhole.
Figure9-10Gluestripsofcardtoguidethemarbleafteritdropsthroughahole.
Figure9-11Lidofthemazegamefittedtobottom
Figure9-12Mazegamebeforeelectronics
AssemblingthePiezosYouarenowgoingtostartassemblingyourcircuit.Usethefollowingstepstoassemblethepiezos:
1. Markonyourboxwhereyourpiezos,LEDsandbuttonwillbelocated.2. Intheupper-rightcornerofyourbox,pokeaholethroughthecardboardsothatall
thewiresfrominsidetheboxcanpassthroughandeventuallyreachtheArduinoUnoontheoutsideofthebox.
3. CutwiresforeachofthepiezosthatreachfromtheredwireofeachpiezototheArduinoUno.Cutanothersetofwiresthatconnectalltheblackwiresfromthepiezostoeachother(seeFigure9-13).
4. Soldera1MΩresistorbetweentheredandblackwiresofthepiezos.Solderthewiresontotheresistoronthesamesideastheredwirefromthepiezos.Solderthewiresconnectingeachoftheblackwiresfromthepiezos.SeeFigure9-13forguidance.Labelthewiressoyouknowwhichwiregoestowhichpin.
Onlystartthesolderingstepswhenthereisanadultnearbytohelpyou.Solderingcanbedangerous,sobecareful!
5. InsertthesixwiressolderedtotheredwiresofthepiezosintotheirinputpinsontheArduinoUno.Insertthewiresolderedtothepiezos'blackwiresintoGND.Uploadthemazegamesketchandtestthatthepiezosallwork.Youshouldbeabletoscorepointswithfiveofthem,andthesixthshouldplaybackthesoundeffectsandmusic.
Figure9-13Wiringlayoutforpiezos
AssemblingtheLEDsandButtonWhenyou’resurethatanywetpaintorgluethatyouusedinyourdecorationshavedried,usethefollowingstepstoassembletheLEDsandbutton:
1. Solderacurrent-limitingresistorontoeachofthepositivelegsoftheLEDs.CutandsolderonwiresthatreachfromeachoftheresistorstotheArduinoUno.
2. CutandsoldertwowiresfromeachofthecontactsonthebuttonthatreachestotheArduinoUno.
3. PlacetheLEDsandbuttonintheirholesonthecardboardtoptothegame.SolderthenegativelegsoftheLEDsandonecontactofthebuttontogether.Figure9-14showswhatyoushouldhaveinfrontofyouonceyou’vefinishedsoldering.
Figure9-14SolderthenegativelegsoftheLEDsandonecontactofthebuttontogether.
CompletingtheFinishingTouchesYoujustneedafewfinishingtouchestocompletethisadventure!Usethefollowingstepstobringitalltogether:
1. Passtheallthewiresfromthepiezos,LEDsandpushbuttonthroughtheholeinbackofthebottombox.AttachtheArduinoUnototheoutsideoftheboxneartheholeforthewiresusingmaskingtape.
2. ConnectthewirestotheArduinoUnowiththesensorpiezosconnectingtoanaloginputs,andconnectthespeakerpiezo,buttonandLEDstodigitalpins.OnewireconnectingallthenegativewiresofthepiezosshouldconnecttooneGNDpin,andanotherwireconnectingthenegativelegsoftheLEDsandbuttonshouldconnecttoanotherGNDpin.
3. Testthatyourlights,buttonandpiezosareallactingasyouexpectbyplayingaroundofyournewgame.
Finished!Congratulationsoncompletingyourbigadventure!ThatwasalotofworkbutIhopeyoufounditrewarding.Youcannowrelaxbyplayingafewroundsofyournewmarblemazegame!
ArduinoCommandQuickReferenceTable
Command Description
booleanDatatypeforavariable.Canbeeithertrueorfalse.Seealsohttp://arduino.cc/en/Reference/BooleanVariables.
else Codethatisexecutedonlyiftheprecedingifstatementwasfalse.Seealsohttp://arduino.cc/en/Reference/Else.
millis()FunctionthatreturnshowlongtheArduinosketchhasbeenrunninginmilliseconds.Seealsohttp://arduino.cc/en/Reference/Millis.
FurtherAdventures:ContinuingYourAdventureswithArduinoTheArduinoisagreatwaytolearnaboutelectronicsandcodingbutofcoursethatisonlyhalfthefun.Asyou’veseen,projectsreallycomealivewhenyoustartembeddingyourArduinointophysicalobjects.Youhaveusedalotofdifferenthandtoolsandtechniques,butwhynotstartexploringdigitaltoolslikelasercuttersand3Dprinters?CheckoutMakeMagazine’ssite(http://makezine.com/3d-printing/)togetstarted.
Youcouldalsotaketheelectronicsandcodingskillsyou’velearnedwiththeArduinoandusethemwiththeRaspberryPi!CheckoutAdventuresinRaspberryPibyCarrieAnnePhilbin(Wiley,2014).
Mostimportantly,rememberthatyouarenowamemberofaworldwideArduinocommunity.YoucanalwaysfindmoreresourcesandtutorialsontheArduinowebsite(http://arduino.cc)alongwithaforumfullofnicepeoplereadytoansweryourquestions.
AchievementUnlocked:Arduinomastermind!
JUSTBECAUSEYOU’VEreachedtheendofyourArduinoadventureshere,itdoesn’tmeanyouradventuresarefinished!It’stimeforyoutoventureoutonyourown.Therearelotsofthingstoexploreandmanyresourcestohelpyouexplorethem.
MoreBoards,Shields,SensorsandActuatorsYouhavealreadylookedattwoArduinoboardsbesidestheArduinoUno:theLilypadandLeonardo.Arduinoscomemanyshapesandsizes,soifyouhaveaprojectinmind,explorewhatmightbebestforit.Doesitneedtobesmall?TheSparkfunArduinoProMini(www.sparkfun.com/products/11113)orArduinoMicro(http://arduino.cc/en/Main/ArduinoBoardMicro)mightbeperfect.Doyouwanttoaddlotsoftouchsensorsandplayaudiofiles?TheBareConductiveTouchBoard(www.bareconductive.com/shop/touch-board/)doesthatallonasingleboard!
ShieldsAshieldisasolderedcircuitthatfitsperfectlyontopofyourArduinoUnoboard.ItcanholdsomecomplicatedcircuitrylikeanArduinoEthernetShield(http://arduino.cc/en/Main/ArduinoEthernetShield)thatletsyouconnectyourArduinototheInternetwithanEthernetcable.Thereareshieldsthataddtouchscreens,MP3players,motorcontrolandmuchmore.Visityourfavouritestore—whetherinpersonoronline—andseewhat’savailable.
SensorsandActuatorsTherearealsomanymoresensorsavailablethanyou’veusedfortheadventuresinthisbook.Justaboutanythingyoucansense,youcangetyourArduinotosenseaswell.Wanttodetectthebarometricpressure?TrytheBMP180(www.adafruit.com/products/1603).Howaboutsound?TryanelectretmicrophonefromSparkFun(https://www.sparkfun.com/products/9964).
Thesamegoesforactuators.Therearemanytypesofmotorandspeakerand,ofcourse,thereisahugeselectionofLEDsandscreens.TheAdafruitNeoPixelisagreatRGBLEDthatyoucancontrolwithanArduino(www.adafruit.com/category/168).
Ofcourse,analternativetobuyingmoresensorsistomakeyourown!Kobakant’sHowtoGetWhatYouWant(http://kobakant.at/DIY)isacollectionofguidesanddocumentationonDIYsensors,oftenusingmaterialslikeconductivethreadandfabric.
OntheWebThewebisfullofprojectsandresources.Onlyafewofthemostpopularonesarelistedhere,sosearcharoundformore!
TheArduinoSiteThefirststopforanyaspiringArduinoengineeristheArduinowebsite(http://arduino.cc).YouwillfindeverythingyouneedtoknowabouteveryofficialArduinoboardthatismade—andtherearealotofthem.It’salsothehomeoftheArduinoplayground(http://playground.arduino.cc)whereArduinouserscanuploadtheirownprojectsandtutorials.
Ifyouhaveanyquestionsorproblemstryingtobringaprojecttolife,youcanaskaquestionontheArduinoForum(http://forum.arduino.cc).Therearealwaysfriendlyfolkwillingtohelp,butit’sgoodtodoacoupleofthingsbeforeaskingaquestion.First,makesureit’snotaquestionthathasalreadybeenasked.Searcharoundtheforums—maybesomeoneelsehasalreadyprovidedalltheinformationyouneed.Second,giveasmanydetailsasyoucan.Describewhatyouhavetriedtodo,whatyouwanttohappenandexactlywhatisactuallyhappening.Thismakesitmucheasierforotherstohelpyouandmorelikelythattheywillreply.
ManufacturersOtherthantheArduinowebsite,thebestresourcesaretwocompaniesthatbuildtheirownsensors,actuatorsandkitsfortheArduino:SparkFunandAdafruit.Bothhaveexcellentsitesfulloftutorialsandguides.Adafruitisathttps://learn.adafruit.comandSparkFunisathttps://learn.sparkfun.com.
BlogsIfyouareinneedofsomeinspirationforyournextproject,tryoutAdafruit’sblog(http://adafruit.com/blog),MakeMagazine(http://makezine.com)orHackaday(http://hackaday.com).Therearelotsofspecialistblogsaswell.Forexample,ifyouareintowearabletechnology,keepyoureyeonFashioningTechnology(http://fashioningtech.com).WanttotakeyourArduinototheskies?DIYDrones(http://diydrones.com/)canhelpyouwiththat.
VideosSometimesnothingbeatsseeingavideodemonstrationofanewskill.YouTubechannelsareagreatwaytolearnaboutanewsensororhowtomakeanewproject.Youwon’tbesurprisedtolearnthatbothAdafruit(https://www.youtube.com/user/adafruit)andSparkFun(https://www.youtube.com/user/sparkfun)haveYouTubechannelsoverflowingwithinformation.MakeMagazinehasoneaswell(https://www.youtube.com/user/makemagazine).
Foranexcellentseriesofelectronicsvideos,searchYouTubefor“Collin’sLab”.CollinCunninghamteachesbasicelectronicsinawaythat’seasytofollow.SomeofthevideosaremadewithMakeMagazineandothersarefromAdafruit,sojustsearchfor“Collin’sLab”.
MassimoBanzi,oneofthefoundersofArduino,madeaseriesofvideosthataccompaniestheofficialArduinoStarterKit.Thevideoshaveaprojectbook,butyoucanonlygetitbybuyingthekit.Thefirstvideoisathttps://www.youtube.com/watch?v=2X8d_r0p92U.
BooksPhysicalbooksaregreattohaveonhandforreference.Therearealotofthemoutthereandmorearebeingwrittenaboutthelatesttechnologyallthetime,buthereareafewtogetyoustarted.
GettingStartedwithArduinoandGeneralProjectsTherearefarmoreprojectsyoucanmakewithanArduinothanyouhavemadewiththisbook.Gooutandmakeevenmoreprojects!Buildmorethings!
GettingStartedwithArduinobyMassimoBanzi(MakerMedia,Inc.,2011)ArduinoForDummiesbyJohnNussey(Wiley,2013)ArduinoProjectsForDummiesbyBrockCraft(Wiley,2013)ExploringArduino:ToolsandTechniquesforEngineeringWizardrybyJeremyBlum(Wiley,2013)
GeneralElectronicsElectricalcircuitsincludemuchmorethanjustArduinos.Ifyouwouldliketostartmakingreallyadvancedprojects,it’sagoodideatolearnmoreaboutcircuits.Thesebookscangetyougoing:
Make:ElectronicsbyCharlesPlatt(Make,2009)PracticalElectronicsforInventorsbyPaulScherzandSimonMonk(TabBooks,2013)
SoftCircuitsandWearablesElectronicsandcraftingtechniqueslikesewingactuallygotogetherreallywell.Ifyou’reinterestedinexploringthisperfectmatch,herearesomegreatbookstogetyoustarted:
FashioningTechnologybySyuziPakhchyan(MakerMedia,Inc.,2008)SwitchCraft:Battery-PoweredCraftstoMakeandSewbyAlisonLewisandFang-YuLin(PotterCraft,2008)SewElectricbyLeahBuechley,KanjunQi,andSonjadeBoer(HLTPress,2013)Make:WearableElectronicsbyKateHartman(MakerMedia,Inc.,2014)
OtherSpecialisedTopicsOfcourse,therearesomanymorethingsthatArduinoscando.HowaboutinvestigatingArduinorobotsorArduinosthatcantalktotheInternet?
MakingThingsMove:DIYMechanismsforInventors,Hobbyists,andArtistsbyDustynRoberts(McGraw-Hill,2011)MakingThingsTalk:UsingSensors,Networks,andArduinotoSee,Hear,andFeelYourWorldbyTomIgoe(MakerMedia,Inc.,2011)
NAVIGATINGYOURWAYthroughtheworldoftoolsandelectricalcomponentscanbedifficult,butluckilythegrowthofdo-it-yourselfelectronicsandcodingprojectshasmadeiteasierthaneverbeforetofindwhatyouneedforyourArduinoproject.
StarterKitsAreallyeasywaytogetgoingwiththeadventuresinthisbookistobuyastarterkit.AstarterkitwillincludeanArduinoUnoandalmostallthecomponentsyouneedlikeLEDs,resistorsandaservo.YoucancomparethelistofcomponentsyouneedintheIntroductionwithwhatisavailableinastarterkitandthenbuywhateverisn’tincluded.YouwillstillneedtobuyanArduinoLeonardoandLilypadArduinoUSBseparatelytocompleteAdventures7and8
Almostallthestoreslistedinthisappendixselltheirownstarterkits,sotherearelotsofoptions.TheArduinocompanymakesitsownstarterkitthatcomeswithawholebookofprojects.YoucanbuyitfromaresellerordirectlyfromtheArduinoshoponline(http://store.arduino.cc/product/K000007).
Brick-and-MortarStoresAbrick-and-mortarstoresimplymeansashop!Beingabletowalkintoastoretofindthecomponentsyouneedhassomebenefits.Forexample,whenworkingwithphysicalcomponents,it’salwaysusefultobeabletopickthemupandseethemforyourself.Youcanalsoaskquestionsfromthehelpfulstaffinthestore.Plus,youdon’thavetowaitforyourpackagetobedelivered;youcangohomeandgetmakingrightaway!
IntheUKMaplin(www.maplin.co.uk)sellsallsortsofthingsandhasawiderangeofstock;youcannowbuyArduinosthere,alongwithelectricalcomponents.MostofthesmallercomponentslikeresistorsandLEDsarekeptbehindthecounter,soyoucanlookuptheproductcodeinacatalogueorin-storecomputerandamemberofstaffwillgetitforyou.Theyalsostockusefultoolslikesolderingirons.
IntheUSRadioShack(www.radioshack.com)hadlongbeentheplaceforhobbyistelectronics.Thechainfiledforbankruptcyin2015,leavingthoseintheUnitedStateswithoutaphysicalstoretovisit.Thereisn’tyetachainaslargeasRadioShacktotakeitsplace,butspaceslikeTechShop(http://techshop.ws/)arebecomingmorewidespreadandcontainshopssellingelectronics.
OnlineStoresTherearebroadlytwodifferentkindsofonlinestoreforelectricalcomponents:friendlyhobbyistorspecialistsites;andvastcataloguesites.Ifyouarejuststartingout,it’sbettertostickwithafriendlysitethatdoesn’tstocksomanydifferentoptionsbutdoesstockwhatyouwillmostlikelyneed.
Thebiggersiteshavethousands,ifnotmillions,ofcomponentssocanbedifficulttonavigateifyoudon’tknowexactlywhatyouarelookingfor.However,theytendtobecheaperthanotheronlinestoresandalsostocklesspopularitemsthatarehardertofind.
OnlineStoresShippingfromtheEUAdafruitandSparkfunarethebestsitesforreference,butyoumightnotwanttodealwithinternationalshippingifyoudon’tliveinNorthAmerica.LuckilytherearealargenumberofEUdistributorsthatimportAdafruitandSparkfunproducts.Thatmeansyoucangetmakingfaster!Trysomeofthesesitestoseeiftheyhavewhatyouneed:
ArduinoStore:http://store.arduino.ccCoolComponents:www.coolcomponents.co.ukMaplin:www.maplin.co.ukOomlout:http://oomlout.comPimoroni:http://shop.pimoroni.comProto-Pic:http://proto-pic.co.ukRobotShop:www.robotshop.com/eu/enSKPang:http://skpang.co.uk
SomebigcataloguesitesthatservetheEUincludethefollowing:
Digi-Key:www.digikey.co.ukFarnell:www.farnell.comMouser:http://uk.mouser.comRapid:www.rapidonline.comRSComponents:www.rs-components.com/index.html
OnlineStoresShippingfromtheUSorCanadaThetwomaker-focusedsitesthatallothermakercompaniesaspiretobeareAdafruit(www.adafruit.com)andSparkfun(https://www.sparkfun.com).Bothhaveexcellentguidesandtutorialsforhowtouseeverythingtheysell.Alotoftheirstockoverlaps,buteachcompanyalsomakestheirownproducts.Thesesitesshouldalwaysbeyourfirststoponline.TheyarebothlocatedintheUS,soreadontothenextsectionifyouarenotinNorthAmericaanddon’twanttowait(orpay)foryourordertoarrivefromfaraway.
YoucanalsocheckouttheseothersmalleronlinesitesthatarealsointheUS:
MakerShed:www.makershed.comRobotShop:www.robotshop.comSpinkenzieLabs:www.spikenzielabs.com
IfyouwanttotryoneofthelargecataloguesitesbasedintheUS,checkoutsomeofthese:
AlliedElectronics:http://ex-en.alliedelec.comDigi-Key:www.digikey.comJameco:www.jameco.comMouser:www.mouser.comNewark:www.newark.com
actuatorAdevicethattranslatesanelectricalsignalintoareal-worldactionsuchaslight,soundormovement.Examplesincludemotors,lightsandspeakers.
alligatorclipsWireswithspring-loadedclipsthatresemblethejawsofanalligator.Theyareusefulforprototypingsoftcircuitsorconnectingcomponentsthatdon’tusejumperwires.
analogueAsignalthatvariesbetweenLOWandHIGH,asopposedtoadigitalsignal.OntheArduinoUno,ananaloguesignalcanbemeasuredasanumberbetween0forgroundand1023for5V.Ananaloguesignalcanbeoutputasavaluebetween0for0Vand255for5V.
anodeThepositivelegofadirectionalcomponent,suchasthelonglegofanLED.
argumentApieceofinformationgiventoafunction,whichthefunctionthenusestoperformitstask.Theargumentgoesinsidethebracketsthatfollowthefunctionname.Forexample,thefunctiondelay(1000)hastheargument1000,whichisthenumberofmillisecondsyouwanttheArduinotowaitbeforeexecutingthenextline.
arrayAlistofthesametypeofthingincode.Forexample,anarraycanholdalistofints.
binaryAnumberthatusesonlythedigits0and1,asopposedtodecimal,whichusesthedigits0to9.Binaryisalsoknownasbase-2.Decimalisreferredtoasbase-10.
breadboard
Areusabledevicethatallowsyoutocreatecircuitswithoutneedingtosolderallthecomponents.Breadboardshaveanumberofholesintowhichyoupushwiresandcomponentstocreatecircuits.
capacitanceTheabilitytostoreanelectricalcharge.Electricalcomponentsbuiltespeciallytoholdachargearecalledcapacitors,butotherobjects—evenpeople—alsohavecapacitance.
cathodeThenegativelegofadirectionalcomponent,suchastheshortlegofanLED.
commentsNoteswithinyourcodethatexplainwhatalineorsectionofcodeisintendedtodo.Eachcommentlinebeginswith//or,ifyouwanttowriteacommentthatspansmultiplelines,itisplacedbetween/*and*/.Thesespecialcharacterstellthecomputerrunningtheprogramtoignorethatlineorlines.
compilingTheprocessoftakingcodewrittenbyahumanandturningitintoinstructionsthatcanbeunderstoodbyamachine.
currentTherateatwhichelectricalenergyflowspastapointinacircuit.Itistheelectricalequivalentoftheflowrateofwaterinpipes.Currentismeasuredinamperes(A).Smallercurrentsaremeasuredinmilliamperes(mA).
debuggingTheprocessoflocatingthecauseofanyerrorsinyourcomputerprogramcodeandfixingthem.
declaringWhereanewvariableiscreatedbygivingitanameandadatatypesuchasint.Thevariabledoesnotholdavalueuntilitisgivenitsfirstvalue.
digitalAsignalthatisonlyeitheronoroff,orHIGHorLOW.OntheArduinoUno,aHIGHsignalis5VandaLOWsignalisground.
directcurrent(DC)ThetypeofelectricityusedinArduinocircuits.It’sthesamekindthatis
generatedbyabatteryandistheoppositeofalternatingcurrent(AC),whichiswhatcomesoutofmainsplugsinthewall.
driverApieceofsoftwarethatletsyourcomputercommunicatewithanexternaldevice,suchasaprinterorakeyboard.
dualin-linepackage(DIPorDIL)OnepossibleshapeofanICchip.Ithastworowsoflegsthatcanfitintoabreadboard.
dutycycleTheratiooftimeasignalisHIGHversusLOWinagivencycle.InPWM,thehigherthedutycycle,thehighertheoutputvoltage.
floatAdatatypefornumbersthataren’twholenumbers,butincludeadecimalplacesuchas1.3or–54.089.
floatinginputApinthatisnotconnectedtoanything.Thepinreadsinrandomvaluesifitisnotconnectedtoavoltagesourcesuchasground,5Vorasensor.
forloopAprogrammingdevicethatrepeatsablockofcodeforapredeterminednumberoftimes.
functionAsetoflinesofcodethathaveaname.Afunctioncanbeusedoverandoveragain.Itmaytakesomeinformationasaninputandoutputmoreinformationwhenitisfinished,butnotallfunctionsneedtodothat.
instantiationGivingavariableavalueforthefirsttime.Instantiationcanhappenatthesametimeyoudeclarethevariableoryoucandoitlater,butthedeclarationalwaysneedstocomefirst.
integratedcircuit(IC)Circuitscontainedwithinasinglechip.Thesamecircuitcanbeputintodifferentshapedchips,calledpackages.Whenworkingwithabreadboard,youneedwhatisknownaDIPorDILpackage.That’stheshapethathaslegsthatfitintoabreadboard.
integrateddevelopmentenvironment(IDE)Asoftwareapplicationthatisusedtowritecomputercodeinaparticular
language;it’salsoreferredtoasaprogrammingenvironment.Theapplicationcancreateandeditcode,aswellasrun(orexecute)thecode.ManyIDEsalsoprovidefeaturestohelpprogrammersdebugtheirprograms—inotherwords,checktheirprogramsforerrors.
light-emittingdiode(LED)Anelectricalcomponentthatlightsupwhenelectricalcurrentflowsthroughit.Adiodeonlyletselectricityflowinonedirection,soanLEDlightsuponlywhenthelonglegisconnectedtothepositivesideofapowersourceandtheshortlegisconnectedtothenegativeside.Ifthelegsareswitched,theLEDwon’tlightup.
libraryAcollectionofreusablefunctionsincodethatcanbeimportedandusedinmultiplesketches.
light-dependentresistorAresistorthatchangesitsresistanceaccordingtohowmuchlightitisexposedto.Itisalsosometimescalledaphotoresistor.
longAdatatypethatcanholdwholeintegernumbersfrom–2,147,483,648to2,147,483,647.
newlinecharacterAcharacterthatrepresentswhathappenswhenyoupresstheEnterorReturnkeyonyourkeyboard.
Ohm’sLawThemathematicalrelationshipbetweenvoltage,currentandresistance.Voltageequalscurrentmultipliedbytheresistance—or,putanotherway,V=IR.
panelmountpushbuttonApushbuttonthatisdesignedtobemountedinsideacase.Itcomeswithanutandwashertosecureittoapanel.
piezoAcrystalthatexpandsandshrinkswhenelectricityisrunthroughit.Italsogenerateselectricitywhenitissqueezedorbent.
potentiometerAtypeofresistorwithanadjustableknobtovarytheresistanceofcurrent.
pull-upresistor
Aresistorthatisconnectedtothehighvoltageinacircuit,whichsetsthedefaultstateofthepinonthatcircuittoHIGH.Theresistorisusually10kΩ.
pulsewidthmodulation(PWM)HowtheArduinoboardgeneratesanoutputsignalbetween0Vand5V.ThesignalswitchesquicklybetweenLOWandHIGHandtheresultingoutputvoltageisbetweenthetwovoltages.
red-green-bluelight-emittingdiode(RGBLED)AsingleLEDwithfourlegsthatcontainsthreelights:onered,onegreenandoneblue.Thethreelightsshareeitheracommonanodeoracommoncathode.
resistorAnelectricalcomponentthatresistscurrentinacircuit.Forexample,LEDscanbedamagedbytoomuchcurrent,butifyouaddaresistorwiththecorrectvaluetotheLEDcircuittolimittheamountofcurrent,theLEDisprotected.ResistanceismeasuredinohmsorΩ.Youneedtopickaresistorwiththecorrectvaluetolimitthecurrentthroughacircuit;thevalueofaresistorisshownbycolouredbandsthatarereadfromlefttoright.
sensorAdevicethatdetectssomethingintherealworldsuchaslight,soundormovementandtranslatesitintoanelectricalsignal.Examplesincludepotentiometersandlight-dependentresistors.
serialcommunicationAwaythattwodevices,suchasacomputerandanArduinoboard,cansendandreceivedatatoeachother.Onepieceofdataissentatatime.
servoAmotorthatcanbecontrolledtorotatetoaspecificposition.Itusuallycan’trotatemorethan180degrees.
shiftregisterAdevicethatcancontrolmultipleoutputswithrelativelyfewinputs.ItiscommonlyusedtocontrolalargenumberofLEDs.
sketchesArduinoprograms.Thenamecomesfromthequickdrawingsartistsmake.
softcircuit:Circuitbuiltwithflexiblematerialssuchasconductivethreadandfabric.Softcircuitsareoftenusedinprojectsthataregoingtobeworn.
surface-mountdevice(SMD)OnepossibleshapeofanICchiporothercomponentsuchasaresistor.Itismadeforsolderingontoaflatsurfacewithoutanylegsbeinginsertedintoholesonacircuitboard.
switchAcomponentthateitherdisruptsorredirectstheflowofcurrentinacircuit.
tactilepushbuttonAtypeofswitch.Apush-to-breakpushbuttoninterruptstheflowofcurrentinacircuitwhenitispressed.Apush-to-makepushbuttondoestheoppositeandinterruptscurrentonlywhenitisnotpressed.
two-dimensionalarrayDatastoredinrowsandcolumns,likeinaspreadsheet.
variableAcodeconstructthatholdsavaluethatcanbechanged.Forexample,thevariablegreenLEDstoresthenumber5.
voltageThedifferenceinelectricalenergybetweentwopointsinacircuit.Itistheelectricalequivalentofwaterpressureinpipes,anditisthispressurethatcausesacurrenttoflowthroughacircuit.Voltageismeasuredinvolts(V).
voltagedividerAcircuitthatoutputsafractionoftheinputvoltage.Itisausefulcircuitfortranslatingachangeinresistanceintoachangeinvoltage.
WILEYENDUSERLICENSEAGREEMENTGotowww.wiley.com/go/eulatoaccessWiley’sebookEULA.