-
CHAPTER 3
LED ProjectsINTHISCHAPTERWEAREGOINGTOstartbuildingsomeLEDbasedprojects.WewillkeepthehardwarefairlysimplesothatwecanconcentrateontheprogrammingoftheArduino.
Programmingmicrocontrollerscanbeatrickybusinessrequiringanintimateknowledgeoftheinnerworkingsofthedevice:fuses,registers,etc.Thisisdue,inpart,tothefactthatmodernmicrocontrollersarealmostinfinitelyconfigurable.Arduinostandardizesitshardwareconfiguration,which,inreturnforasmalllossofflexibility,makesthedevicesagreatdealeasiertoprogram.
Project 2Morse Code S.O.S. FlasherMorsecodeusedtobeavitalmethodofcommunicationinthe19thand20thcenturies.Itscodingoflettersasaseriesoflongandshortdotsmeantthatitcouldbesentovertelegraphwires,overaradiolink,andusingsignalinglights.ThelettersS.O.S.(SaveOurSouls)arestillrecognizedasaninternationalsignalofdistress.
Inthisproject,wewillmakeourLEDflashthesequenceS.O.S.overandoveragain.
ForthisprojectyouwillneedjustthesamecomponentsasforProject1.
COMPONENTSANDEQUIPMENT
Hardware
ThehardwareisexactlythesameasforProject1.SoyoucaneitherjustplugtheresistorandLEDdirectlyintotheArduinoconnectorsoruseabreadboard(seeChapter1).
Software
Ratherthanstarttypingthisprojectinfromscratch,wewilluseProject1asastartingpoint.SopleasecompleteProject1beforeyoubeginthisproject.
Ifyouhavenotalreadydoneso,downloadtheprojectcodefromwww.arduinoevilgenius.com(http://www.arduinoevilgenius.com)thenyoucanalsojustloadthecompletedsketchforProject1fromyourArduinoSketchbookanddownloadittotheboard(seeChapter1).However,itwillhelpyoutounderstandArduinobetterifyoumodifythesketchfrom
PREV2 A Tour of Arduino
NEXT4 More LED Projects
30 Arduino Projects for the Evil Genius: Second Edition Recent
Topics
Tutorials
Highlights
Settings
Feedback(http://community.safaribooksonline.com)
Sign Out
Settings
10 days left in your trial. Subscribe.
Feedback(http://community.safaribooksonline.com/)
Sign Out
-
Project1assuggestednext.
ModifytheloopfunctionofProject1sothatitnowappearsasshownhere.Notethatcopyandpastearehighlyrecommendedinthiskindofsituation.
Thiswouldallwork,andfeelfreetotryithowever,wearenotgoingtoleaveitthere.Wearegoingtoalteroursketchtoimproveitandatthesametimemakeitalotshorter.
WecanreducethesizeofthesketchbycreatingourownfunctiontoreplacethefourlinesofcodeinvolvedinanyflashoftheLEDwithoneline.
Aftertheloopfunctionsfinalcurlybrace,addthefollowingcode:
-
Nowmodifytheloopfunctionsothatitlookslikethis:
ThewholefinallistingisshowninListingProject2.
LISTINGPROJECT2
Thismakesthesketchalotsmallerandaloteasiertoread.
Putting It All Together
ThatconcludesProject2.WewillnowcoversomemorebackgroundonprogrammingtheArduinobeforewegoontolookatProject3,wherewewilluseoursamehardwaretowriteaMorsecodetranslator,withwhichwecantypesentencesonourcomputerandhavethemflashedasMorsecode.InProject4wewillimprovethebrightnessofourflashingbyreplacingourredLEDwithahighpowerLuxeontypeLED.
ButfirstweneedalittlemoretheoryinordertounderstandProjects3and4.
LoopsLoopsallowustorepeatagroupofcommandsacertainnumberoftimesoruntilsomeconditionismet.InProject2,weonlywanttoflashthreedotsforanS,soitisnogreathardshiptorepeattheflashcommandthreetimes.However,itwouldbefarlessconvenientifweneededtoflashtheLED100or1000times.InthatcasewecanusetheforlanguagecommandinC:
Enjoy Safari? Subscribe Today
You have 10 daysleft in your trial,
M.bog.Safari is your trusted guide for building aremarkable career. We hope you've been
enjoying your trialready to join?
Subscribe Today
/ Contact Us(http://safaribooksonline.com/contact/) /Blog(http://blog.safaribooksonline.com) 2015 Safari(http://www.safaribooksonline.com) Terms of Service /
Membership Agreement / Privacy Policy
-
Theforloopisabitlikeafunctionthattakesthreearguments,althoughherethoseargumentsareseparatedbysemicolonsratherthanbytheusualcommas.ThisisjustaquirkoftheClanguage.Thecompilerwillsoontellyouwhenyougetitwrong.
Thefirstthingintheparenthesesafterforisavariabledeclaration.Thisspecifiesavariabletobeusedasacountervariableandgivesitaninitialvalueinthiscase0.
Thesecondpartisaconditionthatmustbetrueforustostayintheloop.Inthiscasewewillstayintheloopaslongasiislessthan100,butassoonasiis100ormore,wewillstopdoingthethingsinsidetheloop.
Thefinalpartiswhattodoeverytimeyouhavedoneallthethingsintheloop.Inthiscase,thatisincrementiby1sothatitcan,after100tripsaroundtheloop,ceasetobelessthan100andcausethelooptoexit.
AnotherwayofloopinginCistousethewhilecommand.Thesameexampleshownpreviouslycouldbeaccomplishedusingawhilecommand,asshownhere:
Theexpressioninparenthesesafterthewhilemustbetruetostayintheloop.Whenitisnolongertrue,thesketchwillcontinuerunningthecommandsafterthefinalcurlybrace.
Thecurlybracesareusedtobrackettogetheragroupofcommands.Inprogrammingparlance,theyareknownasablock.
ArraysArraysareawayofcontainingalistofvalues.Thevariableswehavemetsofarhaveonlycontainedasinglevalue,usuallyanint.Bycontrast,anarraycontainsalistofvalues,andyoucanaccessanyoneofthosevaluesbyitspositioninthelist.
C,likethemajorityofprogramminglanguages,beginsitsindexpositionsat0ratherthan1.Thismeansthatthefirstelementisactuallyelementzero.
Toillustratetheuseofarrays,wecouldchangeourMorsecodeexampletouseanarrayofflashdurations.Wecanthenuseaforlooptostepthrougheachoftheitemsinthearray.
Firstletscreateanarrayoftypeintcontainingthedurations:
Youindicatethatavariablecontainsanarraybyplacing[]afterthevariablename.Ifyouaresettingthecontentsofthearrayatthesametimeyouaredefiningit,asintheprecedingexample,youdonotneedtospecifythesizeofthearray.Ifyouarenotsettingitsinitialcontents,thenyouneedtospecifythesizeofthearrayinsidethesquarebrackets.Forexample:
Nowwecanmodifyourloopmethodtousethearray:
-
Anobviousadvantageofthisapproachisthatitiseasytochangethemessagebysimplyalteringthedurationsarray.InProject3wewilltaketheuseofarraysastagefurthertomakeamoregeneralpurposeMorsecodeflasher.
Project 3Morse Code TranslatorInthisprojectwearegoingtousethesamehardwareasforProjects1and2,butwearegoingtowriteanewsketchthatwillletustypeinasentenceonourcomputerandhaveourArduinoboardconvertthatintotheappropriateMorsecodedotsanddashes.
Figure31showstheMorsecodetranslatorinaction.ThecontentsofthemessageboxarebeingflashedasdotsanddashesontheLED.
Figure31 Morsecodetranslator.
Todothis,wewillmakeuseofwhatwehavelearnedaboutarraysandstringsandalsolearnsomethingaboutsendingmessagesfromourcomputertotheArduinoboardthroughtheUSBcable.
Forthisproject,youwillneedjustthesamecomponentsasforProjects1and2.Infact,thehardwareisexactlythesamewearejustgoingtomodifythesketchofProject1.
COMPONENTSANDEQUIPMENT
Hardware
PleasereferbacktoProject1forthehardwareconstructionforthisproject.
YoucaneitherjustplugtheresistorandLEDdirectlyintotheArduinoconnectorsorusethebreadboard(seeChapter1).YoucanevenjustchangetheledPinvariableinthesketchtobepin13sothatyouusethebuiltinLEDanddonotneedanyexternalcomponentsatall.
Software
-
ThelettersinMorsecodeareshowninTable31.
TABLE31MorseCodeLetters
SomeoftherulesofMorsecodearethatadashisthreetimesaslongasadot,thetimebetweeneachdashordotisequaltothedurationofadot,thespacebetweentwolettersisthesamelengthasadash,andthespacebetweentwowordsisthesamedurationassevendots.
Forthesakeofthisproject,wewillnotworryaboutpunctuation,althoughitwouldbeaninterestingexerciseforyoutotryaddingthistothesketch.ForafulllistofalltheMorsecharacters,seehttp://en.wikipedia.org/wiki/Morse_code.
ThesketchforthisisshowninListingProject3.Anexplanationofhowitallworksfollows.
LISTINGPROJECT3
-
Wekeeptrackofourdotsanddashesusingarraysofstrings.Wehavetwoofthese,oneforlettersandonefornumerals.So,tofindoutwhatweneedtoflashforthefirstletterofthealphabet(A),wewillgetthestringletters[0]remember,thefirstelementofanarrayiselement0,notelement1.
ThevariabledotDelayisdefined,soifwewanttomakeourMorsecodeflashfasterorslower,wecanchangethisvaluebecauseallthedurationsaredefinedasmultiplesofthetimeforadot.
Thesetupfunctionismuchthesameasforourearlierprojectshowever,thistimewearegettingcommunicationsfromtheUSBport,sowemustaddthecommand
ThistellstheArduinoboardtosetthecommunicationsspeedthroughtheUSBtobe9600baud.Thisisnotveryfast,butfastenoughforourMorsecodemessages.ItisalsoagoodspeedtosetittobecausethatisthedefaultspeedusedbytheArduinosoftwareonyourcomputer.
IntheloopfunctionwearegoingtorepeatedlyseeifwehavebeensentanylettersovertheUSBconnectionandifwehavetoprocesstheletter.TheArduinofunctionSerial.available()willbetrueifthereisacharactertobeturnedintoMorsecode,andtheSerial.read()functionwillgiveusthatcharacter,whichweassigntoavariablecalledchthatwedefinedjustinsidetheloop.
Wethenhaveaseriesofifstatementsthatdeterminewhetherthecharacterisanuppercaseletter,alowercaseletter,oraspacecharacterseparatingtwowords.Lookingatthefirstifstatement,wearetestingtoseeifthecharactersvalueisgreaterthanorequaltoaandlessthanorequaltoz.Ifthatisthecase,wecanfindthesequenceofdashesanddotstoflashusingthelettersarraythatwedefinedatthetopofthesketch.Wedeterminewhichsequencefromthearraytousebysubtractingafromthe
-
characterinch.
Atfirstsight,itmightlookstrangetobesubtractingoneletterfromanother,butitisperfectlyacceptabletodothisinC.So,forexample,aais0,whereasdawillgiveustheanswer3.So,iftheletterthatwereadfromtheUSBconnectionsweref,wewouldcalculatefa,whichgivesus5asthepositionofthelettersarray.Lookingupletters[5]willgiveusthestring....andwepassthisstringtoafunctioncalledflashSequence.
TheflashSequencefunctionisgoingtoloopovereachofthepartsofthesequenceandflashitaseitheradashoradot.StringsinCallhaveaspecialcodeontheendofthemthatmarkstheendofthestring,andthisiscalledNULL.SothefirstthingflashSequencedoesistodefineavariablecalledi.Thisisgoingtoindicatethecurrentpositioninthestringofdotsanddashes,startingatposition0.ThewhileloopwillkeepgoinguntilwereachtheNULLontheendofthestring.
Insidethewhileloop,wefirstflashthecurrentdotordashusingafunctionthatwearegoingtodiscussinamomentandthenadd1toiandgobackroundtheloopflashingeachdotordashinturnuntilwereachtheendofthestring.
ThefinalfunctionthatwehavedefinedisflashDotOrDashthisjustturnstheLEDonandthenusesanifstatementtoeitherdelayforthedurationofasingledotifthecharacterisadotorforthreetimesthatdurationifthecharacterisadashbeforeitturnstheLEDoffagain.
Putting It All Together
LoadthecompletedsketchforProject3fromyourArduinoSketchbookanddownloaditontoyourboard(seeChapter1).
TousetheMorsecodetranslator,weneedtouseapartoftheArduinosoftwarecalledtheSerialMonitor.ThiswindowallowsyoutotypemessagesthataresenttotheArduinoboardaswellasseeanymessagesthattheArduinoboardchoosestoreplywith.
TheSerialMonitorislaunchedbyclickingtherightmosticonshownhighlightedinFigure32.
Figure32 LaunchingtheSerialMonitor.
TheSerialMonitor(seeFigure33)hastwoparts.Atthetop,thereisafieldintowhichalineoftextcanbetypedthatwillbesenttotheboardwhenyoueitherclickSendorpressRETURN.
Figure33 TheSerialMonitorwindow.
BelowthatisalargerareainwhichanymessagescomingfromtheArduinoboardwillbedisplayed.Rightatthebottomofthewindowisadropdownlistwhereyoucanselectthespeedatwhichthedataissent.Whateveryouselectheremustmatchthebaudratethatyouspecifyinyourscriptsstartupmessage.Weuse9600,whichisthedefault,sothereisnoneedtochangeanythinghere.
SoallweneedtodoislaunchtheSerialMonitor,typesometextintotheSendfield,andclicktheSendbuttonorpressRETURN.WeshouldthenhaveourmessageflashedtousinMorsecode.
Project 4
-
High-Brightness Morse Code TranslatorThelittleLEDonProject3isunlikelytobevisiblefromtheshiponthehorizonbeingluredbyourbogusEvilGeniusdistressmessage.So,inthisproject,wearegoingtoupthepowerandusea1WLuxeonLED.TheseLEDsareextremelybright,andallthelightcomesfromatinylittleareainthecenter,sotoavoidanypossibilityofretinadamage,donotstaredirectlyintoit.
Wealsolookathow,withabitofsoldering,wecanmakethisprojectintoashieldthatcanbepluggedintoourArduinoboard.
COMPONENTSANDEQUIPMENT
HardwareTheLEDweusedinProject3usedabout10mAat2V.Wecanusethistocalculatepowerusingtheformula
P=IV
Powerequalsthevoltageacrosssomethingtimesthecurrentflowingthroughit,andtheunitofpoweristhewatt.SothatLEDwouldbeapproximately20mW,orafiftiethofthepowerofour1WLuxeonLED.WhileanArduinowillcopejustfinedrivinga20mWLED,itwillnotbeabletodirectlydrivethe1WLED.
Thisisacommonprobleminelectronicsandcanbesummedupasgettingasmallcurrenttocontrolabiggercurrent,somethingthatisknownasamplification.Themostcommonlyusedelectroniccomponentforamplificationisthetransistor,sothatiswhatwewillusetoswitchourLuxeonLEDonandoff.
ThebasicoperationofatransistorisshowninFigure34.Therearemanydifferenttypesoftransistors,andprobablythemostcommonandthetypethatwearegoingtouseiscalledanNPNbipolartransistor.
Figure34 TheoperationofanNPNbipolartransistor.
Thistransistorhasthreeleads:theemitter,thecollector,andthebase.Andthebasicprincipleisthatasmallcurrentflowingthroughthebasewillallowamuchbiggercurrenttoflowbetweenthecollectorandtheemitter.
Justhowmuchbiggerthecurrentisdependsonthetransistor,butitistypicallyafactorof100.Soacurrentof10mAflowingthroughthebasecouldcauseupto1Atoflowthroughthecollector.So,ifwekeptthe270resistorthatweusedtodrivetheLEDat10mA,wecouldexpectittobemorethanenoughtoallowthetransistortoswitchthehundredsofmilliampsneededbytheLuxeonLED.
TheschematicdiagramforourcontrolcircuitisshowninFigure35.
-
Figure35 SchematicdiagramforhighpowerLEDdriving.
The270resistor(R1)limitsthecurrentthatflowsthroughthebase.WecancalculatethecurrentusingtheformulaI=V/R.Vwillbe4.4Vratherthan5Vbecausetransistorsnormallyhaveavoltageof0.6Vbetweenthebaseandemitter,andthehighestvoltagetheArduinocansupplyfromanoutputpinis5V.Sothecurrentwillbe4.4/270=16mA.
ThedatasheetforthisLEDstatesthattheabsolutemaximumforwardcurrentis350mA,andtheforwardvoltageis3.4V.Sowewillaimforaround200mA,whichwillmaketheLEDgoodandbrightwithoutshorteningitslife.
R2limitsthecurrentflowingthroughtheLEDtoaround200mA.Wecameupwiththefigureof4.7byusingtheformulaR=V/I.Vwillberoughly53.40.6=1.0V.5Visthesupplyvoltage,theLEDdropsroughly3.4Vandthetransistor0.6V,sotheresistanceshouldbe1.0V/200mA=5.Resistorscomeinstandardvalues,sowewillselecta4.7resistor.Wemustalsousearesistorthatcancopewiththisrelativelyhighcurrent.Thepowerthattheresistorwillburnoffasheatisequaltothevoltageacrossitmultipliedbythecurrentflowingthroughit.Inthiscase,thatis200mA1.0V,whichis200mW.Thismeansthataregular0.5Woreven0.25Wresistorwillbejustfine.
Inthesameway,whenchoosingatransistor,weneedtomakesurethatitcanhandlethepower.Whenitisturnedon,thetransistorwillconsumepowerequaltocurrenttimesvoltage.Inthiscase,thebasecurrentissmallenoughtoignore,sothepowerwilljustbe0.6V200mA,or120mW.Itisalwaysagoodideatopickatransistorthatcaneasilycopewiththepower.Inthiscase,wearegoingtouseaBD139,whichhasapowerratingofover12W.InChapter10youcanfindatableofcommonlyusedtransistors.
NowweneedtoputourcomponentsintothebreadboardaccordingtothelayoutshowninFigure36,withthecorrespondingphotographofFigure38.ItiscrucialtocorrectlyidentifytheleadsofthetransistorandtheLED.Themetallicsideofthetransistorshouldbefacingtheboard.TheLEDwillhavealittle+symbolnexttothepositiveconnection.
-
Figure36 Project4breadboardlayout.
LaterinthisprojectwearegoingtoshowyouhowyoucanmovetheprojectfromthebreadboardtoamorepermanentdesignusingtheArduinoProtoshield.Thisrequiressomesoldering,soifyouthinkyoumightgoontomakeashieldandhavethefacilitiestosolder,IwouldsoldersomeleadsontotheLuxeonLED.Soldershortlengthsofsolidcorewiretotwoofthesixtagsaroundtheedge.Theyshouldbemarked+and.Itisagoodideatocolorcodeyourleadswithredforpositiveandblueorblackfornegative.
Ifyoudonotwanttosolder,thatsfineyoujustneedtocarefullytwistthesolidcorewirearoundtheconnectorsasshowninFigure37.
Figure37 AttachingleadstotheLuxeonLEDwithoutsoldering.
Figure38showsthefullyassembledbreadboard.
Figure38 PhotographofcompletebreadboardforProject4.
Software
Project4usesexactlythesamesketchasProject3.
Putting It All Together
IfyoudonotstillhavethesketchfromProject3loaded,thenloadthesketchforProject3fromyourArduinoSketchbookanddownloaditontoyourboard(seeChapter1).
Again,testingtheprojectisthesameasforProject3.YouwillneedtoopentheSerialMonitorwindowandjuststarttyping.
TheLEDactuallyhasaverywideangleofview,soonevariationonthisprojectwouldbetoadaptanLEDtorchinwhichtheLEDhasareflectortofocusthebeam.
Making a Shield
ThisisthefirstprojectthatwehavemadethathasenoughcomponentstojustifymakinganArduinoShieldcircuitboardtositontopoftheArduinoboarditself.WearealsogoingtousethishardwarewithminormodificationsinProject6,soperhapsitistimetomakeourselvesaLuxeonLEDShield.
Makingyourowncircuitboardsathomeisperfectlypossiblebutrequirestheuseofnoxiouschemicalsandafairamountofequipment.Butfortunately,thereisanothergreatpieceofArduinorelatedopensourcehardwarecalledtheArduinoProtoshield.Ifyoushoparound,thesecanbeobtainedfor$10orlessandwillprovideyouwithakitofallyouneedtomakeabasicshield.Thatincludestheboarditself,theheaderconnectorpinsthatfitintotheArduino,andsomeLEDs,switches,andresistors.PleasebeawarethatthereareseveralvariationsoftheProtoshieldboard,soyoumayhavetoadaptthefollowingdesignifyourboardisslightlydifferent.
ThecomponentsforaProtoshieldareshowninFigure39,themostimportantpartbeingtheProtoshieldcircuitboard(PCB).Itispossibleto
-
justbuythePCBonitsown,whichformanyprojectswillbeallyouneed.
Figure39 Protoshieldinkitform.
Wearenotgoingtosolderallthecomponentsthatcamewithourkitontotheboard.WearejustgoingtoaddthepowerLED,itsresistor,andjustthebottompinsthatconnecttotheArduinoboardbecausethisisgoingtobeatopshieldandwillnothaveanyothershieldsontopofit.
Agoodguideforassemblingcircuitboardsistosolderinplacethelowestcomponentsfirst.Sointhiscasewewillsoldertheresistors,theLED,theresetswitch,andthenthebottompinconnectors.
The1Kresistor,LED,andswitchareallpushedthroughfromthetopoftheboardandsolderedunderneath(Figure310).Theshortpartoftheconnectorpinswillbepushedupfromunderneaththeboardandsolderedontop.
Figure310 TheundersideoftheProtoshield.
Whensolderingtheconnectorpins,makesurethattheyarelinedupcorrectlybecausetherearetwoparallelrowsfortheconnectors:onefortheconnectiontothepinsbelowandoneforthesockets,whichwearenotusing,thatareintendedtoconnecttofurthershields.
AgoodwaytoensurethattheheadersareintherightplaceistofitthesectionsofheaderintoanArduinoboardandthenplacetheshieldontopandsolderthepinswhileitsstillpluggedintotheArduinoboard.Thiswillalsoensurethatthepinsarestraight.
Whenallthecomponentshavebeensolderedinplace,youshouldhaveaboardthatlookslikeFigure311.
Figure311 AssembledbasicProtoshield.
Wecannowaddourcomponentsforthisproject,whichwecantakefromthebreadboard.First,lineupallthecomponentsintheirintendedplacesaccordingtothelayoutofFigure312tomakesurethateverythingfitsintheavailablespace.
Figure312 Project4Protoshieldlayout.
Thiskindofboardisdoublesidedthatis,youcansoldertothetoporbottomoftheboard.AsyoucanseefromthelayoutinFigure312,someoftheconnectionsareinstripslikeabreadboard.
Wearegoingtomountallthecomponentsonthetopside,withtheleadspushedthroughandsolderedontheundersidewheretheyemergefromtheboard.Theleadsofthecomponentsunderneathcanthenbeconnectedupandexcessleadssnippedoff.Ifnecessary,lengthsofsolidcorewirecanbeusedwheretheleadswillnotreach.
Figure313showsthecompletedshield.Powerupyourboardandtestitout.Ifitdoesnotworkassoonasyoupoweritup,disconnectitfromthepowerrightawayandcarefullychecktheshieldforanyshortcircuitsorbrokenconnectionsusingamultimeter.
Figure313 CompleteLuxeonshieldattachedtoanArduinoboard.
Congratulations!YouhavecreatedyourfirstArduinoShield,anditisonethatwecanreuseinlaterprojects.
SummarySowehavemadeastartonsomesimpleLEDprojectsanddiscoveredhowtousehighpowerLuxeonLEDs.WehavealsolearnedabitmoreaboutprogrammingourArduinoboardinC.
InChapter4wearegoingtoextendthisbylookingatsomemoreLEDbasedprojects,includingamodeltrafficsignalandahighpowerstrobelight.
Recommended / Queue / Recent / Topics / Tutorials / Settings / Blog(http://blog.safaribooksonline.com) /Feedback(http://community.safaribooksonline.com/) / Sign Out 2015 Safari(http://www.safaribooksonline.com/).
-
Terms of Service / Privacy Policy