Tải bản đầy đủ

buiding wireless sensor network using arduino


BuildingWirelessSensorNetworksUsing
Arduino


TableofContents
BuildingWirelessSensorNetworksUsingArduino
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport

Downloadingtheexamplecode
Errata
Piracy
eBooks,discountoffers,andmore
Questions
1.AWorldwithoutWires
XBeeradiohardware
XBeeproductfamilies
Versionsandvariants
OfficialXBeedocumentation
Yourfirsttransmission
UsingtheSparkFunXBeeExplorerUSB
GettingandrunningXCTU
Updatingthefirmware
Failedfirmwareupdates
Configuration
TalkingtotheXBeemodule
Receivingdata
Uploadingthesketch
ConnectingtheXBee
Receivingdata
SwitchingtoAPImode
FirstmoduleinAPImode
Sendingdata
SecondmoduleinAPImode
Startingandjoininganetwork


Moduleaddressing
Networkscanningandremoteconfiguration
TheCommissioningbuttonandLEDs
Makingyournetworksecure
Distributingthenetworkkey
Trustcenterlinkkey
Trustcenterterminologydifferences
Selectingencryptionkeys
Settingupyoursecurenetwork
Disablingnetworkjoining
OtherXBeefamilies
Configurationvalues

Summary
2.CollectingSensorData
Hardwaresetup
SerialonXBee
Handshakingsignals
Voltagelevels
Serialonacomputer
SerialonArduino
XBeeshields
Othershields
Softwaresetup
Examplesketches
Variabletypes
PROGMEMandF()strings
Pointers
Serialportsetup
Thexbee-arduinolibrary
Creatingthesketch
Sendingandreceivingdata
Sendingdata
TheZBTxRequestobjects
Creatingthesketch
Blockingandpolling
Runningthesketch
Callbacks
Callbacktypes
Callbacklimitations
Receivingdata
TheZBRxResponseobjects
Creatingthesketch
Collectingsensordata
ReadingaDHT22sensor


Handlingpacketsusingbinary.h
Buildingandsendingapacket
Constructingapacketusingbinary.h
Creatingthesketch
Receivingandparsingapacket
Parsingapacketusingbinary.h
Creatingthesketch
Troubleshooting
CommunicationwiththeXBeemoduleisnotworking
Modulesarenotjoiningthenetwork
Modulescannottalktoeachother
Summary
3.StoringandVisualizingYourData
Storingyourdatainthecloud
IntroducingBeebotte
Channelsandresources
Security
Accessprotocols
SendingyourdatatoBeebotte
PreparingBeebotte
ConnectingyourArduinototheInternet
Writingthesketch
Visualizingyourdata
Accessingyourdata
Keepingyourdatalocally
Sendingdataovertheserialport
Receivingdataovertheserialport
Summary
4.ControllingtheWorld
Controllingyourheatingand/orcoolingsystem
Replacingthethermostat
Controllingmainspower
Hairdryer–analternative
Controlsystems
Addingsetpointcontrol
Subscribingtoevents
Readingevents
Rememberingsensorreadings
Thermostatcontroller
Controllingarelay
Controllingoff-the-shelfZigBeedevices
ZigBeeprofiles,endpoints,andclusters
ZigBeepublicprofiles
SelectingaZigBeedevice


TalkingtoaZigBeeon/offdevice
Joiningthenetwork
Factoryresetincaseofproblems
Discoveringservices
TheZBExplicitTxRequestobjects
Sendingamessage
TheZBExplicitRxResponseobjects
Receivingmessages
Receivingon/offcommandresponses
MoreZigBeefeatures
Summary
5.StandaloneXBeeOperation
Creatingawindowsensor
Connectingthings
Poweringthemodule
Connectingthewindowsensor
I/Opinnaming
ConfiguringtheXBeemodule
Remotelysamplingthepins
Queryingthepinstate
Automaticallysendingthesampledata
Theconfigurationvalues
Receivingthesamplesonthecoordinator
TheZBRxIoSampleResponseobjects
ReceivingtheI/Osamples
Creatingastandalonerelay
Connectingthings
ConfiguringtheXBeemodule
Remotelytogglinganoutputpin
Summary
6.BatteryPowerandSleeping
Batterypower
Lithium-ionandlithiumpolymerbatteries
Regulators
Savingpower
Powersavingtechniques
Knowingwhattooptimizeandwhentostop
XBeepower-saving
TheXBeesleepmodes
Configuringthenetwork
Thesleepingwindowsensor
Batterypower
Powerusage
Arduinopower-saving


TheXBeeconfiguration
Hardware
PoweringtheArduino
Hardwareconnections
PuttingtheArduinotosleep
Sleepmodes
Wakingup
Creatingthesketch
Powerusage
Summary
Index


BuildingWirelessSensorNetworksUsing
Arduino


BuildingWirelessSensorNetworksUsing
Arduino
Copyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,or
transmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealers
anddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyor
indirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,
PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:October2015
Productionreference:1121015
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78439-558-2
www.packtpub.com


Credits
Author
MatthijsKooijman
Reviewers
AnvirupBasu
RobertoGallea
VincentGijsen
RandySchur
FangzhouXia
CommissioningEditor
NadeemBagban
AcquisitionEditor
SonaliVernekar
ContentDevelopmentEditor
ShaliDeeraj
TechnicalEditor
DanishShaikh
CopyEditor
TasneemFatehi
ProjectCoordinator
KinjalBari
Proofreader
SafisEditing


Indexer
MariammalChettiyar
Graphics
AbhinashSahu
ProductionCoordinator
ConidonMiranda
CoverWork
ConidonMiranda
LayoutCoordinator
ConidonMiranda


AbouttheAuthor
MatthijsKooijmanisanindependentembeddedsoftwaredeveloperwhoisfirmlyconnected
withthemakermovementthroughalocalfablabandhisworkontheArduinoproject.Since
hisyouth,Matthijshasbeeninterestedinmakingthings;forexample,hebuilthisfirst
televisionremotecontrolbeforetheageof10(usingapieceofropetopullonthevolume
slider,notasolutionthathewouldchoosetoday).
Matthijshasafirmbeliefinthemeritsofopensourcesoftwareandenjoyscontributingtothe
softwarethatheuses—bothbycodingandhelpingoutotherusers.Hisworkexperienceis
broad—rangingfromWebdevelopmenttoLinuxdriverhacking,fromtechsupportto
variousformsofwirelessnetworking,butalmostalwaysrelatedtoopensourcesoftwarein
someway.


AbouttheReviewers
AnvirupBasuiscurrentlyastudentpursuinghisB.Techinelectronicsandcommunication
engineeringfromtheSiliguriInstituteofTechnology.Besidesacademics,heisactively
involvedinrobotics,IoT,andmobileapplicationdevelopment.Sincethefirstyear,hehas
beeninvolvedwithMicrosoftasaMicrosoftStudentPartnerandorganizedthreeseminars
andworkshopsonthevariousMicrosofttechnologies,mainlyforWindowsphonesandthe
Windowsappdevelopment.
BeingenthusiasticaboutroboticsandMicrosofttechnologies,hehasdevelopedseveral
robots,bothautonomousandmanual,andacoupleofmanualrobotcontrollers,someof
whicharetheUniversalRobotControllerforWindowsPCsandMark1pilotforWindows
phones.Heisalsointocomputervisionandhasworkedonthedetectionofwildanimals.
AutomatedElephantTrackerisoneofhisprojects,inthejournalnamedInternationaljournal
ofElectronicsandCommunicationEngineering&Technology,underInternationalAssociation
forEngineeringandManagementEducation,whichincludeshisworksonroboticsand
computervision.
Hiswebsite,http://www.avirupbasu.com,holdssomeofhisworkandonemaygetincontact
withhimthere.Beingapart-timeblogger,heblogsabouttopicsheisinterestedin.Currently,
heisworkingonautonomousrobotcontrolusingSONARandGPS.Hedreamsaboutdoing
researchanddevelopmentinhisareasofinterest.
RobertoGallea,PhD,hasbeenacomputerscienceresearchersince2007attheUniversityof
Palermo,Italy.Heiscommittedtoresearchingfieldssuchasmedicalimaging,multimedia,
andcomputervision.In2012,hestartedenhancinghisacademicandpersonalprojectswith
theuseofanaloganddigitalelectronicsandwithaparticularinvolvementintheopensource
hardwareandsoftwareplatforms,suchastheArduino.Besideshisacademicinterests,he
conductspersonalprojects,whichareaimedatproducinghandcrafteditemssuchasmusical
instruments,furniture,andLEDdevicesusingembeddedinvisibleelectronics.Healso
collaborateswithcontemporarydancecompaniesondigitalscenesandcostumedesigning.
VincentGijsenisanall-roundtypeofaguy.Withabachelor'sdegreeinembeddedsystems,a
mastersininformationscience,workexperienceinaBigDatastart-up,andbeingcurrently
activeasasecurityofficerandcybersecurityconsultantinindustrialandinfrastructure
environments,hehasabroadrangeofinterests.Inhissparetime,helikestofiddlewith
lasers,microcontrollers,andotherrelatedelectronics.
IwouldliketothankPacktPublishingfortheirpleasantcooperationandtheirabilityalways
presentinterestingreadstoreviewlike:StormBlueprints:PatternsforDistributedReal-Time
Computation,andArduinoDevelopmentCookbookaswellasmygirlfriend:Lisa-Anne,for
hersupport.
RandySchurisagraduatestudentinmechanicalengineeringattheGeorgeWashington


University.HehasexperienceworkingwiththeArduino,robotics,andrapidprototyping,and
hasworkedonthebookArduinoComputerVisionProgrammingbyPacktPublishingPvt.Ltd.
FangzhouXiaiscurrentlypursuingamaster'sdegreeinmechanicalengineering(ME)atthe
MassachusettsInstituteofTechnology(MIT).Hereceivedhisbachelor'sdegreeinMEfrom
theUniversityofMichigan(UM)andabachelor'sdegreeinelectricalandcomputer
engineeringatShanghaiJiaoTongUniversity(SJTU).Hisareasofinterestinmechanical
engineeringincludesystemcontrol,robotics,productdesign,andmanufacturingautomation.
HisareasofinterestinelectricalengineeringincludeWebapplicationdevelopment,
embeddedsystemimplementation,anddataacquisitionsystemsetup.


www.PacktPub.com


Supportfiles,eBooks,discountoffers,andmore
Forsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePub
filesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprint
bookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat
formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupfora
rangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksand
eBooks.

https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt'sonlinedigitalbook
library.Here,youcansearch,access,andreadPackt'sentirelibraryofbooks.


Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent
Ondemandandaccessibleviaawebbrowser


FreeaccessforPacktaccountholders
IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLib
todayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.


Preface
TheArduinoplatformmakesiteasytogetstartedwithprogrammingandelectronics,but
introducingwirelesscommunicationinyourprojectcangetcomplicatedquickly.TheXBee
wirelessplatformhidesmostofthecomplicateddetailsfromyou,andthisbookprovidesa
step-by-stepguidetousingXBeemoduleswithArduino.
Thisbookdescribesanexamplewirelesssensornetwork,andinvitesyoutobuildthat
networkyourself.Byfollowingthestepsineachchapter,youwillbuildanetworkthatcan
measuretemperatureandhumidityinvariousroomsofyourhouse,collectthatdataonline,
andautomaticallycontrolyourheatingand/orcoolingsystemtomaintaintheproper
temperatureinyourhouse.Thistemperaturecanbeconfiguredthroughanonlinedashboard,
ultimatelyputtingcontrolbackinyourhands.
Alltheconceptsneededtobuildthisexamplenetworkwillbeexplained,soyouwillhavethe
knowledgetobuildyourownprojectusingthesesameconcepts.Conceptsthatareclosely
related,butbeyondthescopeofthisbook,willbementionedandappropriatereferenceswill
begivensoyoucanfindoutmoreifneeded.


Whatthisbookcovers
Chapter1,AWorldwithoutWires,introducestheXBeeplatformandshowshowtousethe
XCTUprogramtocontrolandconfigureXBeemodules.ItcoverstheATandAPImodes,
firmwareupdates,andZigBeenetworkcreationandsecurity.Italsoshowshowtotransmit
yourfirstmessagesbetweentwoXBeemodules.
Chapter2,CollectingSensorData,providesmoredetailsonwiringupXBeemodules,and
introducesthexbee-arduinolibrarythatletsanArduinotakecontrolofanXBeemodule.
Readingasensor,designingapacketformat,andwirelesslytransmittingdataarediscussed;
thus,bytheendofthischapteryouwillhaveabasicwirelesssensornetworkwhereoneor
moreArduinosreadtemperatureandhumiditydataandthisiswirelesslycollectedbyanother
Arduino.
Chapter3,StoringandVisualizingYourData,coversstoringandvisualizingyourcollected
datawiththeBeebottecloudservice,usinganInternet-connectedArduinoandtheMQTT
protocol.Storingandvisualizingyourdataonyourowncomputer,usingaPythonprogram
anddatabase,arealsobrieflydiscussed.
Chapter4,ControllingtheWorld,showshowtoletyournetworkcontrolthingsinadditionto
monitoringthem,suchasheatingand/orcoolingyourhouse.Simpleon/offcontrolis
coveredindetail,eitherusingarelaymoduleconnectedtoanArduino,orusinganoff-theshelfwirelesspowersocketthatsupportstheZigBeeHomeAutomationprotocol.
Chapter5,StandaloneXBeeOperation,letsyouimplementsimpledeviceswithoutusingan
Arduino,bylettingtheXBeemoduledirectlycontrolormeasurethings.Youwillseehowto
simplifytherelaymodulefromChapter4,ControllingtheWorldandaddwindow
open/closeddetectiontoyournetwork.
Chapter6,BatteryPowerandSleeping,discussesoptionsforbattery-poweringyourprojects,
aswellastechniquestoreducethepowerused.Thisincludessomehardwaretechniques,as
wellasapplyingvarioussleepmodestodrasticallyreduceXBeeandArduinopowerusage
whentheyareidle.


Whatyouneedforthisbook
Touploadprograms(sketches)toyourArduinoboards,youwillneedtheArduinoIDE,
whichcanbedownloadedfromhttp://www.arduino.ccVersion1.6.5wasusedinthisbook,but
itisrecommendedtogetthenewestversion.Thisbookassumesyouarealreadyfamiliarwith
thisprogramandknowhowtowriteanduploadasketch,whichwillnotbecoveredinthis
book.
ForconfiguringandinteractingwithXBeemodules,youwillneedtheXCTUprogram,which
canbedownloadedfromhttp://www.digi.com/xctu.Version6.2.0wasusedinthisbook,butit
isrecommendedtogetthenewestversion.Nopriorexperiencewiththisprogramisneeded;
itwillbeintroducedindetail.
TheexamplesketchesinthisbookuseanumberofArduinolibraries.Theselibrariesare:
AltSoftSerialbyPaulStoffregen(version1.3.0)
XBee-ArduinolibrarybyAndrewRapp(version0.6.0)
DHTsensorlibrarybyAdafruit(version1.2.0)
AdafruitMQTTlibrarybyAdafruit(version0.11.1)
AdafruitSleepyDoglibrarybyAdafruit(1.0.0)
AdafruitCC3000librarybyAdafruit(version1.0.3optional)
Ingeneral,itisrecommendedyoudownloadthenewestversionofalibraryusingthelibrary
managerintheArduinoIDE.However,ifyourunintoproblemsbecausealibraryhasmade
changesthatarenotbackwards-compatible,itmightbeusefultotesttheexactsameversionof
alibrarythatwasusedwhenwritingthisbook.Theseversionsareshownabove,butalso
includedintheprovidedcodebundle.
Theintroductionofeachchapterindicateswhathardwareyouwillneedfortheexamplesin
thatchapter.Thisalwaysliststhehardwarerequiredtobuildanexampleonce,sometimesalso
sharingitemsbetweenexamples.Ifyouwanttoexpandyournetworktoincludemultiple
temperaturesensors,windowsensors,andsoon,youwillofcourseneedmultiplesofsome
ofthecomponentslisted.


Whothisbookisfor
ThisbookisforthosewhohavebeenplayingwiththeArduinoplatformandnowwantto
maketheircreationswireless.Thereisnoneedtobeaveteranprogrammer,thoughabasic
understandingoftheArduinoandArduinoprogrammingisassumed.Allexamplesmakeuse
ofready-madehardware,sonosolderingskillsarerequiredand,electronically,thingsare
limitedtojustconnectingafewpinsandwires.Thisbookwillalsoproveusefulforanyone
wantingtointegrateXBeewithmicrocontrollerplatformsotherthantheArduino,sincemost
oftheadviceregardingXBeeisnotspecifictotheArduino.


Conventions
Inthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsof
information.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,foldernames,filenames,fileextensions,pathnames,dummyURLs,user
input,andconfigurationvaluesareshownasfollows:"Sendingapacketishandledbythe
sendPacket()function."
Ablockofcodeissetasfollows:
//theloopfunctionrunsoverandoveragainforever
voidloop(){
digitalWrite(13,HIGH);//turntheLEDon(HIGHisthevoltagelevel)
delay(1000);//waitforasecond
digitalWrite(13,LOW);//turntheLEDoffbymakingthevoltageLOW
delay(1000);//waitforasecond
}

Anycommand-lineinputoroutputiswrittenasfollows:
opensslrand-hex16

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,for
example,inmenusordialogboxes,alsoappearsinboldlikethis:"ClickontheUpdate
Firmwarebuttontoreplacethefirmwareofyourdevice."

Note
Warningsorimportantnotesappearinaboxlikethis.

Tip
Tipsandtricksappearlikethis.


Readerfeedback
Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—
whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitles
thatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail,andmentionthe
book'stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingor
contributingtoabook,seeourauthorguideatwww.packtpub.com/authors.


Customersupport
NowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyouto
getthemostfromyourpurchase.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×