Вы находитесь на странице: 1из 13

30 Arduino Projects for the Evil Genius: Second Edition

NEXT

PREV

2 A Tour of Arduino

4 More LED Projects

Recent

Topics
Tutorials

CHAPTER 3

Highlights

Settings
Feedback(http://community.safaribooksonline.com)

LED Projects
INTHISCHAPTERWEAREGOINGTOstartbuildingsomeLEDbased

Sign Out

projects.Wewillkeepthehardwarefairlysimplesothatwecan
concentrateontheprogrammingoftheArduino.

Settings

Programmingmicrocontrollerscanbeatrickybusinessrequiringan
intimateknowledgeoftheinnerworkingsofthedevice:fuses,registers,
etc.Thisisdue,inpart,tothefactthatmodernmicrocontrollersare
almostinfinitelyconfigurable.Arduinostandardizesitshardware
configuration,which,inreturnforasmalllossofflexibility,makesthe

10 days left in your trial.

Feedback(http://community.safaribooksonline.com/)

devicesagreatdealeasiertoprogram.

Project 2
Morse Code S.O.S. Flasher
Morsecodeusedtobeavitalmethodofcommunicationinthe19thand
20thcenturies.Itscodingoflettersasaseriesoflongandshortdots
meantthatitcouldbesentovertelegraphwires,overaradiolink,and
usingsignalinglights.ThelettersS.O.S.(SaveOurSouls)arestill
recognizedasaninternationalsignalofdistress.
Inthisproject,wewillmakeourLEDflashthesequenceS.O.S.overand
overagain.
ForthisprojectyouwillneedjustthesamecomponentsasforProject1.
COMPONENTSANDEQUIPMENT

Hardware
ThehardwareisexactlythesameasforProject1.Soyoucaneitherjust
plugtheresistorandLEDdirectlyintotheArduinoconnectorsorusea
breadboard(seeChapter1).

Software
Ratherthanstarttypingthisprojectinfromscratch,wewilluseProject1
asastartingpoint.SopleasecompleteProject1beforeyoubeginthis
project.
Ifyouhavenotalreadydoneso,downloadtheprojectcodefrom
www.arduinoevilgenius.com(http://www.arduinoevilgenius.com)thenyoucan
alsojustloadthecompletedsketchforProject1fromyourArduino
Sketchbookanddownloadittotheboard(seeChapter1).However,itwill
helpyoutounderstandArduinobetterifyoumodifythesketchfrom

Subscribe.

Sign Out

Project1assuggestednext.
ModifytheloopfunctionofProject1sothatitnowappearsasshown
here.Notethatcopyandpastearehighlyrecommendedinthiskindof
situation.

Thiswouldallwork,andfeelfreetotryithowever,wearenotgoingto
leaveitthere.Wearegoingtoalteroursketchtoimproveitandatthe
sametimemakeitalotshorter.
Wecanreducethesizeofthesketchbycreatingourownfunctionto
replacethefourlinesofcodeinvolvedinanyflashoftheLEDwithone
line.
Aftertheloopfunctionsfinalcurlybrace,addthefollowingcode:

Enjoy Safari? Subscribe Today

You have 10 days


left in your trial,
M.bog.

Nowmodifytheloopfunctionsothatitlookslikethis:

Safari is your trusted guide for building a


remarkable career. We hope you've been
enjoying your trialready to join?

Subscribe Today
/ Contact Us(http://safaribooksonline.com/contact/) /
Blog(http://blog.safaribooksonline.com)
ThewholefinallistingisshowninListingProject2.
2015 Safari(http://www.safaribooksonline.com)
Terms of Service /
Membership Agreement / Privacy Policy

LISTINGPROJECT2

Thismakesthesketchalotsmallerandaloteasiertoread.

Putting It All Together


ThatconcludesProject2.Wewillnowcoversomemorebackgroundon
programmingtheArduinobeforewegoontolookatProject3,wherewe
willuseoursamehardwaretowriteaMorsecodetranslator,withwhich
wecantypesentencesonourcomputerandhavethemflashedasMorse
code.InProject4wewillimprovethebrightnessofourflashingby
replacingourredLEDwithahighpowerLuxeontypeLED.
ButfirstweneedalittlemoretheoryinordertounderstandProjects3
and4.

Loops
Loopsallowustorepeatagroupofcommandsacertainnumberoftimes
oruntilsomeconditionismet.InProject2,weonlywanttoflashthree
dotsforanS,soitisnogreathardshiptorepeattheflashcommandthree
times.However,itwouldbefarlessconvenientifweneededtoflashthe
LED100or1000times.Inthatcasewecanusetheforlanguage
commandinC:

Theforloopisabitlikeafunctionthattakesthreearguments,although
herethoseargumentsareseparatedbysemicolonsratherthanbythe
usualcommas.ThisisjustaquirkoftheClanguage.Thecompilerwill
soontellyouwhenyougetitwrong.
Thefirstthingintheparenthesesafterforisavariabledeclaration.This
specifiesavariabletobeusedasacountervariableandgivesitaninitial
valueinthiscase0.
Thesecondpartisaconditionthatmustbetrueforustostayintheloop.
Inthiscasewewillstayintheloopaslongasiislessthan100,butas
soonasiis100ormore,wewillstopdoingthethingsinsidetheloop.
Thefinalpartiswhattodoeverytimeyouhavedoneallthethingsinthe
loop.Inthiscase,thatisincrementiby1sothatitcan,after100trips
aroundtheloop,ceasetobelessthan100andcausethelooptoexit.
AnotherwayofloopinginCistousethewhilecommand.Thesame
exampleshownpreviouslycouldbeaccomplishedusingawhile
command,asshownhere:

Theexpressioninparenthesesafterthewhilemustbetruetostayinthe
loop.Whenitisnolongertrue,thesketchwillcontinuerunningthe
commandsafterthefinalcurlybrace.
Thecurlybracesareusedtobrackettogetheragroupofcommands.In
programmingparlance,theyareknownasablock.

Arrays
Arraysareawayofcontainingalistofvalues.Thevariableswehavemet
sofarhaveonlycontainedasinglevalue,usuallyanint.Bycontrast,an
arraycontainsalistofvalues,andyoucanaccessanyoneofthosevalues
byitspositioninthelist.
C,likethemajorityofprogramminglanguages,beginsitsindexpositions
at0ratherthan1.Thismeansthatthefirstelementisactuallyelement
zero.
Toillustratetheuseofarrays,wecouldchangeourMorsecodeexample
touseanarrayofflashdurations.Wecanthenuseaforlooptostep
througheachoftheitemsinthearray.
Firstletscreateanarrayoftypeintcontainingthedurations:

Youindicatethatavariablecontainsanarraybyplacing[]afterthe
variablename.Ifyouaresettingthecontentsofthearrayatthesametime
youaredefiningit,asintheprecedingexample,youdonotneedto
specifythesizeofthearray.Ifyouarenotsettingitsinitialcontents,then
youneedtospecifythesizeofthearrayinsidethesquarebrackets.For
example:

Nowwecanmodifyourloopmethodtousethearray:

Anobviousadvantageofthisapproachisthatitiseasytochangethe
messagebysimplyalteringthedurationsarray.InProject3wewilltake
theuseofarraysastagefurthertomakeamoregeneralpurposeMorse
codeflasher.

Project 3
Morse Code Translator
InthisprojectwearegoingtousethesamehardwareasforProjects1and
2,butwearegoingtowriteanewsketchthatwillletustypeinasentence
onourcomputerandhaveourArduinoboardconvertthatintothe
appropriateMorsecodedotsanddashes.
Figure31showstheMorsecodetranslatorinaction.Thecontentsofthe
messageboxarebeingflashedasdotsanddashesontheLED.

Figure31 Morsecodetranslator.
Todothis,wewillmakeuseofwhatwehavelearnedaboutarraysand
stringsandalsolearnsomethingaboutsendingmessagesfromour
computertotheArduinoboardthroughtheUSBcable.
Forthisproject,youwillneedjustthesamecomponentsasforProjects1
and2.Infact,thehardwareisexactlythesamewearejustgoingto
modifythesketchofProject1.
COMPONENTSANDEQUIPMENT

Hardware
PleasereferbacktoProject1forthehardwareconstructionforthis
project.
YoucaneitherjustplugtheresistorandLEDdirectlyintotheArduino
connectorsorusethebreadboard(seeChapter1).Youcanevenjust
changetheledPinvariableinthesketchtobepin13sothatyouusethe
builtinLEDanddonotneedanyexternalcomponentsatall.

Software

ThelettersinMorsecodeareshowninTable31.
TABLE31MorseCodeLetters

SomeoftherulesofMorsecodearethatadashisthreetimesaslongasa
dot,thetimebetweeneachdashordotisequaltothedurationofadot,
thespacebetweentwolettersisthesamelengthasadash,andthespace
betweentwowordsisthesamedurationassevendots.
Forthesakeofthisproject,wewillnotworryaboutpunctuation,although
itwouldbeaninterestingexerciseforyoutotryaddingthistothesketch.
ForafulllistofalltheMorsecharacters,see
http://en.wikipedia.org/wiki/Morse_code.
ThesketchforthisisshowninListingProject3.Anexplanationofhowit
allworksfollows.
LISTINGPROJECT3

Wekeeptrackofourdotsanddashesusingarraysofstrings.Wehavetwo
ofthese,oneforlettersandonefornumerals.So,tofindoutwhatwe
needtoflashforthefirstletterofthealphabet(A),wewillgetthestring
letters[0]remember,thefirstelementofanarrayiselement0,not
element1.
ThevariabledotDelayisdefined,soifwewanttomakeourMorsecode
flashfasterorslower,wecanchangethisvaluebecauseallthedurations
aredefinedasmultiplesofthetimeforadot.
Thesetupfunctionismuchthesameasforourearlierprojectshowever,
thistimewearegettingcommunicationsfromtheUSBport,sowemust
addthecommand

ThistellstheArduinoboardtosetthecommunicationsspeedthroughthe
USBtobe9600baud.Thisisnotveryfast,butfastenoughforourMorse
codemessages.Itisalsoagoodspeedtosetittobecausethatisthe
defaultspeedusedbytheArduinosoftwareonyourcomputer.
Intheloopfunctionwearegoingtorepeatedlyseeifwehavebeensent
anylettersovertheUSBconnectionandifwehavetoprocesstheletter.
TheArduinofunctionSerial.available()willbetrueifthereisacharacter
tobeturnedintoMorsecode,andtheSerial.read()functionwillgiveus
thatcharacter,whichweassigntoavariablecalledchthatwedefinedjust
insidetheloop.
Wethenhaveaseriesofifstatementsthatdeterminewhetherthe
characterisanuppercaseletter,alowercaseletter,oraspacecharacter
separatingtwowords.Lookingatthefirstifstatement,wearetestingto
seeifthecharactersvalueisgreaterthanorequaltoaandlessthanor
equaltoz.Ifthatisthecase,wecanfindthesequenceofdashesanddots
toflashusingthelettersarraythatwedefinedatthetopofthesketch.We
determinewhichsequencefromthearraytousebysubtractingafromthe

characterinch.
Atfirstsight,itmightlookstrangetobesubtractingoneletterfrom
another,butitisperfectlyacceptabletodothisinC.So,forexample,aa
is0,whereasdawillgiveustheanswer3.So,iftheletterthatweread
fromtheUSBconnectionsweref,wewouldcalculatefa,whichgivesus
5asthepositionofthelettersarray.Lookingupletters[5]willgiveusthe
string....andwepassthisstringtoafunctioncalledflashSequence.
TheflashSequencefunctionisgoingtoloopovereachofthepartsofthe
sequenceandflashitaseitheradashoradot.StringsinCallhavea
specialcodeontheendofthemthatmarkstheendofthestring,andthis
iscalledNULL.SothefirstthingflashSequencedoesistodefinea
variablecalledi.Thisisgoingtoindicatethecurrentpositioninthestring
ofdotsanddashes,startingatposition0.Thewhileloopwillkeepgoing
untilwereachtheNULLontheendofthestring.
Insidethewhileloop,wefirstflashthecurrentdotordashusinga
functionthatwearegoingtodiscussinamomentandthenadd1toiand
gobackroundtheloopflashingeachdotordashinturnuntilwereach
theendofthestring.
ThefinalfunctionthatwehavedefinedisflashDotOrDashthisjustturns
theLEDonandthenusesanifstatementtoeitherdelayfortheduration
ofasingledotifthecharacterisadotorforthreetimesthatdurationif
thecharacterisadashbeforeitturnstheLEDoffagain.

Putting It All Together


LoadthecompletedsketchforProject3fromyourArduinoSketchbook
anddownloaditontoyourboard(seeChapter1).
TousetheMorsecodetranslator,weneedtouseapartoftheArduino
softwarecalledtheSerialMonitor.Thiswindowallowsyoutotype
messagesthataresenttotheArduinoboardaswellasseeanymessages
thattheArduinoboardchoosestoreplywith.
TheSerialMonitorislaunchedbyclickingtherightmosticonshown
highlightedinFigure32.

Figure32 LaunchingtheSerialMonitor.
TheSerialMonitor(seeFigure33)hastwoparts.Atthetop,thereisa
fieldintowhichalineoftextcanbetypedthatwillbesenttotheboard
whenyoueitherclickSendorpressRETURN.

Figure33 TheSerialMonitorwindow.
Belowthatisalargerareainwhichanymessagescomingfromthe
Arduinoboardwillbedisplayed.Rightatthebottomofthewindowisa
dropdownlistwhereyoucanselectthespeedatwhichthedataissent.
Whateveryouselectheremustmatchthebaudratethatyouspecifyin
yourscriptsstartupmessage.Weuse9600,whichisthedefault,sothere
isnoneedtochangeanythinghere.
SoallweneedtodoislaunchtheSerialMonitor,typesometextintothe
Sendfield,andclicktheSendbuttonorpressRETURN.Weshouldthen
haveourmessageflashedtousinMorsecode.

Project 4

High-Brightness Morse Code Translator


ThelittleLEDonProject3isunlikelytobevisiblefromtheshiponthe
horizonbeingluredbyourbogusEvilGeniusdistressmessage.So,inthis
project,wearegoingtoupthepowerandusea1WLuxeonLED.These
LEDsareextremelybright,andallthelightcomesfromatinylittleareain
thecenter,sotoavoidanypossibilityofretinadamage,donotstare
directlyintoit.
Wealsolookathow,withabitofsoldering,wecanmakethisprojectinto
ashieldthatcanbepluggedintoourArduinoboard.
COMPONENTSANDEQUIPMENT

Hardware
TheLEDweusedinProject3usedabout10mAat2V.Wecanusethisto
calculatepowerusingtheformula
P=IV
Powerequalsthevoltageacrosssomethingtimesthecurrentflowing
throughit,andtheunitofpoweristhewatt.SothatLEDwouldbe
approximately20mW,orafiftiethofthepowerofour1WLuxeonLED.
WhileanArduinowillcopejustfinedrivinga20mWLED,itwillnotbe
abletodirectlydrivethe1WLED.
Thisisacommonprobleminelectronicsandcanbesummedupas
gettingasmallcurrenttocontrolabiggercurrent,somethingthatis
knownasamplification.Themostcommonlyusedelectroniccomponent
foramplificationisthetransistor,sothatiswhatwewillusetoswitchour
LuxeonLEDonandoff.
ThebasicoperationofatransistorisshowninFigure34.Therearemany
differenttypesoftransistors,andprobablythemostcommonandthe
typethatwearegoingtouseiscalledanNPNbipolartransistor.

Figure34 TheoperationofanNPNbipolartransistor.
Thistransistorhasthreeleads:theemitter,thecollector,andthebase.
Andthebasicprincipleisthatasmallcurrentflowingthroughthebase
willallowamuchbiggercurrenttoflowbetweenthecollectorandthe
emitter.
Justhowmuchbiggerthecurrentisdependsonthetransistor,butitis
typicallyafactorof100.Soacurrentof10mAflowingthroughthebase
couldcauseupto1Atoflowthroughthecollector.So,ifwekeptthe270
resistorthatweusedtodrivetheLEDat10mA,wecouldexpectittobe
morethanenoughtoallowthetransistortoswitchthehundredsof
milliampsneededbytheLuxeonLED.
TheschematicdiagramforourcontrolcircuitisshowninFigure35.

Figure35 SchematicdiagramforhighpowerLEDdriving.
The270resistor(R1)limitsthecurrentthatflowsthroughthebase.We
cancalculatethecurrentusingtheformulaI=V/R.Vwillbe4.4Vrather
than5Vbecausetransistorsnormallyhaveavoltageof0.6Vbetweenthe
baseandemitter,andthehighestvoltagetheArduinocansupplyfroman
outputpinis5V.Sothecurrentwillbe4.4/270=16mA.
ThedatasheetforthisLEDstatesthattheabsolutemaximumforward
currentis350mA,andtheforwardvoltageis3.4V.Sowewillaimfor
around200mA,whichwillmaketheLEDgoodandbrightwithout
shorteningitslife.
R2limitsthecurrentflowingthroughtheLEDtoaround200mA.We
cameupwiththefigureof4.7byusingtheformulaR=V/I.Vwillbe
roughly53.40.6=1.0V.5Visthesupplyvoltage,theLEDdrops
roughly3.4Vandthetransistor0.6V,sotheresistanceshouldbe
1.0V/200mA=5.Resistorscomeinstandardvalues,sowewillselecta
4.7resistor.Wemustalsousearesistorthatcancopewiththis
relativelyhighcurrent.Thepowerthattheresistorwillburnoffasheatis
equaltothevoltageacrossitmultipliedbythecurrentflowingthroughit.
Inthiscase,thatis200mA1.0V,whichis200mW.Thismeansthata
regular0.5Woreven0.25Wresistorwillbejustfine.
Inthesameway,whenchoosingatransistor,weneedtomakesurethatit
canhandlethepower.Whenitisturnedon,thetransistorwillconsume
powerequaltocurrenttimesvoltage.Inthiscase,thebasecurrentis
smallenoughtoignore,sothepowerwilljustbe0.6V200mA,or120
mW.Itisalwaysagoodideatopickatransistorthatcaneasilycopewith
thepower.Inthiscase,wearegoingtouseaBD139,whichhasapower
ratingofover12W.InChapter10youcanfindatableofcommonlyused
transistors.
Nowweneedtoputourcomponentsintothebreadboardaccordingtothe
layoutshowninFigure36,withthecorrespondingphotographofFigure
38.Itiscrucialtocorrectlyidentifytheleadsofthetransistorandthe
LED.Themetallicsideofthetransistorshouldbefacingtheboard.The
LEDwillhavealittle+symbolnexttothepositiveconnection.

Figure36 Project4breadboardlayout.
Laterinthisprojectwearegoingtoshowyouhowyoucanmovethe
projectfromthebreadboardtoamorepermanentdesignusingthe
ArduinoProtoshield.Thisrequiressomesoldering,soifyouthinkyou
mightgoontomakeashieldandhavethefacilitiestosolder,Iwould
soldersomeleadsontotheLuxeonLED.Soldershortlengthsofsolidcore
wiretotwoofthesixtagsaroundtheedge.Theyshouldbemarked+and
.Itisagoodideatocolorcodeyourleadswithredforpositiveandblue
orblackfornegative.
Ifyoudonotwanttosolder,thatsfineyoujustneedtocarefullytwistthe
solidcorewirearoundtheconnectorsasshowninFigure37.

Figure37 AttachingleadstotheLuxeonLEDwithoutsoldering.
Figure38showsthefullyassembledbreadboard.

Figure38 PhotographofcompletebreadboardforProject4.

Software
Project4usesexactlythesamesketchasProject3.

Putting It All Together


IfyoudonotstillhavethesketchfromProject3loaded,thenloadthe
sketchforProject3fromyourArduinoSketchbookanddownloaditonto
yourboard(seeChapter1).
Again,testingtheprojectisthesameasforProject3.Youwillneedto
opentheSerialMonitorwindowandjuststarttyping.
TheLEDactuallyhasaverywideangleofview,soonevariationonthis
projectwouldbetoadaptanLEDtorchinwhichtheLEDhasareflector
tofocusthebeam.

Making a Shield
Thisisthefirstprojectthatwehavemadethathasenoughcomponentsto
justifymakinganArduinoShieldcircuitboardtositontopoftheArduino
boarditself.Wearealsogoingtousethishardwarewithminor
modificationsinProject6,soperhapsitistimetomakeourselvesa
LuxeonLEDShield.
Makingyourowncircuitboardsathomeisperfectlypossiblebutrequires
theuseofnoxiouschemicalsandafairamountofequipment.But
fortunately,thereisanothergreatpieceofArduinorelatedopensource
hardwarecalledtheArduinoProtoshield.Ifyoushoparound,thesecan
beobtainedfor$10orlessandwillprovideyouwithakitofallyouneed
tomakeabasicshield.Thatincludestheboarditself,theheader
connectorpinsthatfitintotheArduino,andsomeLEDs,switches,and
resistors.Pleasebeawarethatthereareseveralvariationsofthe
Protoshieldboard,soyoumayhavetoadaptthefollowingdesignifyour
boardisslightlydifferent.
ThecomponentsforaProtoshieldareshowninFigure39,themost
importantpartbeingtheProtoshieldcircuitboard(PCB).Itispossibleto

justbuythePCBonitsown,whichformanyprojectswillbeallyouneed.

Figure39 Protoshieldinkitform.
Wearenotgoingtosolderallthecomponentsthatcamewithourkitonto
theboard.WearejustgoingtoaddthepowerLED,itsresistor,andjust
thebottompinsthatconnecttotheArduinoboardbecausethisisgoingto
beatopshieldandwillnothaveanyothershieldsontopofit.
Agoodguideforassemblingcircuitboardsistosolderinplacethelowest
componentsfirst.Sointhiscasewewillsoldertheresistors,theLED,the
resetswitch,andthenthebottompinconnectors.
The1Kresistor,LED,andswitchareallpushedthroughfromthetopof
theboardandsolderedunderneath(Figure310).Theshortpartofthe
connectorpinswillbepushedupfromunderneaththeboardandsoldered
ontop.

Figure310 TheundersideoftheProtoshield.
Whensolderingtheconnectorpins,makesurethattheyarelinedup
correctlybecausetherearetwoparallelrowsfortheconnectors:onefor
theconnectiontothepinsbelowandoneforthesockets,whichwearenot
using,thatareintendedtoconnecttofurthershields.
Agoodwaytoensurethattheheadersareintherightplaceistofitthe
sectionsofheaderintoanArduinoboardandthenplacetheshieldontop
andsolderthepinswhileitsstillpluggedintotheArduinoboard.This
willalsoensurethatthepinsarestraight.
Whenallthecomponentshavebeensolderedinplace,youshouldhavea
boardthatlookslikeFigure311.

Figure311 AssembledbasicProtoshield.
Wecannowaddourcomponentsforthisproject,whichwecantakefrom
thebreadboard.First,lineupallthecomponentsintheirintendedplaces
accordingtothelayoutofFigure312tomakesurethateverythingfitsin
theavailablespace.

Figure312 Project4Protoshieldlayout.
Thiskindofboardisdoublesidedthatis,youcansoldertothetopor
bottomoftheboard.AsyoucanseefromthelayoutinFigure312,some
oftheconnectionsareinstripslikeabreadboard.
Wearegoingtomountallthecomponentsonthetopside,withtheleads
pushedthroughandsolderedontheundersidewheretheyemergefrom
theboard.Theleadsofthecomponentsunderneathcanthenbe
connectedupandexcessleadssnippedoff.Ifnecessary,lengthsofsolid
corewirecanbeusedwheretheleadswillnotreach.
Figure313showsthecompletedshield.Powerupyourboardandtestit
out.Ifitdoesnotworkassoonasyoupoweritup,disconnectitfromthe
powerrightawayandcarefullychecktheshieldforanyshortcircuitsor
brokenconnectionsusingamultimeter.

Figure313 CompleteLuxeonshieldattachedtoanArduinoboard.
Congratulations!YouhavecreatedyourfirstArduinoShield,anditisone
thatwecanreuseinlaterprojects.

Summary
SowehavemadeastartonsomesimpleLEDprojectsanddiscoveredhow
tousehighpowerLuxeonLEDs.Wehavealsolearnedabitmoreabout
programmingourArduinoboardinC.
InChapter4wearegoingtoextendthisbylookingatsomemoreLED
basedprojects,includingamodeltrafficsignalandahighpowerstrobe
light.

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

Вам также может понравиться