As a software developer who has a passion for electronics and astronomy, he started one of the first projects to control a telescope with the Arduino microcontroller by using acomputer w
Trang 3Python Programming for Arduino
Trang 8Prototyping templates using Firmata
Potentiometer – continuous observation from an analog inputConnections
Trang 9Prototyping with the I2C protocol
Arduino examples for I2C interfacing
Arduino coding for the TMP102 temperature sensorArduino coding for the BH1750 light sensor
Trang 10The close() method
The read() method
The with statement – Python context managerUsing CSV files to store data
Trang 11Plotting percentage humidity using matplotlib
Using button interrupts to control the parameters
Changing the temperature unit by pressing a buttonSwapping between the GUI and the plot by pressing a buttonTroubleshooting
Stage 2 – using a Raspberry Pi for the deployable thermostat
What is a Raspberry Pi?
Installing the operating system and configuring the Raspberry PiWhat do you need to begin using the Raspberry Pi?
Trang 14Uploading data using a web interface based on web.pyPython – downloading data from Xively
The basic method for retrieving data from XivelyRetrieving data from the web.py web interface
10 The Final Project – a Remote Home Monitoring SystemThe design methodology for IoT projects
Trang 18www.it-ebooks.info
Trang 20Copyright © 2015 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented However, the information contained in this book is sold withoutwarranty, either express or implied Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be causeddirectly or indirectly by this book
Trang 23Manu Joseph
Trang 25
Pratik Desai, PhD, is the Principal Scientist and cofounder of a connected devices start-up, Imbue Labs, where he develops scalable and interoperable architecture for wearabledevices and Internet of Things (IoT) platforms during the day At night, he leads the
development of an open source IoT initiative, the Semantic Repository of Things Pratikhas 8 years of research and design experience in various layers of the IoT and its
predecessor technologies such as wireless sensor networks, RFID, and machine-to-machine (M2M) communication His domains of expertise are the IoT, Semantic Web,machine learning, robotics, and artificial intelligence
Pratik completed his MS and PhD from Wright State University, Ohio, and collaboratedwith the Ohio Center of Excellence in Knowledge-enabled Computing (Kno.e.sis) duringhis doctoral research His doctoral research was focused on developing situation
awareness frameworks for IoT devices, enabling semantic web-based reasoning and
handling the uncertainty associated with sensor data
In his personal life, Pratik is an avid DIY junkie and likes to get hands-on experience onupcoming technologies He extensively expresses his views on technology and sharesinteresting developments on Twitter (@chheplo)
I would like to dedicate the book to my parents, who were responsible for building thefoundation of what I am today The book would not have been possible without the
patience, support, and encouragement from my beloved wife, Sachi I would also like tothank her for landing her photography skills that were used in development of some of theimportant images used in the book I would also like to extend my sincere gratitude to theeditors for their valuable feedbacks
Trang 27Juan Ramón González is a technical engineer of computer systems and lives in Seville
(Andalusia, Spain) For the past 9 years, he has been working on free software-basedprojects for the regional Ministry of Education by using Python, C++, and JavaScript,among other programming languages
He is one of the main members of the CGA project in Andalusia (Centro de Gestión
Avanzado or Advanced Management Center), which manages a network with more than4,000 servers with Debian and 500,000 client computers that run Guadalinex, a
customized Ubuntu-based operating system for Andalusian schools
As a software developer who has a passion for electronics and astronomy, he started one
of the first projects to control a telescope with the Arduino microcontroller by using acomputer with the Stellarium software and a driver developed with Python to
communicate with the telescope This project’s sources are published on the collaborativeplatform GitHub You can see the whole code and the prototype at
He runs several websites around Arduino, including the Open Home Automation websitethat is dedicated to building home automation systems using open source hardware
Trang 29www.PacktPub.com
Trang 30Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.Did you know that Packt offers eBook versions of every book published, with PDF andePub files available? You can upgrade to the eBook version at www.PacktPub.com and as
a print book customer, you are entitled to a discount on the eBook copy Get in touch with
us at < service@packtpub.com > for more details
At www.PacktPub.com, you can also read a collection of free technical articles, sign upfor a range of free newsletters and receive exclusive discounts and offers on Packt booksand eBooks
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt’s online digitalbook library Here, you can search, access, and read Packt’s entire library of books
www.it-ebooks.info
Trang 31Fully searchable across every book published by PacktCopy and paste, print, and bookmark content
On demand and accessible via a web browser
Trang 32If you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view 9 entirely free books Simply use your login credentials forimmediate access
www.it-ebooks.info
Trang 34In the era of the Internet of Things (IoT), it has become very important to rapidly developand test prototypes of your hardware products while also augmenting them using softwarefeatures The Arduino movement has been the front-runner in this hardware revolution,and through its simple board designs it has made it convenient for anyone to develop DIYhardware projects The great amount of support that is available through the open sourcecommunity has made the difficulties that are associated with the development of a
hardware prototype a thing of the past On the software front, Python has been the crownjewel of the open source software community for a significant amount of time Python issupported by a huge amount of libraries to develop various features, such as graphical userinterfaces, plots, messaging, and cloud applications
This book tries to bring you the best of both hardware and software worlds to help youdevelop exciting projects using Arduino and Python The main goal of the book is to assistthe reader to solve the difficult problem of interfacing Arduino hardware with Pythonlibraries Meanwhile, as a secondary goal, the book also provides you with exercises andprojects that can be used as blueprints for your future IoT projects
The book has been designed in such a way that every successive chapter has increasingcomplexity in terms of material that is covered and also more practical value The bookhas three conceptual sections (getting started, implementing Python features, and networkconnectivity) and each section concludes with a practical project that integrates the
concepts that you learned in that section
The theoretical concepts and exercises covered in the book are meant to give you hands-on experience with Python-Arduino programming, while the projects are designed to teachyou hardware prototyping methodologies for your future projects However, you will stillneed extensive expertise in each domain to develop a commercial product In the end, Ihope to provide you with sufficient knowledge to jump-start your journey in this noveldomain of the IoT
www.it-ebooks.info
Trang 35to create your first Python-Arduino project, which controls different LEDs according tothe detected motion
Chapter 8, Introduction to Arduino Networking, introduces computer networking for
Arduino while utilizing various protocols to establish Ethernet communication betweenthe Python program and Arduino This chapter also explores a messaging protocol calledMQTT, with basic examples This protocol is specifically designed for resource-
Trang 37To begin with, you will just need a computer with one of the supported operating systems,Windows, Mac OS X, or Linux The book requires various additional hardware
designed for Python 2.7 and they have not been tested against Python 3+
Trang 39If you are a student, a hobbyist, a developer, or a designer with little or no programmingand hardware prototyping experience and you want to develop IoT applications, then thisbook is for you
If you are a software developer and interested in gaining experience with hardware
domain, this book will help you to get started If you are a hardware engineer who wants
to learn advance software features, this book can help you to begin with
Trang 41digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second
}
Any command-line input or output is written as follows:
$ sudo easy_install pip
New terms and important words are shown in bold Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: “In the System
Trang 43Feedback from our readers is always welcome Let us know what you think about thisbook—what you liked or disliked Reader feedback is important for us as it helps usdevelop titles that you will really get the most out of
To send us general feedback, simply e-mail < feedback@packtpub.com >, and mention thebook’s title in the subject of your message
If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide at www.packtpub.com/authors
Trang 45Now that you are the proud owner of a Packt book, we have a number of things to helpyou to get the most from your purchase
Trang 47We also provide you with a PDF file that has color images of the screenshots/diagramsused in this book The color images will help you better understand the changes in theoutput You can download this file from:
http://www.packtpub.com/sites/default/files/downloads/5938OS_ColoredImages.pdf
Trang 48Although we have taken every care to ensure the accuracy of our content, mistakes dohappen If you find a mistake in one of our books—maybe a mistake in the text or thecode—we would be grateful if you could report this to us By doing so, you can save otherreaders from frustration and help us improve subsequent versions of this book If you findany errata, please report them by visiting http://www.packtpub.com/submit-errata,
selecting your book, clicking on the Errata Submission Form link, and entering the
details of your errata Once your errata are verified, your submission will be accepted andthe errata will be uploaded to our website or added to any list of existing errata under theErrata section of that title
To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of the book in the
search field The required information will appear under the Errata section.
www.it-ebooks.info
Trang 49Piracy of copyrighted material on the Internet is an ongoing problem across all media AtPackt, we take the protection of our copyright and licenses very seriously If you comeacross any illegal copies of our works in any form on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy
Please contact us at < copyright@packtpub.com > with a link to the suspected piratedmaterial
We appreciate your help in protecting our authors and our ability to bring you valuablecontent
Trang 50If you have a problem with any aspect of this book, you can contact us at
< questions@packtpub.com >, and we will do our best to address the problem
www.it-ebooks.info
Trang 52Chapter 1 Getting Started with Python and Arduino
This chapter introduces the Python programming language and the open source electronicprototyping platform Arduino The first section of the chapter focuses on Python andbriefly describes the benefits of Python along with installation and configuration steps.The remaining part of the chapter describes Arduino and Arduino’s development
environment
At the end of this chapter, you will have configured a programming environment for bothPython and Arduino for your favorite operating system If you are a beginner with either
or both platforms (that is, Python and Arduino), it is advisable that you follow the givensteps in this chapter, as the later chapters will assume that you have the exact
configuration described here If you have previous experience of working with theseplatforms, you can skip to the next chapter
www.it-ebooks.info
Trang 53Since its introduction by Guido van Rossum in 1991, Python has grown into one of themost widely used general-purpose, high-level programming languages, and is supported
by one of the largest open source developer communities Python is an open source
programming language that includes a lot of supporting libraries These libraries are thebest feature of Python, making it one of the most extensible platforms Python is a
dynamic programming language, and it uses an interpreter to execute code at runtimerather than using a compiler to compile and create executable byte codes
The philosophy behind the development of Python was to create flexible, readable, andclear code to easily express concepts The emphasis on using whitespace indentation in aunique way differentiates Python from other popular high-level languages Python
supports functional, imperative, and object-oriented programming with automatic memorymanagement
Trang 54Python is considered to be one of the easiest languages to learn for first-time
programmers Compared to other popular object-oriented languages such as C++ andJava, Python has the following major benefits for programmers:
applications, as well as the development of simple GUI-based applications to plot chartsfrom complex math functions The majority of Python library packages have
systematically maintained the code that was obtained from the community with regularupdates The de facto repository that indexes the largest number of Python packages isPyPI (http://pypi.python.org) PyPI also provides simple ways to install various packages
on your operating system, which will be covered in the upcoming section
While working with the hardware platform, it is necessary to have some means of
communication between the hardware and the computer that you are using for
based communication is the most popular, and it is really simple to establish, especiallyfor the Arduino platform Python provides a library called pySerial that is really easy touse and quick to implement to interface a serial port It is really simple to use similar
development Among the common computer to hardware interfacing methods, serial- port-libraries and Python’s interactive programming abilities to rapidly test and implement yourproject ideas
successful at providing support for these types of applications for years Python has anumber of libraries to support the development of each of the features mentioned here,which are available through PyPI These libraries are open source, easy to use, and widelysupported by the community This makes Python a language of choice for IoT
applications Additionally, Python also has support to create and ship your custom-builtapplications as libraries so that everyone else can also utilize them in their projects This is
a helpful feature if you are developing custom protocols, APIs, or algorithms for your ownhardware products
www.it-ebooks.info