Tải bản đầy đủ (.pdf) (576 trang)

Python programming for arduino pratik desai

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.01 MB, 576 trang )



PythonProgrammingforArduino


TableofContents
PythonProgrammingforArduino
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Downloadingthecolorimagesofthisbook
Errata
Piracy
Questions
1.GettingStartedwithPythonandArduino
IntroductiontoPython
WhyweusePython
Whendoweuseotherlanguages
InstallingPythonandSetuptools


InstallingPython
Linux
Ubuntu
FedoraandRedHat


Windows
MacOSX
InstallingSetuptools
Linux
Windows
MacOSX
Installingpip
InstallingPythonpackages
ThefundamentalsofPythonprogramming
Pythonoperatorsandbuilt-intypes
Operators
Built-intypes
Datastructures
Lists
Tuples
Sets
Dictionaries
Controllingtheflowofyourprogram
Theifstatement
Theforstatement
Thewhilestatement
Built-infunctions
Conversions
Mathoperations

Stringoperations
IntroductiontoArduino
History
WhyArduino?
Arduinovariants
TheArduinoUnoboard
InstallingtheArduinoIDE


Linux
MacOSX
Windows
GettingstartedwiththeArduinoIDE
WhatisanArduinosketch?
Workingwithlibraries
UsingArduinoexamples
Compilinganduploadingsketches
UsingtheSerialMonitorwindow
IntroductiontoArduinoprogramming
Comments
Variables
Constants
Datatypes
Conversions
Functionsandstatements
Thesetup()function
Theloop()function
ThepinMode()function
Workingwithpins
Statements

Summary
2.WorkingwiththeFirmataProtocolandthepySerialLibrary
ConnectingtheArduinoboard
Linux
MacOSX
Windows
Troubleshooting
IntroducingtheFirmataprotocol
WhatisFirmata?
UploadingaFirmatasketchtotheArduinoboard


TestingtheFirmataprotocol
GettingstartedwithpySerial
InstallingpySerial
PlayingwithapySerialexample
BridgingpySerialandFirmata
Summary
3.TheFirstProject–Motion-triggeredLEDs
Motion-triggeredLEDs–theprojectdescription
Theprojectgoal
Thelistofcomponents
Thesoftwareflowdesign
Thehardwaresystemdesign
IntroducingFritzing–ahardwareprototypingsoftware
Workingwiththebreadboard
Designingthehardwareprototype
Testinghardwareconnections
Method1–usingastandaloneArduinosketch
Theprojectsetup

TheArduinosketch
Thesetup()function
Theloop()function
WorkingwithcustomArduinofunctions
Testing
Troubleshooting
Method2–usingPythonandFirmata
Theprojectsetup
WorkingwithPythonexecutablefiles
ThePythoncode
WorkingwithpyFirmatamethods
WorkingwithPythonfunctions
Testing


Troubleshooting
Summary
4.DivingintoPython-ArduinoPrototyping
Prototyping
WorkingwithpyFirmatamethods
SettinguptheArduinoboard
ConfiguringArduinopins
Thedirectmethod
Assigningpinmodes
Workingwithpins
Reportingdata
Manualoperations
Thewrite()method
Theread()method
Additionalfunctions

Upcomingfunctions
PrototypingtemplatesusingFirmata
Potentiometer–continuousobservationfromananaloginput
Connections
ThePythoncode
Buzzer–generatingsoundalarmpattern
Connections
ThePythoncode
DCmotor–controllingmotorspeedusingPWM
Connections
ThePythoncode
LED–controllingLEDbrightnessusingPWM
Connections
ThePythoncode
Servomotor–movingthemotortoacertainangle
Connections


ThePythoncode
PrototypingwiththeI2Cprotocol
ArduinoexamplesforI2Cinterfacing
ArduinocodingfortheTMP102temperaturesensor
ArduinocodingfortheBH1750lightsensor
PyMataforquickI2Cprototyping
InterfacingTMP102usingPyMata
InterfacingBH1750usingPyMata
UsefulpySerialcommands
Connectingwiththeserialport
Readingalinefromtheport
Flushingtheporttoavoidbufferoverflow

Closingtheport
Summary
5.WorkingwiththePythonGUI
LearningTkinterforGUIdesign
YourfirstPythonGUIprogram
TherootwidgetTk()andthetop-levelmethods
TheLabel()widget
ThePackgeometrymanager
TheButton()widget–interfacingGUIwithArduinoandLEDs
TheEntry()widget–providingmanualuserinputs
TheScale()widget–adjustingthebrightnessofanLED
TheGridgeometrymanager
TheCheckbutton()widget–selectingLEDs
TheLabel()widget–monitoringI/Opins
RemakingyourfirstPython-ArduinoprojectwithaGUI
Summary
6.StoringandPlottingArduinoData
WorkingwithfilesinPython
Theopen()method


Thewrite()method
Theclose()method
Theread()method
Thewithstatement–Pythoncontextmanager
UsingCSVfilestostoredata
StoringArduinodatainaCSVfile
Gettingstartedwithmatplotlib
ConfiguringmatplotlibonWindows
ConfiguringmatplotlibonMacOSX

Upgradingmatplotlib
Troubleshootinginstallationerrors
SettingupmatplotlibonUbuntu
Plottingrandomnumbersusingmatplotlib
PlottingdatafromaCSVfile
Plottingreal-timeArduinodata
IntegratingplotsintheTkinterwindow
Summary
7.TheMidtermProject–aPortableDIYThermostat
Thermostat–theprojectdescription
Projectbackground
Projectgoalsandstages
Thelistofrequiredcomponents
Hardwaredesign
Softwareflowforuserexperiencedesign
Stage1–prototypingthethermostat
TheArduinosketchforthethermostat
Interfacingthetemperaturesensor
Interfacingthehumiditysensor
Interfacingthelightsensor
UsingArduinointerrupts
DesigningtheGUIandplotinPython


UsingpySerialtostreamsensordatainyourPythonprogram
DesigningtheGUIusingTkinter
Plottingpercentagehumidityusingmatplotlib
Usingbuttoninterruptstocontroltheparameters
Changingthetemperatureunitbypressingabutton
SwappingbetweentheGUIandtheplotbypressingabutton

Troubleshooting
Stage2–usingaRaspberryPiforthedeployablethermostat
WhatisaRaspberryPi?
InstallingtheoperatingsystemandconfiguringtheRaspberryPi
WhatdoyouneedtobeginusingtheRaspberryPi?
PreparinganSDcard
TheRaspberryPisetupprocess
UsingaportableTFTLCDdisplaywiththeRaspberryPi
ConnectingtheTFTLCDusingGPIO
ConfiguringtheTFTLCDwiththeRaspberryPiOS
OptimizingtheGUIfortheTFTLCDscreen
Troubleshooting
Summary
8.IntroductiontoArduinoNetworking
Arduinoandthecomputernetworking
Networkingfundamentals
ObtainingtheIPaddressofyourcomputer
Windows
MacOSX
Linux
NetworkingextensionsforArduino
ArduinoEthernetShield
ArduinoWiFiShield
ArduinoYún
ArduinoEthernetlibrary


TheEthernetclass
TheIPAddressclass
TheServerclass

TheClientclass
Exercise1–awebserver,yourfirstArduinonetworkprogram
DevelopingwebapplicationsusingPython
Pythonwebframework–web.py
Installingweb.py
YourfirstPythonwebapplication
Essentialweb.pyconceptsfordevelopingcomplexwebapplications
HandlingURLs
TheGETandPOSTmethods
Templates
Forms
Exercise2–playingwithweb.pyconceptsusingtheArduinoserialinterface
RESTfulwebapplicationswithArduinoandPython
DesigningREST-basedArduinoapplications
WorkingwiththeGETrequestfromArduino
TheArduinocodetogeneratetheGETrequest
TheHTTPserverusingweb.pytohandletheGETrequest
WorkingwiththePOSTrequestfromArduino
TheArduinocodetogeneratethePOSTrequest
TheHTTPserverusingweb.pytohandlethePOSTrequest
Exercise3–aRESTfulArduinowebapplication
TheArduinosketchfortheexercise
Theweb.pyapplicationtosupportRESTrequests
Whydoweneedaresource-constrainedmessagingprotocol?
MQTT–Alightweightmessagingprotocol
IntroductiontoMQTT
Mosquitto–anopensourceMQTTbroker
SettingupMosquitto



GettingfamiliarwithMosquitto
GettingstartedwithMQTTonArduinoandPython
MQTTonArduinousingthePubSubClientlibrary
InstallingthePubSubClientlibrary
DevelopingtheArduinoMQTTclient
MQTTonPythonusingpaho-mqtt
Installingpaho-mqtt
Usingthepaho-mqttPythonlibrary
Exercise4–MQTTGatewayforArduino
DevelopingArduinoastheMQTTclient
DevelopingtheMQTTGatewayusingMosquitto
ExtendingtheMQTTGatewayusingweb.py
TestingyourMosquittoGateway
Summary
9.ArduinoandtheInternetofThings
GettingstartedwiththeIoT
ArchitectureofIoTwebapplications
Hardwaredesign
TheIoTcloudplatforms
Xively–acloudplatformfortheIoT
SettingupanaccountonXively
WorkingwithXively
AlternativeIoTplatforms
ThingSpeak
Carriots
DevelopingcloudapplicationsusingPythonandXively
InterfacingArduinowithXively
UploadingArduinodatatoXively
DownloadingdatatoArduinofromXively
AdvancedcodetouploadanddownloaddatausingArduino

Python–uploadingdatatoXively


Thebasicmethodforsendingdata
Uploadingdatausingawebinterfacebasedonweb.py
Python–downloadingdatafromXively
ThebasicmethodforretrievingdatafromXively
Retrievingdatafromtheweb.pywebinterface
Triggers–customnotificationsfromXively
YourowncloudplatformfortheIoT
GettingfamiliarwiththeAmazonAWSplatform
SettingupanaccountonAWS
CreatingavirtualinstanceontheAWSEC2service
Loggingintoyourvirtualinstance
CreatinganIoTplatformontheEC2instance
InstallingthenecessarypackagesonAWS
Configuringthesecurityofthevirtualinstance
Testingyourcloudplatform
TestingtheMosquittoservice
Configuringandtestingbasicsecurity
Uploadingandtestingaprojectontheinstance
Summary
10.TheFinalProject–aRemoteHomeMonitoringSystem
ThedesignmethodologyforIoTprojects
Projectoverview
Theprojectgoals
Theprojectrequirements
Designingsystemarchitecture
Themonitoringstation
Thecontrolcenter

Thecloudservices
DefiningUXflow
Thelistofrequiredcomponents
Definingtheprojectdevelopmentstages


Stage1–amonitoringstationusingArduino
Designingthemonitoringstation
TheArduinosketchforthemonitoringstation
Publishingsensorinformation
Subscribingtoactuatoractions
Programminganinterrupttohandlethepressofabutton
Testing
Stage2–acontrolcenterusingPythonandtheRaspberryPi
Thecontrolcenterarchitecture
ThePythoncodeforthecontrolcenter
CreatingtheGUIusingTkinter
CommunicatingwiththeMosquittobroker
Calculatingthesystem’sstatusandsituationawareness
CommunicatingwithXively
Checkingandupdatingthebuzzer’sstatus
Testingthecontrolcenterwiththemonitoringstation
SettingupthecontrolcenterontheRaspberryPi
Stage3–awebapplicationusingXively,Python,andAmazoncloudservice
Architectureofthecloudservices
PythonwebapplicationhostedonAmazonAWS
Testingthewebapplication
Testingandtroubleshooting
Extendingyourremotehomemonitoringsystem
Utilizingmultiplemonitoringstations

Extendingsensorycapabilities
ImprovingUX
Expandingcloud-basedfeatures
Improvingintelligenceforsituationawareness
Creatinganenclosureforhardwarecomponents
Summary
11.Tweet-a-PowerStrip


Projectoverview
Projectrequirements
Systemarchitecture
Requiredhardwarecomponents
Relays
PowerSwitchTail
Userexperienceflow
Developmentanddeploymentstages
Stage1–asmartpowerstripwithArduinoandrelays
Hardwaredesign
TheArduinocode
Stage2–thePythoncodetoprocesstweets
Pythonsoftwareflow
SettinguptheTwitterapplication
ThePythoncode
Testingandtroubleshooting
Extendingtheprojectwithadditionalfeatures
Summary
Index




PythonProgrammingforArduino



PythonProgrammingforArduino
Copyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:February2015
Productionreference:1230215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78328-593-8
www.packtpub.com



Credits

Author
PratikDesai
Reviewers
JuanRamónGonzález
MarcoSchwartz
JoshVanderLinden
CommissioningEditor
SaleemAhmed
AcquisitionEditor
JamesJones
ContentDevelopmentEditor
PriyankaShah
TechnicalEditor
AnkitaThakur
CopyEditors
JasmineNadar
VikrantPhadke
ProjectCoordinator
MiltonDsouza
Proofreaders
SafisEditing
MariaGould
AmeeshaGreen
PaulHindle
Indexer
MariammalChettiyar
Graphics
AbhinashSahu
ProductionCoordinator
ManuJoseph



CoverWork
ManuJoseph



AbouttheAuthor
PratikDesai,PhD,isthePrincipalScientistandcofounderofaconnecteddevicesstartup,ImbueLabs,wherehedevelopsscalableandinteroperablearchitectureforwearable
devicesandInternetofThings(IoT)platformsduringtheday.Atnight,heleadsthe
developmentofanopensourceIoTinitiative,theSemanticRepositoryofThings.Pratik
has8yearsofresearchanddesignexperienceinvariouslayersoftheIoTandits
predecessortechnologiessuchaswirelesssensornetworks,RFID,andmachine-tomachine(M2M)communication.HisdomainsofexpertisearetheIoT,SemanticWeb,
machinelearning,robotics,andartificialintelligence.
PratikcompletedhisMSandPhDfromWrightStateUniversity,Ohio,andcollaborated
withtheOhioCenterofExcellenceinKnowledge-enabledComputing(Kno.e.sis)during
hisdoctoralresearch.Hisdoctoralresearchwasfocusedondevelopingsituation
awarenessframeworksforIoTdevices,enablingsemanticweb-basedreasoningand
handlingtheuncertaintyassociatedwithsensordata.
Inhispersonallife,PratikisanavidDIYjunkieandlikestogethands-onexperienceon
upcomingtechnologies.Heextensivelyexpresseshisviewsontechnologyandshares
interestingdevelopmentsonTwitter(@chheplo).
Iwouldliketodedicatethebooktomyparents,whowereresponsibleforbuildingthe
foundationofwhatIamtoday.Thebookwouldnothavebeenpossiblewithoutthe
patience,support,andencouragementfrommybelovedwife,Sachi.Iwouldalsoliketo
thankherforlandingherphotographyskillsthatwereusedindevelopmentofsomeofthe
importantimagesusedinthebook.Iwouldalsoliketoextendmysinceregratitudetothe
editorsfortheirvaluablefeedbacks.



×