Getting Started with Python and Raspberry Pi - Dan Nixon - E-Book

Getting Started with Python and Raspberry Pi E-Book

Dan Nixon

0,0
32,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The Raspberry Pi is one of the smallest and most affordable single board computers that has taken over the world of hobby electronics and programming, and the Python programming language makes this the perfect platform to start coding with.
The book will start with a brief introduction to Raspberry Pi and Python. We will direct you to the official documentation that helps you set up your Raspberry Pi with the necessary equipment such as the monitor, keyboard, mouse, power supply, and so on. It will then dive right into the basics of Python programming. Later, it will focus on other Python tasks, for instance, interfacing with hardware, GUI programming, and more. Once you get well versed with the basic programming, the book will then teach you to develop Python/Raspberry Pi applications.
By the end of this book, you will be able to develop Raspberry Pi applications with Python and will have good understanding of Python programming for Raspberry Pi.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 167

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Getting Started with Python and Raspberry Pi
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Your First Steps with Python on the Pi
Installing and setting up Raspbian
Writing to the SD card
Windows
Linux and Mac
Booting the Pi for the first time
The Python development tools
Python 2 versus Python 3
Running some simple Python scripts
Summary
2. Understanding Control Flow and Data Types
Data in Python
Numerical types
Operations on numerical types
String manipulation
String functions
String formatting
String templates
Control flow operators
Using functions
Summary
3. Working with Data Structures and I/O
Data structures
Lists
Creating lists
List operations
Dictionaries
Creating dictionaries
Dictionary operations
Sets
Set operations
Frozen sets
Tuples
Input/output
The os.path module
Reading and writing files
Summary
4. Understanding Object-oriented Programming and Threading
Object-oriented programming
Classes in Python
Operation.py
Calculator.py
Using the module
Inheritance
Threading
Locks
Summary
5. Packaging Code with setuptools
Using packages in your Python code
Importing modules
Installing modules manually
Installing modules using pip
Installing modules using apt
Packaging your own Python modules
Packaging a library
Adding an entry point
Summary
6. Accessing the GPIO Pins
Digital electronics
The GPIO library
Single LED output
PWM output
Multiple outputs
Basic switch
Switch using interrupt
Universal Asynchronous Receiver/Transmitter (UART)
Setting up the serial port
Using pySerial
Additional libraries
Summary
7. Using the Camera Module
Setting up the camera module
Installing and testing the Python library
Writing applications for the camera
A time lapse recorder
A point-and-shoot camera
An image effect randomizer
Summary
8. Extracting Data from the Internet
Using urllib2 to download data
Parsing JSON APIs
Parsing XML APIs
The DOM method
The SAX method
Parsing a web page using BeautifulSoup
Summary
9. Creating Command-line Interfaces
Unit conversion application
Command-line interface
Summary
10. Debugging Applications with PDB and Log Files
The Python debugger
Writing log files
Unit testing
Summary
11. Designing Your GUI with Qt
Setting up the codebase
Building the UI with Qt Designer
Writing the UI code
Launching the UI
Packaging the code
Summary
Index

Getting Started with Python and Raspberry Pi

Getting Started with Python and Raspberry Pi

Copyright © 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 the publisher, 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 the information presented. However, the information contained in this book is sold without warranty, 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 caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2015

Production reference: 1210915

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78355-159-0

www.packtpub.com

Credits

Author

Dan Nixon

Reviewers

Ankit Aggarwal

Neil Broers

Yash Gajera

Bhavyanshu Parasher

David Whale

Commissioning Editor

Dipika Gaonkar

Acquisition Editor

Indrajit Das

Content Development Editor

Zeeyan Pinheiro

Technical Editor

Namrata Patil

Copy Editor

Alpha Singh

Project Coordinator

Suzanne Coutinho

Proofreader

Safis Editing

Indexer

Tejal Soni

Graphics

Jason Monteiro

Production Coordinator

Manu Joseph

Cover Work

Manu Joseph

About the Author

Dan Nixon is a software and electronics engineer living in the north of England. He has past experience of creating software for data analysis, process control, and business intelligence applications. In most of these projects, Python was one of the main languages used.

Dan previously authored another book on the uses of the Raspberry Pi, called Raspberry Pi Blueprints, and has worked on many personal projects that use both Python and the Raspberry Pi.

I would like to thank my mother and father for their support in writing this book and Greg Fenton for his help in testing some of the examples included.

About the Reviewers

Ankit Aggarwal has been fascinated with science and technology since childhood. He likes to experiment and learn new things. He is a software engineer and researcher by profession and loves computer science. He wants to solve problems using technology. His interests include science, technology, academic research, music, photography, entrepreneurship, DIY, movies, anime, and much more.

He has worked in the fields of networking, distributed systems, pervasive/mobile computing, data science, AI, and computer vision; the list goes on. Ankit has authored IEEE Xplore research papers and is an active contributor to and author of several open source projects. He is socially active, blogs occasionally, and maintains his website at http://ankitaggarwal.me.

In his free time, he reads, takes part in competitive programming, captures photos of nature with a lens, and watches TV shows, movies, and anime. When he is not doing these things, he can be found jogging at the nearest ground.

Neil Broers is a Python developer by day and a hardware hacker by night, building his "Smart Home," one Raspberry Pi at a time. He is an avid technical blogger on www.foo.co.za, where he documents his adventures with home automation. In 2014, he presented a talk on the Raspberry Pi and the Internet of Things at the PyConZA conference in South Africa.

Yash Gajera is an embedded software engineer at Insignex in Anand, India. He studied electronics and communication engineering and graduated in 2014 from the A. D. Patel Institute of Technology, Anand. At Insignex, he has worked on fully automated irrigation control systems. He did his final year project on the Internet of Things. It was selected as the best project from the EC department at Gujarat Technological University in 2014. Yash wrote a Python library for the Zigbee protocol to work with the Raspberry Pi. He also has a lot of experience in embedded system development and web technologies.

Bhavyanshu Parasher holds a BTech degree in computer science engineering. He is currently working toward getting a master's degree in computer science. He has been developing web applications since 2011. He also has experience in developing apps for Android and Linux. He has authored and contributed to various open source projects. Apart from computer science, he is also interested in electronics. He has developed various projects using the Raspberry Pi, including service bots, weather monitoring systems, and data analysis automation tools. When he is not writing code, he spends time writing tutorials on his blog at https://bhavyanshu.me.

David Whale is a software developer living in Essex, UK. He started coding as a schoolboy aged 11, inspired by the school science technician to build his own computer from a kit, and quickly progressed to writing machine code programs because they were "small and fast." These early experiments led to some of his code being used in a saleable educational word game when he was only 13.

David has been developing software professionally ever since, mainly writing small and fast code that goes into electronic products, including automated machinery, electric cars, mobile phones, energy meters, and wireless doorbells.

These days, he runs his own software consultancy called Thinking Binaries. He spends much of his time helping design the next wave of the Internet, called the Internet of Things. This means connecting electronic devices to the Internet. The rest of the time, he volunteers for The Institution of Engineering and Technology, running training courses for teachers, designing and running workshops and clubs for school children, and generally being busy with his Raspberry Pi.

David was the technical editor of the book Adventures in Raspberry Pi. He is a coauthor of the book Adventures in Minecraft and is the technical editor of the official Raspberry Pi magazine, the MagPi.

I was really pleased to be asked to review this new book. Dan Nixon has done an excellent job of getting you started with Python and your Raspberry Pi, and he presents the material in an easy-to-follow format. There are lots of fun ideas and building blocks here, which I hope many readers will extend into bigger and more ambitious projects of their own.

www.PacktPub.com

Support 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 and ePub 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 <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

The Raspberry Pi is one of the smallest and most affordable single board computers that has taken over the world of hobby electronics and programming, and the Python programming language makes this the perfect platform to start coding with.

Getting Started with Python and Raspberry Pi will guide you through the process of designing, implementing, and debugging your own Python applications to run on the Raspberry Pi and will help you interact with some of its unique hardware.

What this book covers

Chapter 1, Your First Steps with Python on the Pi, introduces the Python development tools as you install and set them up on the Raspberry Pi after installing the Raspbian operating system.

Chapter 2, Understanding Control Flow and Data Types, introduces you to the control flow and conditional execution operations. Also, the basic data types and the operations that can be performed on them will be covered in this chapter.

Chapter 3, Working with Data Structures and I/O, gives you an overview of the standard Python data structures (for example, list, dict, and tuple) and how they can be used within an application. Also, this chapter will provide an introduction to reading and writing files on the Raspberry Pi's filesystem, including reading from the sysfs to get data such as the current temperature of the processor.

Chapter 4, Understanding Object-oriented Programming and Threading, introduces the concept of object-oriented programming and compares it to the functional programming that has been done up to this point in this book.

Chapter 5, Packaging Code with setuptools, introduces you to the setup tools in the Python package, which are used to package Python applications and libraries for easier installation. This will also include an introduction to the pip utility and PyPi package repository.

Chapter 6, Accessing the GPIO Pins, gives you an overview of the Python library for accessing the GPIO pins on the Raspberry Pi and a brief introduction to some basic electronics needed for the tutorials in the chapter.

Chapter 7, Using the Camera Module, covers using the picamera Python library to interact with the camera module, the options that can be configured using the library, and writing a simple application to record a section of video in several different modes.

Chapter 8, Extracting Data from the Internet, covers the use of several libraries (including requests and urllib2) to connect to webservers and request data, and will include obtaining weather forecasts from an online API. Also, you will be introduced to several third-party libraries that access data from specific sources.

Chapter 9, Creating Command-line Interfaces, covers interaction with applications via the command line using the argparse Python module.

Chapter 10, Debugging Applications with PDB and Log Files, introduces you to the PDB (Python debugger) tool, discusses how it can be used to diagnose and fix issues in Python programs, and covers how the logging Python module can be used to capture information from an application to be used later for debugging. This includes a tutorial in which code with several issues placed into it will be debugged and corrected.

Chapter 11, Designing Your GUI with Qt, provides an introduction to GUI design with Qt using Qt Designer and the Python Qt package.

What you need for this book

You will need:

A Raspberry PiAn SD card (4 GB or higher)

Who this book is for

This book is designed for those who are unfamiliar with the art of Python development and want to get to know their way around the language and the many additional libraries that allow you to get a full application up and running in no time.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any 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 and the errata will be uploaded to our website or added to any list of existing errata under the Errata 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.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Your First Steps with Python on the Pi

In this chapter, we will look at setting up the Raspbian operating system on the Raspberry Pi and have a quick look at the Python development tools that come pre-installed on it, along with looking at some basic ways in which we can execute the Python code.

The only things that are required here are:

A Raspberry PiA USB power source capable of delivering at least 1AUSB keyboardUSB mouseTV with HDMI portAn SD card (or microSD card for the model B+ and Pi 2) of at least 4GB capacityAn SD card readerA USB hub (if you wish to connect more USB devices that there are ports on the Raspberry Pi)Optionally, a WiFi adapter if you want to connect the Pi to your network wirelessly (the list of supported USB WiFi adapters is available at elinux.org/RPi_USB_Wi-Fi_Adapters)

Installing and setting up Raspbian

The first thing we need to do is head to the Raspberry Pi downloads page at https://www.raspberrypi.org/downloads/ and download the latest version of Raspbian. This is a version of the Debian Linux distribution, specifically designed for the Raspberry Pi.

On the downloads page select the Download ZIP option under RASPBIAN.Once the file has downloaded, extract the Zip archive using the default tool on your OS. You should now have a single file ending with the file extension .img.

Writing to the SD card

The next step is to write the just downloaded operating system image to the SD card so that it can be used with the Pi. The way this is done varies depending on the operating system you use on your main PC.

Windows

On Windows, we will use a tool called Win32 Disk Imager to write the OS image to the SD card. This tool can be downloaded from the SourceForge page at sourceforge.net/projects/win32diskimager.

Once downloaded and installed, insert your SD card and open Win32 Disk Imager. You should see a window similar to the following screenshot:

The important thing to check is that a drive letter appears in the Device drop down list. If this does not happen then Win32 Disk Imager has failed to recognize your SD card. In such a case, try it in a different SD card reader. If it still does not work then it could indicate that the card has failed.

Next, browse to select the .img file you had previously extracted from the downloaded Zip archive and click the Write button as shown in the following screenshot, after first making sure that the correct device is selected in the Device drop down list: