Sie sind auf Seite 1von 25

30 Arduino Projects for the Evil Genius: Second Edition

NEXT

PREV

4 More LED Projects

6 Light Projects

Recent

Topics
Tutorials

CHAPTER 5

Highlights

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

Sensor Projects
SENSORSTURNREALWORLDmeasurementsintoelectronicsignalsthat

Sign Out

wecanthenuseonourArduinoboards.Theprojectsinthischapterare
allaboutusinglightandtemperature.

Settings

Wealsolookathowtointerfacewithkeypadsandrotaryencoders.
10 days left in your trial.

Project 10
Keypad Security Code

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

ThisprojectwouldnotbeoutofplaceinthelairofanyEvilGeniusworth
theirsalt.Asecretcodemustbeenteredonthekeypad,andifitiscorrect,
agreenLEDwilllightotherwise,aredLEDwillstaylit.InProject27we
willrevisitthisprojectandshowhowitcannotjustshowtheappropriate
lightbutalsocontroladoorlock.
COMPONENTSANDEQUIPMENT

Enjoy Safari? Subscribe Today

Unfortunately,keypadsdonotusuallyhavepinsattached,sowewillhave
toattachsome,andtheonlywaytodothatistosolderthemon.Sothisis
anotherofourprojectswhereyouwillhavetodoalittlesoldering.

Hardware
TheschematicdiagramforProject10isshowninFigure51.Bynow,you
willbeusedtoLEDsthenewcomponentisthekeypad.

Subscribe.

Sign Out

Figure51 SchematicdiagramforProject10.
Keypadsarenormallyarrangedinagridsothatwhenoneofthekeysis
pressed,itconnectsarowtoacolumn.Figure52showsatypical
arrangementfora12keykeypadwithnumbersfrom0to9and*and#
keys.

Figure52 A12keykeypad.
Thekeyswitchesarearrangedattheintersectionofrowandcolumn
wires.Whenakeyispressed,itconnectsaparticularrowtoaparticular
column.
Byarrangingthekeysinagridlikethis,itmeansthatweonlyneedtouse
7(4rows+3columns)ofourdigitalpinsratherthan12(oneforeach
key).
However,italsomeansthatwehavetodoabitmoreworkinthesoftware
todeterminewhichkeysarepressed.Thebasicapproachwehavetotake
istoconnecteachrowtoadigitaloutputandeachcolumntoadigital
input.Wethenputeachoutputhighinturnandseewhichinputsare
high.
Figure53showshowyoucansoldersevenpinsfromapinheaderstrip
ontothekeypadsothatyoucanthenconnectittothebreadboard.Pin
headersareboughtinstripsandcanbeeasilysnappedtoprovidethe
numberofpinsrequired.

Figure53 Solderingpinstothekeypad.
Nowwejustneedtofindoutwhichpinonthekeypadcorrespondsto
whichroworcolumn.Ifwearelucky,thekeypadwillcomewitha
datasheetthattellsusthis.Ifnot,wewillhavetodosomedetectivework
withamultimeter.Setthemultimetertocontinuitysothatitbeepswhen
youconnecttheleadstogether.Thengetsomepaper,drawadiagramof
thekeypadconnections,andlabeleachpinwithaletterfromatog.Then
writealistofallthekeys.Then,holdingeachkeydowninturn,findthe
pairofpinsthatmakethemultimeterbeep,indicatingaconnection
(Figure54).Releasethekeytocheckthatyouhaveindeedfoundthe
correctpair.Afterawhile,apatternwillemerge,andyouwillbeableto
seehowthepinsrelatetorowsandcolumns.Figure54showsthe
arrangementforthekeypadusedbytheauthor.

Figure54 Workingoutthekeypadconnections.
ThecompletedbreadboardlayoutisshowninFigure55andthe
assembledbreadboardinFigure56.Notethatyourkeypadmayhavea
differentpinout.Ifso,youwillneedtochangethejumperwiresconnected
toitaccordingly.

Figure55 Project10breadboardlayout.

Figure56 Project10keypadsecuritycode.
Youmayhavenoticedthatdigitalpins0and1haveTXandRXnextto
them.ThisissobecausetheyarealsousedbytheArduinoboardforserial
communications,includingtheUSBconnection.Itiscommontoavoid
usingthesepinsforgeneralpurposeinputoutputdutiessothatserial
communications,includingprogrammingtheArduino,cantakeplace
withouttheneedtodisconnectanywires.

Software
Whilewecouldjustwriteasketchthatturnsontheoutputforeachrowin
turnandreadstheinputstogetthecoordinatesofanykeypressed,itisa
bitmorecomplexthanthatbecauseswitchesdonotalwaysbehaveina

goodwaywhenyoupressthem.Keypadsandpushswitchesarelikelyto
bounce.Thatis,whenyoupressthem,theydonotsimplygofrombeing
openedtoclosedbutmayopenandcloseseveraltimesaspartofpressing
thebutton.
Fortunatelyforus,MarkStanleyandAlexanderBrevighavecreateda
librarythatyoucanusetoconnecttokeypadsthathandlesuchthingsfor
us.Thisisagoodopportunitytodemonstrateinstallingalibraryintothe
Arduinosoftware.
InadditiontothelibrariesthatcomewiththeArduino,manypeoplehave
developedtheirownlibrariesandpublishedthemforthebenefitofthe
Arduinocommunity.TheEvilGeniusismuchamusedbysuchaltruism
andseesitasagreatweakness.However,theEvilGeniusisnotabove
usingsuchlibrariesforhisowndeviousends.
Tomakeuseofthislibrary,wemustfirstdownloaditfromtheArduino
websiteatthisaddress:
www.arduino.cc/playground/Code(http://www.arduino.cc/playground/Code)/Keypad.
DownloadthefileKeypad.ziptoyourdesktop.
WhetherusingWindows,Mac,orLINUX,youwillfindthattheArduino
softwarehascreatedafolderinyourDocumentsfolderthatcontainsa
directorycalledArduino.Librariesthatyoudownloadallshouldbe
installedinafoldercalledLibraieswithinthisArduinodirectory.If
thisisthefirstlibraryyouhaveinstalled,youwillneedtocreatethis
folder.
Figure57showshowyoucancreatethisfolderasyouextractthe
LibraryfolderfromtheZipfile

Figure57 UnzippingthelibraryforWindows.
OnceyouhaveinstalledthislibraryintoyourArduinodirectory,you
willbeabletouseitwithanysketchesthatyouwrite.
Youcancheckthatthelibraryisinstalledcorrectlybyrestartingthe
ArduinoIDEandselectingtheExamplesoptionfromtheFilemenu.
YoushouldnowfindthatthereisanewcategoryfortheKeypadlibrary
(Figure58).

Figure58 Checkingtheinstallation.
ThesketchfortheapplicationisshowninListingProject10.Notethat
youmaywellhavetochangeyourkeysrowPinsandcolPinsarrayssothat
theyagreewiththekeylayoutofyourkeypad,aswediscussedinthe
hardwaresection.
LISTINGPROJECT10

Thissketchisquitestraightforward.Theloopfunctionchecksforakey
press.Ifthekeypressedisa#ora*,itsetsthepositionvariablebackto
0.If,ontheotherhand,thekeypressedisoneofthenumerals,itchecks
toseeifthenextkeyexpected(secretCode[position])isthekeyjust
pressed,andifitis,itincrementspositionbyone.Finally,theloopchecks
toseeifpositionis4,andifitis,itsetstheLEDstotheirunlockedstate.

Putting It All Together


LoadthecompletedsketchforProject10fromyourArduinoSketchbook
anddownloadittotheboard(seeChapter1).
Ifyouhavetroublegettingthistowork,itismostlikelyaproblemwith
thepinlayoutonyourkeypad.Soperseverewiththemultimetertomap
outthepinconnections.

Rotary Encoders
Wehavealreadymetvariableresistors:Asyouturntheknob,the
resistancechanges.Theseusedtobebehindmostknobsthatyoucould
twiddleonelectronicequipment.Thereisanalternative,therotary
encoder,andifyouownsomeconsumerelectronicswhereyoucanturn
theknobroundandroundindefinitelywithoutmeetinganykindofend
stop,thereisprobablyarotaryencoderbehindtheknob.
Somerotaryencodersalsoincorporateabuttonsothatyoucanturnthe
knobandthenpress.Thisisaparticularlyusefulwayofmakinga
selectionfromamenuwhenusedwithaliquidcrystaldisplay(LCD)
screen.
Arotaryencoderisadigitaldevicethathastwooutputs(AandB),andas
youturntheknob,yougetachangeintheoutputsthatcantellyou
whethertheknobhasbeenturnedclockwiseorcounterclockwise.

Figure59showshowthesignalschangeonAandBwhentheencoderis
turned.Whenrotatingclockwise,thepulseswillchange,astheywould
movinglefttorightonthediagramwhenmovingcounterclockwise,the
pulseswouldbemovingrighttoleftonthediagram.

Figure59 Pulsesfromarotaryencoder.
So,ifAislowandBislowandthenBbecomeshigh(goingfromphase1
tophase2),thatwouldindicatethatwehaveturnedtheknobclockwise.A
clockwiseturnalsowouldbeindicatedbyAbeinglow,Bbeinghigh,and
thenAbecominghigh(goingfromphase2tophase3),etc.However,ifA
werehighandBwerelowandthenBwenthigh,wehavemovedfrom
phase4tophase3andarethereforeturningcounterclockwise.

Project 11
Model Traffic Signal Using a Rotary Encoder
Thisprojectusesarotaryencoderwithabuiltinpushswitchtocontrol
thesequenceofthetrafficsignalsandisbasedonProject5.Itisamuch
morerealisticversionofatrafficsignalcontrollerandisreallynotfaroff
thelogicthatyouwouldfindinarealtrafficsignalcontroller.
Rotatingtherotaryencoderwillchangethefrequencyofthelight
sequencing.Pressingthebuttonwilltestthelights,turningthemallonat
thesametime,whilethebuttonispressed.
ThecomponentsarethesameasforProject5,withtheadditionofthe
rotaryencoderinplaceoftheoriginalpushswitch.
COMPONENTSANDEQUIPMENT

Hardware
TheschematicdiagramforProject11isshowninFigure510.The
majorityofthecircuitryisthesameasforProject5,exceptthatnowwe
havearotaryencoder.

Figure510 SchematicdiagramforProject11.
Therotaryencoderworksjustasiftherewerethreeswitches:oneeachfor
AandBandoneforthepushswitch.
SincetheschematicismuchthesameasforProject5,itwillnotbemuch
ofasurprisetoseethatthebreadboardlayout(Figure511)isalsosimilar
totheoneforthatproject.

Figure511 BreadboardlayoutforProject11.

Software
ThestartingpointforthesketchisthesketchforProject5.Wehave
addedcodetoreadtheencoderandtorespondtothebuttonpressby
turningalltheLEDson.Wealsohavetakentheopportunitytoenhance
thelogicbehindthelightstomakethembehaveinamorerealisticway,
changingautomatically.InProject5,whenyouhelddownthebutton,the
lightschangedsequenceroughlyoncepersecond.Inarealtrafficsignal,
thelightsstaygreenandredalotlongerthantheyareyellow.Soour
sketchnowhastwoperiods:shortPeriod,whichdoesnotalterbutisused
whenthelightsarechanging,andlongPeriod,whichdetermineshowlong
theyareilluminatedwhengreenorred.ThislongPeriodistheperiodthat
ischangedbyturningtherotaryencoder.

Thekeytohandlingtherotaryencoderliesinthefunction
getEncoderTurn.Everytimethisiscalled,itcomparesthepreviousstate
ofAandBwiththeircurrentstate,andifsomethinghaschanged,itworks
outwhetheritwasclockwiseorcounterclockwiseandreturnsa1or1,
respectively.Ifthereisnochange(theknobhasnotbeenturned),it
returns0.Thisfunctionmustbecalledfrequently,orturningtherotary
controllerquicklywillresultinsomechangesnotbeingrecognized
correctly.
Ifyouwanttousearotaryencoderforotherprojects,youcanjustcopy
thisfunction.ThefunctionusesthestaticmodifierfortheoldAandoldB
variables.Thisisausefultechniquethatallowsthefunctiontoretainthe
valuesbetweenonecallofthefunctionandthenext,wherenormallyit
wouldresetthevalueofthevariableeverytimethefunctioniscalled.
LISTINGPROJECT11

Thissketchillustratesausefultechniquethatletsyoutimeevents
(turninganLEDonforsomanyseconds)whileatthesametimechecking
therotaryencoderandbuttontoseeiftheyhavebeenturnedorpressed.
IfwejustusedtheArduinodelayfunctionwith,say,20,000,for20
seconds,wewouldnotbeabletochecktherotaryencoderorswitchin
thatperiod.
Sowhatwedoisuseaveryshortdelay(1millisecond)butmaintaina
countthatisincrementedeachtimeroundtheloop.Thus,ifwewantto
delayfor20seconds,westopwhenthecounthasreached20,000.Thisis
lessaccuratethanasinglecalltothedelayfunctionbecausethe1
millisecondisactually1millisecondplustheprocessingtimefortheother
thingsthataredoneinsidetheloop.

Putting It All Together


LoadthecompletedsketchforProject11fromyourArduinoSketchbook

anddownloadittotheboard(seeChapter1).
YoucanpresstherotaryencoderbuttontotesttheLEDsandturnthe
rotaryencodertochangehowlongthesignalstaysgreenandred.

Sensing Light
Acommonandeasytousedeviceformeasuringlightintensityisthe
lightdependentresistor(orLDR).Theyarealsosometimescalled
photoresistors.
ThebrighterthelightfallingonthesurfaceoftheLDR,theloweristhe
resistance.AtypicalLDRwillhaveadarkresistanceofupto2Manda
resistancewhenilluminatedinbrightdaylightofperhaps20k.
Wecanconvertthischangeinresistancetoachangeinvoltagebyusing
theLDR,withafixedresistorasavoltagedivider,connectedtooneofour
analoginputs.TheschematicforthisisshowninFigure512.

Figure512 UsinganLDRtomeasurelight.
Withafixedresistorof100K,wecandosomeroughcalculationsabout
thevoltagerangetoexpectattheanaloginput.
Indarkness,theLDRwillhavearesistanceof2M,sowithafixed
resistorof100K,therewillbeabouta20:1ratioofvoltage,withmostof
thatvoltageacrosstheLDR,sothiswouldmeanabout4VacrosstheLDR
and1Vattheanalogpin.
Ontheotherhand,iftheLDRisinbrightlight,itsresistancemightfallto
20k.Theratioofvoltagesthenwouldbeabout4:1infavorofthefixed
resistor,givingavoltageattheanaloginputofabout4V.
Amoresensitivephotodetectoristhephototransistor.Thisfunctionslike
anordinarytransistorexceptthereisnotusuallyabaseconnection.
Instead,thecollectorcurrentiscontrolledbytheamountoflightfalling
onthephototransistor.

Project 12
Pulse-Rate Monitor
Thisprojectusesanultrabrightinfrared(IR)LEDandaphototransistor
todetectthepulseinyourfinger.ItthenflashesaredLEDintimewith
yourpulse.
COMPONENTSANDEQUIPMENT

Hardware
Thepulsemonitorworksasfollows:ShinethebrightLEDontoonesideof
yourfingerwhilethephototransistorontheothersideofyourfingerpicks
uptheamountoftransmittedlight.Theresistanceofthephototransistor
willvaryslightlyasthebloodpulsesthroughyourfinger.
TheschematicforthisisshowninFigure513andthebreadboardlayout
inFigure515.WehavechosenquiteahighvalueofresistanceforR1
becausemostofthelightpassingthroughthefingerwillbeabsorbed,and
wewantthephototransistortobequitesensitive.Youmayneedto
experimentwiththevalueoftheresistortogetthebestresults.

Figure513 SchematicforProject12.
Itisimportanttoshieldthephototransistorfromasmuchstraylightas
possible.Thisisparticularlyimportantfordomesticlightsthatactually
fluctuateat50or60Hzandwilladdaconsiderableamountofnoiseto
ourweakheartsignal.
Forthisreason,thephototransistorandLEDarebuiltintoatubeor
corrugatedcardboardheldtogetherwithducttape.Theconstructionof
thisisshowninFigure514.

Figure514 Sensortubeforheartmonitor.
Two5mmholesaredrilledoppositeeachotherinthetube,andtheLED
isinsertedintoonesideandthephototransistorintotheother.Short
leadsaresolderedtotheLEDandphototransistor,andthenanotherlayer
oftapeiswrappedovereverythingtoholditallinplace.Besuretocheck
whichcoloredwireisconnectedtowhichleadoftheLEDand
phototransistorbeforeyoutapethemup.
Itisalsoagoodideatousescreenedwireforthephototransistorto
reduceinterference.ItisalsoworthnotingthatapeculiarityofmostIR
LEDsisthatthelongerleadisnegativeratherthanpositive,socheckthe
datasheetofthedevicebeforeyouattachit.
Thebreadboardlayoutforthisproject(Figure515)isvery
straightforward.

Figure515 BreadboardlayoutforProject12.
ThefinalfingertubecanbeseeninFigure516.

Figure516 Project12:pulseratemonitor.

Software
Thesoftwareforthisprojectisquitetrickytogetright.Indeed,thefirst
stepisnottoruntheentirefinalscriptbutratheratestscriptthatwill
gatherdatathatwecanthenpasteintoaspreadsheetandcharttotestout
thesmoothingalgorithm(moreonthislater).
ThetestscriptisprovidedinListingProject12.
LISTINGPROJECT12TESTSCRIPT

Thisscriptreadstherawsignalfromtheanaloginput,appliesthe
smoothingfunction,andthenwritesbothvaluestotheSerialMonitor,
wherewecancapturethemandpastethemintoaspreadsheetfor
analysis.NotethattheSerialMonitorscommunicationsissettoits
fastestratetominimizetheeffectsofthedelayscausedbysendingthe
data.WhenyoustarttheSerialMonitor,youwillneedtochangetheserial
speedto115,200baud.

Thesmoothingfunctionusesatechniquecalledleakyintegration,and
youcanseeinthecodewherewedothissmoothingusingtheline

Thevariablealphaisanumbergreaterthan0butlessthan1and
determineshowmuchsmoothingtodo.
Putyourfingerintothesensortube,starttheSerialMonitor,andleaveit
runningfor3or4secondstocaptureafewpulses.
Thencopyandpastethecapturedtextintoaspreadsheet.Youwill
probablybeaskedforthecolumndelimitercharacter,whichisacomma.
Theresultingdataandalinechartdrawnfromthetwocolumnsare
showninFigure517.

Figure517 Heartmonitortestdatapastedintoaspreadsheet.
Themorejaggedtraceisfromtherawdatareadfromtheanalogport,and
thesmoothertraceclearlyhasmostofthenoiseremoved.Ifthesmoothed
traceshowssignificantnoiseinparticular,anyfalsepeaksthatwill
confusethemonitorincreasethelevelofsmoothingbydecreasingthe
valueofalpha.
Onceyouhavefoundtherightvalueofalphaforyoursensor
arrangement,youcantransferthisvalueintotherealsketchandswitch
overtousingtherealsketchratherthanthetestsketch.Therealsketchis
providedinthefollowinglisting.
LISTINGPROJECT12

Therenowjustremainstheproblemofdetectingthepeaks.Lookingat
Figure517,wecanseethatifwekeeptrackofthepreviousreading,we
canseethatthereadingsaregraduallyincreasinguntilthechangein
readingflipsoverandbecomesnegative.So,ifwelittheLEDwhenever
theoldchangewaspositivebutthenewchangewasnegative,wewould
getabriefpulsefromtheLEDatthepeakofeachpulse.

Putting It All Together


BoththetestandrealsketchforProject12areinyourArduino
Sketchbook.Forinstructionsondownloadingittotheboard,seeChapter
1.
Asmentionedearlier,gettingthisprojecttoworkisalittletricky.Youwill
probablyfindthatyouhavetogetyourfingerinjusttherightplaceto
startgettingapulse.Ifyouarehavingtrouble,runthetestscriptas
describedpreviouslytocheckthatyourdetectorisgettingapulseandthe
smoothingfactoralphaislowenough.
Theauthorwouldliketopointoutthatthisdeviceshouldnotbeusedfor
anykindofrealmedicalapplication.

Measuring Temperature
Measuringtemperatureisasimilarproblemtomeasuringlightintensity.
InsteadofanLDR,adevicecalledathermistorisused.Asthe
temperatureincreases,sodoestheresistanceofthethermistor.
Whenyoubuyathermistor,itwillhaveastatedresistance.Inthiscase,
thethermistorchosenis33k.Thiswillbetheresistanceofthedeviceat
25C.
Theformulaforcalculatingtheresistanceataparticulartemperatureis
givenby
R=R exp(beta/(T+273)beta/(T +273)
o

Youcandothemathifyoulike,butamuchsimplerwaytomeasure
temperatureistouseaspecialpurposethermometerchipsuchasthe
TMP36.Thisthreepinneddevicehastwopinsforthepowersupply(5V)
andathirdoutputpin,whosetemperatureTindegreesCisrelatedtothe
outputvoltageVbytheequation
T=(V0.5)100
So,ifthevoltageatitsoutputis1V,thetemperatureis50C.

Project 13
USB Temperature Logger

Thisprojectiscontrolledbyyourcomputer,butoncegivenitslogging
instructions,thedevicecanbedisconnectedandrunonbatteriestodoits
logging.Whilelogging,itstoresitsdata,andthenwhentheloggeris
reconnected,itwilltransferitsdatabackovertheUSBconnection,where
itcanbeimportedintoaspreadsheet.Bydefault,theloggerwillrecord
onesampleevery5minutesandcanrecordupto1000samples.
Toinstructthetemperatureloggerfromyourcomputer,wehavetodefine
somecommandsthatcanbeissuedfromthecomputer.Theseareshown
inTable51.
TABLE51TemperatureLoggerCommands

ThisprojectjustrequiresaTMP36thatcanfitdirectlyintothesocketson
theArduino.
COMPONENTSANDEQUIPMENT

Hardware
TheschematicdiagramforProject13isshowninFigure518.

Figure518 SchematicdiagramforProject13.
ThisissosimplethatwecansimplyfittheleadsoftheTMP36intothe
Arduinoboard,asshowninFigure519.Notethatthecurvedsideofthe
TMP36shouldfaceoutwardfromtheArduino.Puttingalittlekinkinthe
leadswithplierswillensureabettercontact.

Figure519 Project13:temperaturelogger.
Twooftheanalogpins(A0andA2)aregoingtobeusedfortheGNDand
5VpowerconnectionstotheTMP36.TheTMP36usesverylittlecurrent,
sothepinscaneasilysupplyenoughtopoweritifwesetonepinHIGH
andtheotherLOW.

Software
Thesoftwareforthisprojectisalittlemorecomplexthanforsomeofour
otherprojects(seeListingProject13).Allthevariablesthatwehaveused
inoursketchessofarareforgottenassoonastheArduinoboardisreset
ordisconnectedfromthepower.Sometimeswewanttobeabletostore
datapersistentlysothatitistherenexttimewestartuptheboard.This
canbedonebyusingthespecialtypeofmemoryontheArduinocalled
EEPROM,whichstandsforelectricallyerasableprogrammableread
onlymemory.TheArduinoUnoandLeonardobothhave1024bytesof
EEPROM.
Forthedataloggertobeuseful,itneedstorememberthereadingsthatit
hasalreadytaken,evenwhenitisdisconnectedfromthecomputerand
poweredfromabattery.Italsoneedstoremembertheloggingperiod.
ThisisthefirstprojectwherewehaveusedtheArduinosEEPROMto
storevaluessothattheyarenotlostiftheboardisresetordisconnected
fromthepower.Thismeansthatoncewehavesetourdatalogging
recording,wecandisconnectitfromtheUSBleadandleaveitrunningon
batteries.Evenifthebatteriesgodead,ourdatawillstillbetherethenext
timeweconnectit.
LISTINGPROJECT13

Youwillnoticethatatthetopofthissketchweusethecommand#define
forwhatinthepastwewouldhaveusedvariablesfor.Thisisactuallya
moreefficientwayofdefiningconstantsthatis,valuesthatwillnot
changeduringtherunningofthesketch.Soitisactuallyidealforpin

settingsandconstantssuchasbeta.Thecommand#defineiswhatis
calledapreprocessordirective,andwhathappensisthatjustbeforethe
sketchiscompiled,alloccurrencesofitsnameanywhereinthesketchare
replacedbyitsvalue.Itisverymuchamatterofpersonaltastewhether
youuse#defineoravariable.
Fortunately,readingandwritingEEPROMhappensjust1byteatatime.
So,ifwewanttowriteavariablethatisabyteorachar,wecanjustuse
thefunctionsEEPROM.writeandEEPROM.read,asshowninthe
examplehere:

The0intheparametersforreadandwriteistheaddressintheEEPROM
touse.Thiscanbeanynumberbetween0and1023,witheachaddress
beingalocationwhere1byteisstored.
Inthisprojectwewanttostoreboththepositionofthelastreadingtaken
(inthelastReadingvariable)andallthereadings.Sowewillrecord
lastReadinginthefirstbyteofEEPROM,theloggingperiodasacharacter
1to9,andthentheactualreadingdatainthebytesthatfollow.
Eachtemperaturereadingiskeptinafloat,andifyourememberfrom
Chapter2,afloatoccupies4bytesofdata.Herewehadachoice:We
couldeitherstoreall4bytesorfindawaytoencodethetemperatureinto
asinglebyte.Wedecidedtotakethelatterroutesothatwecanstoreas
manyreadingsaspossibleintheEEPROM.
Thewayweencodethetemperatureintoasinglebyteistomakesome
assumptionsaboutourtemperatures.First,weassumethatany
temperatureinCentigradewillbebetween20and+40.Anythinghigher
orlowerwouldlikelydamageourArduinoboardanyway.Second,we
assumethatweonlyneedtoknowthetemperaturetothenearestquarter
ofadegree.
Withthesetwoassumptions,wecantakeanytemperaturevalueweget
fromtheanaloginput,add20toit,multiplyitby4,andstillbesurethat
wealwayshaveanumberbetween0and240.Sinceabytecanholda
numberbetween0and255,thatjustfitsnicely.
WhenwetakeournumbersoutofEEPROM,weneedtoconvertthem
backtoafloat,whichwecandobyreversingtheprocess,dividingby4,
andthensubtracting20.
Bothencodinganddecodingthevaluesarewrappedupinthefunctions
storeReadingandgetReading.So,ifwedecidedtotakeadifferent
approachtostoringthedata,wewouldonlyhavetochangethesetwo
functions.

Putting It All Together


LoadthecompletedsketchforProject13fromyourArduinoSketchbook
anddownloadittotheboard(seeChapter1).
NowopentheSerialMonitor(Figure520),andfortestpurposes,wewill
setthetemperatureloggertologeveryminutebytyping1intheSerial
Monitor.TheboardshouldrespondwiththemessageSampleperiodset
to:1min.Ifwewantedto,wecouldthenchangethemodetoFahrenheit
bytypingFintotheSerialMonitor.Nowwecancheckthestatusofthe
loggerbytyping?(Figure521).

Figure520 IssuingcommandsthroughtheSerialMonitor.

Figure521 DisplayingtheTemperatureLoggerStatus.
InordertounplugtheUSBcable,weneedtohaveanalternativesourceof
power,suchasthebatteryleadwemadebackinProject6.Youneedto
havethispluggedinandpoweredupatthesametimeastheUSB
connectorisconnectedifyouwanttheloggertokeeploggingafteryou
disconnecttheUSBlead.
Finally,wecantypetheGcommandtostartlogging.Wecanthenunplug
theUSBleadandleaveourloggerrunningonbatteries.Afterwaiting10
or15minutes,wecanplugitbackintoseewhatdatawehavebyopening
theSerialMonitorandtypingtheRcommand,theresultsofwhichare
showninFigure522.Selectallthedata,includingtheTimeand
Tempheadingsatthetop.

Figure522 Datatocopyandpasteintoaspreadsheet.
Copythetexttotheclipboard(pressCTRLConWindowsandLINUX,ALT
ConMacs),openaspreadsheetinaprogramsuchasMicrosoftExcel,and

pasteitintoanewspreadsheet(Figure523).

Figure523 Temperaturedataimportedintoaspreadsheet.
Onceinthespreadsheet,wecanevendrawachartusingourdata.

Summary
Wenowknowhowtohandlevarioustypesofsensorsandinputdevicesto
gowithourknowledgeofLEDs.Inthenextsectionwewilllookata
numberofprojectsthatuselightinvariouswaysandgetourhandson
somemoreadvanceddisplaytechnologies,suchasLCDtextpanelsand
sevensegmentLEDs.

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

Das könnte Ihnen auch gefallen