Raspberry Pi Cookbook for Python Programmers

Similar documents
Selenium Testing Tools Cookbook

Selenium Testing Tools Cookbook

Learning Embedded Linux Using the Yocto Project

Apache Hive Cookbook. Hanish Bansal Saurabh Chauhan Shrey Mehrotra BIRMINGHAM - MUMBAI

Android SQLite Essentials

TortoiseSVN 1.7. Beginner's Guide. Perform version control in the easiest way with the best SVN client TortoiseSVN.

HTML5 Games Development by Example

Learning PrimeFaces Extensions Development

PHP 5 e-commerce Development

Learning Drupal 6 Module Development

App Inventor 2 Essentials

vsphere Design Best Practices

Mastering FreeSWITCH

Instant Nginx Starter

Foundation Flash MX Applications

Learning Redis. Design efficient web and business solutions with Redis. Vinoo Das BIRMINGHAM - MUMBAI.

DOWNLOAD PDF FUNDAMENTALS OF DATABASE SYSTEMS

Windows Server 2012 Automation with PowerShell Cookbook

Program and Electronic Projects for the SSC, Electron and Spectrum Computers

Training Kit Administering Microsoft SQL Server 2012 Databases. Training Kit EXAM SQL Server 2012 Databases

Raspberry Pi 3 Model B

Learning Python With Raspberry Pi By Alex Bradbury, Ben Everard

C++: C++ And Hacking For Dummies. A Smart Way To Learn C Plus Plus And Beginners Guide To Computer Hacking (C Programming, HTML, Javascript,

Tread-bot with the Retail kit Tread-bot with the Educational kit Programming the robot to move forward Summary 4. Sensors and Control Using sensors

Study Guide. Robert Schmidt Dane Charlton

Raspberry Pi User Guide, 2nd Edition

Join the p2p.wrox.com. Wrox Programmer to Programmer. Beginning PHP 5.3. Matt Doyle

7 Windows Tweaks. A Comprehensive Guide to Customizing, Increasing Performance, and Securing Microsoft Windows 7. Steve Sinchak

RaRa Academy: Raspberry Pi. Karl Heinz Kremer - K5KHK

/smlcodes /smlcodes /smlcodes JIRA. Small Codes. Programming Simplified. A SmlCodes.Com Small presentation. In Association with Idleposts.

UMD: Using mobile IT devices

Surface Go for Education

Software Testing using Visual Studio 2010

BCS Raspberry Pi Launch Events Getting started with Raspberry Pi

Getting Started Guide XC9010 Raspberry Pi Starter Kit

N A T H A N P R E N T I C E I 6 N T P

Programming The Raspberry Pi: Getting Started With Python PDF

How to Become a Successful Working Web Copywriter in Rebecca Matter AWAI Vice President and Director of Online Marketing

Computer Literacy - A Beginners' Guide

Software Testing By Ron Patton

Connect to CCPL

4th Quarter Communicating with Fans and Advertisers Using Databases

Raspberry Pi & GPIO Zero

MAGENTO 2 DEVELOPMENT COOKBOOK BY BART DELVAUX DOWNLOAD EBOOK : MAGENTO 2 DEVELOPMENT COOKBOOK BY BART DELVAUX PDF

Your NOOK, the Barnes & Noble Reader, has many great features, designed to give you the best reading experience, including:

Table of Contents. VisualSVN Server on Windows Integrating Eclipse with code repositories

Python 3 for Absolute Beginners

Away3D 3.6 Essentials

Advanced Embedded Systems

Summary 4. Sample RESS Page WURFL plus screen size detection Dave Olsen's Detector Pure JavaScript screen size test Utility functions Dave Olsen's

acknowledgments...xiii foreword...xiv

AlphaBot2 robot building kit for Raspberry Pi 3 Model B

Your NOOK, the Barnes & Noble Reader, has many great features designed to give you the best reading experience, including:

Digital Devices in the Digital Technologies curriculum (F-10) Steve Allen VCAA Digital Coding Specialist Teacher

XSLT 2.0 and XPath 2.0

e-issn: p-issn:

Manually Transfer Books To Kindle Fire Hd From

Process. Interface Design Introduction. Purpose and Goals of your Website. Module 2. Introduction

Managing Microsoft Exchange Server By Paul Robichaux READ ONLINE

3. Part of Speech Tagging What is Part of speech tagging Stanford tagger Diving deep into a tagger Sequential tagger N-gram tagger Regex tagger Brill

DOWNLOAD OR READ : THE LENOVO WAY PDF EBOOK EPUB MOBI

xiii A. Hayden Lindsey IBM Distinguished Engineer and Director, Studio Tools Foreword

App Description Tips Download

Embedded Technosolutions

CMS Design Using PHP and jquery

Experiments 1 How to set up Raspberry Pi B+ The little computer you can cook into DIY tech projects

What is the Best Way for Children to Learn Computer Programming?

Accessed from 239 Countries. 350,000 Newsletter Subscribers

Modern Perl Ebooks Free

Qualcomm Technologies, Inc.

Linux Command Line and Shell Scripting Bible. Third Edtion

Ding Dong, You've Got Mail! A Lab Activity for Teaching the Internet of Things

MEMBER RATES. CONTACT Joanna Keel

Many Files, One Simple Solution Use Acrobat 7.0 Professional to combine multiple file formats in one easily accessible document

Adventures in Python i

The Gaggle ipad App. The Gaggle ipad App functions best when the ipad is kept in landscape mode.

SABRE for Automotive Infotainment Quick Start Guide. Smart Application Blueprint for Rapid Engineering Based on the i.mx 6 Series

Low Level X Window Programming

print online NEWS BRIEFS MEDIA KIT EMP2018 Electronics Manufacturing & Production Handbook

Oracle Profitability and Cost Management Cloud. November 2017 Update (17.11) What s New

Writing & Executing a Software Validation Protocol: Plain and Simple

CDW.ca/lenovo

User Manual. Delpro CRM

User s Guide. Know Your USA

Manual Leica M9 Digital Camera Price

Pinterest MONDAY, APRIL 22, Basics PAGE 2. How-tos PAGE 3. Advanced PAGE 4

DOWNLOAD OR READ : THE COMPLETE WINDOWS 10 MANUAL UPDATED FOR THE NEW SPRING UPDATE PDF EBOOK EPUB MOBI

The smartest of smartphones

Raspberry Pi User Guide

Oracle SOA Suite Performance Tuning Cookbook

Ipad User Guide Macbook Pro Inch Mid 2012

A Slice of Raspberry Pi

Learning Redis. Design efficient web and business solutions with Redis. Vinoo Das BIRMINGHAM - MUMBAI.

How to Improve Telephone Skills in Fixed Ops!

THEHOMEPAGE. Vero Beach Computer Group. In this Issue... VOLUME 28, ISSUE 3-4 MARCH/APRIL

Build An HTML5 Game: A Developer's Guide With CSS And JavaScript By Karl Bunyan READ ONLINE

Created by John Helfen. Edited by Janice Miller. Autodesk, Inc.

DIGITAL CITIZEN TABLET FUNDAMENTALS

Cooking with Team 279

jquery UI 1.8 The User Interface Library for jquery

Transcription:

Raspberry Pi Cookbook for Python Programmers Over 50 easy-to-comprehend tailor-made recipes to get the most out of the Raspberry Pi and unleash its huge potential using Python Tim Cox BIRMINGHAM - MUMBAI

Raspberry Pi Cookbook for Python Programmers Copyright 2014 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. Raspberry Pi and the Raspberry Pi logo are registered trademarks of the Raspberry Pi Foundation. All other trademarks are the property of their respective owners. First published: April 2014 Production Reference: 2230414 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-662-3 www.packtpub.com Cover Image by Darren Brindley (darrenbrindleyphotography@gmail.com)

Credits Author Tim Cox Reviewers Colin Deady Ian McAlpine Acquisition Editors Pramila Balan Luke Presland Rebecca Pedley Content Development Editor Arvind Koul Technical Editors Shubhangi H. Dhamgaye Novina Kewalramani Rohit Kumar Singh Pratish Soman Copy Editors Janbal Dharmaraj Insiya Morbiwala Aditya Nair Karuna Narayanan Project Coordinator Wendell Palmer Proofreaders Simran Bhogal Kirsty Cox Maria Gould Ameesha Green Paul Hindle Indexer Tejal Soni Graphics Ronak Dhruv Yuvraj Mannari Abhinash Sahu Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat

About the Author Tim Cox lives in England with his wife and two young daughters and works as a software engineer. His passion for programming can be traced back to one Christmas in the mid 1980s when he received a Sinclair Spectrum 48k+ home computer (a joint present with his two elder brothers). By typing out and modifying BASIC programs, while dreaming about building robots, an interest in computers and electronics was sparked, which has never faded. This interest saw him through university, where he earned a BEng in Electronics and Electrical Engineering, and into a career in developing embedded software for a wide range of applications, for automotive, aerospace, and the oil industry, among others. Keen to support the vision behind the Raspberry Pi, reignite engineering in schools, and encourage a new generation of engineers, Tim co-founded the MagPi magazine. Thanks to the dedication and time of the volunteers who contribute to it every month, it continues to have monthly issues and attract an ever-increasing number of readers (and writers) worldwide. Through his site PiHardware.com, Tim produces electronic kits and helps people learn about the Raspberry Pi and hardware interfacing; each of them is supported with detailed instructions and tutorials to help novices build the knowledge and skills for their projects. This is Tim's Þ rst ever book; it mirrors his own experience of discovering the Raspberry Pi and showcasing its fantastic abilities. Writing a book about the Raspberry Pi wouldn't have been possible without the creation itself, so thanks to the Raspberry Pi foundation for their hard work (and good humor) in making it a huge success. The Raspberry Pi community consists of an excellent group of exceptionally helpful people from all over the world, and it has been a pleasure to be involved with it from the start. In particular, I would like to thank The MagPi team that has supported me by reviewing the chapters and helping me achieve the best possible standard. Also thanks to the Pi3D team who worked hard to get their library running with Python 3 for the book. Thanks to my family, particularly my wife Kirsty, who has supported me every step of the way and daily suffered my obsession with the Raspberry Pi. The excitement my daughters, Phoebe and Amelia, have as they discover new things inspires me to share and teach as much as I can.

About the Reviewers Colin Deady started his career in IT in the late 1990s when he discovered software testing. By now he had already fallen in love with computers, thanks to his parents buying him and his brother ZX81 and ZX Spectrum+ home computers in the 1980s. He graduated to the Amiga 1200 in the early 1990s and spent countless hours learning the insides of the operating system. Now with 14 years' experience in testing, he works as a test manager with an emphasis on test automation and extolls the virtues of Agile using Kanban and behaviordriven development to great effect. (Test early, test often; Þ x early, Þ x often.) In his spare time, Colin is part of the editorial team for The MagPi (www.themagpi.com), a community-written magazine for the Raspberry Pi. With several published articles and having reviewed and edited many more, he has built up extensive knowledge of this tiny platform. He can also be found jointly running The MagPi stand at regular Bristol DigiMakers events in the UK, demonstrating projects such as a remote control robot arm, a roverbot, and LED display boards, all of which he has programmed in Python. He currently runs a blog related to the Raspberry Pi at www.rasptut.co.uk. Ian McAlpine was Þ rst introduced to computers with his school's Research Machines RML-380Z and his Physics teacher's Compukit UK101 microcomputer. This was followed by a Sinclair ZX81 home computer and then a BBC Micro Model A microcomputer, which he still has to this day. His interest in computers resulted in him acquiring an MEng in Electronic Systems Engineering from Aston University and an MSc in Information Technology from the University of Liverpool. Ian currently works as a senior product owner at SAP Canada. Being introduced to the Raspberry Pi not only rekindled his desire to "tinker", but also provided him with an opportunity to give back to the community. Consequently, Ian is a very active member of the editorial team for The MagPi, a monthly magazine for the Raspberry Pi, which you can read online or download for free from www.themagpi.com. I would like to thank my darling wife, Louise, and my awesome kids, Emily and Molly, for their patience and support.

www.packtpub.com Support Þ les, ebooks, discount offers and more You might want to visit www.packtpub.com for support Þ les and downloads related to your book. Did you know that Packt offers ebook versions of every book published, with PDF and epub Þ les 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 up for a range of free newsletters and receive exclusive discounts and offers on Packt books and ebooks. TM http://packtlib.packtpub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via 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 nine entirely free books. Simply use your login credentials for immediate access.

Table of Contents Preface 1 Chapter 1: Getting Started with a Raspberry Pi Computer 7 Introduction 7 Connecting the Raspberry Pi 10 Using NOOBS to set up your Raspberry Pi SD card 14 Networking and connecting your Raspberry Pi to the Internet via the LAN connector 24 ConÞ guring your network manually 26 Networking directly to a laptop or computer 28 Networking and connecting your Raspberry Pi to the Internet via a USB Wi-Fi dongle 39 Connecting to the Internet through a proxy server 44 Connecting remotely to the Raspberry Pi over the network using VNC 47 Connecting remotely to the Raspberry Pi over the network using SSH (and X11 Forwarding) 49 Sharing the home folder of the Raspberry Pi with SMB 53 Keeping the Raspberry Pi up to date 55 Chapter 2: Starting with Python Strings, Files, and Menus 57 Introduction 57 Working with text and strings 58 Using Þ les and handling errors 67 Creating a boot-up menu 71 Creating a self-deþ ning menu 74 Chapter 3: Using Python for Automation and Productivity 79 Introduction 79 Using Tkinter to create graphical user interfaces 80 Creating a graphical application Start menu 84

Table of Contents Displaying photo information in an application 89 Organizing your photos automatically 98 Chapter 4: Creating Games and Graphics 103 Introduction 103 Using IDLE3 to debug your programs 104 Drawing lines using a mouse on Tkinter Canvas 107 Creating a bat and ball game 109 Creating an overhead scrolling game 116 Chapter 5: Creating 3D Graphics 125 Introduction 125 Starting with 3D coordinates and vertices 126 Creating and importing 3D models 134 Creating a 3D world to roam in 139 Building 3D maps and mazes 143 Chapter 6: Using Python to Drive Hardware 155 Introduction 155 Controlling an LED 158 Responding to a button 163 A controlled shutdown button 168 The GPIO keypad input 176 Multiplexed color LEDs 182 Chapter 7: Sense and Display Real-world Data 193 Introduction 193 Using devices with the I 2 C bus 194 Reading analog data using an analog-to-digital converter 201 Logging and plotting data 208 Extending the Raspberry Pi GPIO with an I/O expander 216 Sensing and sending data to online services 223 Chapter 8: Creating Projects with the Raspberry Pi Camera Module 229 Introduction 229 Getting started with the Raspberry Pi camera module 230 Using the camera with Python 233 Generating a time-lapse video 241 Creating a stop frame animation 250 Making a QR code reader 260 ii

Table of Contents Chapter 9: Building Robots 267 Introduction 267 Building a Rover-Pi robot with forward driving motors 268 Using advanced motor control 281 Building a six-legged Pi-Bug robot 287 Avoiding objects and obstacles 298 Getting a sense of direction 305 Chapter 10: Interfacing with Technology 317 Introduction 317 Automating your home with remote sockets 318 Using SPI to control an LED matrix 326 Communicating using a serial interface 339 Controlling the Raspberry Pi over Bluetooth 352 Controlling USB devices 357 Appendix: Hardware and Software List 369 Introduction 369 General component sources 370 Hardware list 371 Software list 375 Index 379 iii