Raspberry Pi for Python Programmers Cookbook - Second Edition - Tim Cox - E-Book

Raspberry Pi for Python Programmers Cookbook - Second Edition E-Book

Tim Cox

0,0
38,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

Over 60 recipes that harness the power of the Raspberry Pi together with Python programming and create enthralling and captivating projects

About This Book

  • Install your first operating system, share files over the network, and run programs remotely
  • Construct robots and interface with your own circuits and purpose built add-ons, as well as adapt off-the-shelf household devices using this pragmatic guide
  • Packed with clear, step-by-step recipes to walk you through the capabilities of Raspberry Pi

Who This Book Is For

Readers are expected to be familiar with programming concepts and Python (where possible Python 3 is used), although beginners should manage with the help of a good Python reference book and background reading. No prior knowledge of the Raspberry Pi or electronics is required; however, for the hardware sections you will need some basic electronic components/household tools to build some of the projects.

What You Will Learn

  • Get the Raspberry Pi set up and running for the first time
  • Remotely connect to the Raspberry Pi and use your PC/laptop instead of a separate screen/keyboard
  • Get to grips with text, files and creating quick menus using Python
  • Develop desktop applications; handle images and process files with ease
  • Make use of graphics and user control to develop your own exciting games
  • Use the Raspberry Pi's powerful GPU to create 3D worlds
  • Take control of the real world and interface with physical hardware, combining hardware and software for your own needs
  • Measure and control processes, respond to real events and monitor through the Internet
  • Learn about the Raspberry Pi hardware inputs/outputs, starting with the basics and beyond
  • Expand the capabilities of the Raspberry Pi with hardware expansion / add-on modules (use analogue inputs, drive servos and motors, and use SPI/I2C)
  • Create your own Pi-Rover or Pi-Hexpod driven by the Raspberry Pi
  • Make use of existing hardware by modifying and interfacing with it using the Raspberry Pi

In Detail

Raspberry Pi cookbook for Python Programmers is a practical guide for getting the most out of this little computer. This book begins by guiding you through setting up the Raspberry Pi, performing tasks using Python 3 and introduces the first steps to interface with electronics. As you work through each chapter you will build up your skills and knowledge and apply them as you progress throughout the book, delving further and further into the unique abilities and features of the Raspberry Pi.

Later, you will learn how to automate tasks by accessing files, build applications using the popular Tkinter library and create games by controlling graphics on screen. You will harness the power of the built-in graphics processor by using Pi3D to generate your own high quality 3D graphics and environments. Connect directly to the Raspberry Pi's hardware pins to control electronics from switching on LEDs and responding to push buttons right through to driving motors and servos. Learn how to monitor sensors to gather real life data and to use it to control other devices, and view the results over the Internet. Apply what you have learnt by creating your own Pi-Rover or Pi-Hexipod robots. Finally, we will explore using many of the purpose built add-ons available for the Raspberry Pi, as well as interfacing with common household devices in new ways.

Style and approach

Written in a cookbook style, the book contains a series of recipes on various topics, ranging from simple to complex. It is an easy-to-follow and step-by-step guide with examples of various feature integration suitable for any search application.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 534

Veröffentlichungsjahr: 2016

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

Raspberry Pi for Python Programmers Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why Subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Safety and using electronics
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with a Raspberry Pi Computer
Introduction
Introducing the Raspberry Pi
What is with the name?
Why Python?
Python 2 and Python 3
Which version of Python should you use?
The Raspberry Pi family – a brief history of Pi
Which Pi to choose?
Connecting the Raspberry Pi
Getting ready
How to do it…
There's more…
Secondary hardware connections
Using NOOBS to set up your Raspberry Pi SD card
Getting ready
How to do it…
How it works…
There's more…
Changing the default user password
Ensuring that you shut down safely
Preparing an SD card manually
Expanding the system to fit in your SD card
Accessing the RECOVERY/BOOT partition
Using the tools to back up your SD card in case of failure
Networking and connecting your Raspberry Pi to the Internet via the LAN connector
Getting ready
How to do it…
There's more…
Using built-in Wi-Fi and Bluetooth on the Raspberry Pi
Getting ready
How to do it…
Connecting to your Wi-Fi network
Connecting to Bluetooth devices
Configuring your network manually
Getting ready
How to do it…
There's more…
Networking directly to a laptop or computer
Getting ready
How to do it…
How it works…
There's more…
Direct network link
See also
Networking and connecting your Raspberry Pi to the Internet via a USB Wi-Fi dongle
Getting ready
How to do it…
There's more…
Using USB wired network adapters
Connecting to the Internet through a proxy server
Getting ready
How to do it…
How it works…
There's more…
Connecting remotely to the Raspberry Pi over the network using VNC
Getting ready
How to do it…
There's more…
Connecting remotely to the Raspberry Pi over the network using SSH (and X11 Forwarding)
Getting ready
How to do it…
How it works…
There's more…
Running multiple programs with X11 Forwarding
Running as a desktop with X11 Forwarding
Running PyGame and Tkinter with X11 Forwarding
Sharing the home folder of the Raspberry Pi with SMB
Getting ready
How to do it…
Keeping the Raspberry Pi up to date
Getting ready
How to do it…
There's more…
2. Starting with Python Strings, Files, and Menus
Introduction
Working with text and strings
Getting ready
How to do it…
How it works…
There's more…
Using files and handling errors
Getting ready
How to do it…
How it works…
Creating a boot-up menu
How to do it…
How it works…
There's more…
Creating a self-defining menu
How to do it…
How it works…
There's more…
Alternative script locations
Adding scripts to PATH
3. Using Python for Automation and Productivity
Introduction
Using Tkinter to create graphical user interfaces
Getting ready
How to do it…
How it works…
Creating a graphical application – Start menu
Getting ready
How to do it…
How it works…
There's more…
Displaying photo information in an application
Getting ready
How to do it…
How it works…
There's more…
Organizing your photos automatically
Getting ready
How to do it…
How it works…
4. Creating Games and Graphics
Introduction
Using IDLE3 to debug your programs
How to do it…
How it works…
Drawing lines using a mouse on Tkinter Canvas
Getting ready
How to do it…
How it works…
Creating a bat and ball game
Getting ready
How to do it…
How it works…
Creating an overhead scrolling game
Getting ready
How to do it…
How it works…
5. Creating 3D Graphics
Introduction
Starting with 3D coordinates and vertices
Getting ready
How to do it…
How it works…
There's more…
Camera
Shaders
Lights
Textures
Creating and importing 3D models
Getting ready
How to do it…
How it works...
There's more…
Creating or loading your own objects
Changing the object's textures and .mtl files
Taking screenshots
Creating a 3D world to roam in
Getting ready
How to do it…
How it works…
Building 3D maps and mazes
Getting ready
How to do it…
How it works...
There's more...
The Building module
Using SolidObjects to detect collisions
6. Using Python to Drive Hardware
Introduction
Controlling an LED
Getting ready
How to do it…
How it works…
There's more…
Controlling the GPIO current
Responding to a button
Getting ready
How to do it…
How it works…
There's more…
Safe voltages
Pull-up and pull-down resistor circuits
Protection resistors
A controlled shutdown button
Getting ready
How to do it…
How it works…
There's more…
Resetting and rebooting Raspberry Pi
Adding extra functions
The GPIO keypad input
Getting ready
How to do it…
How it works…
There's more…
Generating other key combinations
Emulating mouse events
Multiplexed color LEDs
Getting ready
How to do it…
How it works…
There's more…
Hardware multiplexing
Displaying random patterns
Mixing multiple colors
Writing messages using Persistence of Vision
Getting ready
How to do it…
How it works…
7. Sense and Display Real-World Data
Introduction
Using devices with the I2C bus
Getting ready
How to do it...
How it works...
There's more...
Using multiple I2C devices
I2C bus and level shifting
Using just the PCF8591 chip or adding alternative sensors
Reading analog data using an analog-to-digital converter
Getting ready
How to do it...
How it works...
There's more...
Gathering analog data without hardware
Logging and plotting data
Getting ready
How to do it...
How it works...
There's more...
Plotting live data
Scaling and calibrating data
Extending the Raspberry Pi GPIO with an I/O expander
Getting ready
How to do it...
How it works...
There's more…
I/O expander voltages and limits
Using your own I/O expander module
Directly controlling an LCD alphanumeric display
Capturing data in an SQLite database
Getting ready
How to do it...
How it works...
There's more…
CREATE
INSERT
SELECT
WHERE
UPDATE
DELETE
DROP
Viewing data from your own webserver
Getting ready
How to do it...
How it works...
There's more…
Security
Using MySQL instead
Sensing and sending data to online services
Getting ready
How to do it...
How it works...
See also
8. Creating Projects with the Raspberry Pi Camera Module
Introduction
Getting started with the Raspberry Pi camera module
Getting ready
How to do it…
How it works…
Using the camera with Python
Getting ready
How to do it…
How it works…
There's more…
Class member and static functions
Using a USB webcam instead
Additional drivers for the Raspberry Pi camera
See also
Generating a time-lapse video
Getting ready
How to do it…
How it works…
There's more…
Class inheritance and function overriding
Disabling the camera LED
Pi NoIR – taking night shots
Creating a stop frame animation
Getting ready
How to do it…
How it works…
There's more…
Improving the focus
Creating a hardware shutter
Making a QR code reader
Getting ready
How to do it…
How it works…
There's more…
Generating QR codes
See also
Discover and experiment with OpenCV
Getting ready
How to do it…
How it works…
Color detection with OpenCV
Getting ready
How to do it…
How it works…
There's more…
Performing motion tracking with OpenCV
Getting ready
How to do it…
How it works…
There's more…
9. Building Robots
Introduction
Building a Rover-Pi robot with forward driving motors
Getting ready
How to do it…
How it works…
There's more…
Darlington array circuits
Transistor and relay circuits
Tethered or untethered robots
Rover kits
Using advanced motor control
Getting ready
How to do it…
How it works…
There's more…
Motor speed control using PWM control
Using I/O expanders
Building a six-legged Pi-Bug robot
Getting ready
How to do it…
How it works…
Controlling the servos
The servo class
Learning to walk
The Pi-Bug code for walking
Controlling servos directly with Servoblaster
Getting ready
How to do it…
How it works…
Using an Infra-Red Remote Control with your Raspberry Pi
Getting Ready
How to do it…
There's more…
Avoiding objects and obstacles
Getting ready
How to do it…
How it works…
There's more…
Ultrasonic reversing sensors
Getting a sense of direction
Getting ready
How to do it…
How it works…
There's more…
Calibrating the compass
Calculating the compass bearing
Saving the calibration
Driving the robot using the compass
10. Interfacing with Technology
Introduction
Automating your home with remote sockets
Getting ready
How to do it...
How it works...
There's more...
Sending RF control signals directly
Extending the range of the RF Transmitter
Determining the structure of the remote control codes
Using SPI to control an LED matrix
Getting ready
How to do it…
How it works...
There's more...
Daisy-chain SPI configuration
Communicating using a serial interface
Getting ready
How to do it...
How it works...
There's more...
Configuring a USB to RS232 device for the Raspberry Pi
RS232 signals and connections
Using the GPIO built-in serial pins
The RS232 loopback
Controlling the Raspberry Pi over Bluetooth
Getting ready
How to do it...
How it works...
There's more...
Configuring Bluetooth module settings
Controlling USB devices
Getting ready
How to do it...
How it works...
There's more...
Controlling similar missile-type devices
Robot arm
Taking USB control further
A. Hardware and Software List
Index

Raspberry Pi for Python Programmers Cookbook - Second Edition

Raspberry Pi for Python Programmers Cookbook - Second Edition

Copyright © 2016 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: April 2014

Second edition: September 2016

Production reference: 1270916

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-832-6

www.packtpub.com

Credits

Author

Tim Cox

Reviewer

Dan Purdy

Commissioning Editor

Kartikey Pandey

Acquisition Editor

Vivek Anantharaman

Content Development Editor

Siddhesh Salvi

Technical Editor

Danish Shaikh

Copy Editor

Vibha Shukla

Project Coordinator

Nidhi Joshi

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

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 contributed to it every month, it has become the official magazine for the Raspberry Pi and continues 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 first 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 Reviewer

Dan Purdy is a Front End Developer at a digital agency in London. His fascination with computers started early on when he first caught sight of a ZX Spectrum loading a program from a tape. When he first got his hands on a Raspberry Pi, he started building a number of tools, games, and applications sometimes to help with the day job but primarily for fun.

Dan currently works on a variety of projects, from product prototypes and e-commerce sites to enterprise-level web applications, while continuing to experiment with new frameworks, technologies and his Raspberry Pi.

Dan was previously a technical reviewer for Raspberry Pi Gaming – Second Edition and Wordpress 4.0 Site Blueprints.

www.PacktPub.com

eBooks, discount offers, and more

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://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why Subscribe?

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

Preface

Since the release of the Raspberry Pi computer in February 2012, millions of people have been introduced to a new way of computing. Modern home computers, tablets, and phones are typically focused on providing content to the user to consume, either as a passive viewer or through basic interaction via games and activities.

However, the Raspberry Pi turns this concept on its head. The idea is that the user provides the input and the imagination, and the Raspberry Pi becomes an extension of their creativity. The Raspberry Pi provides a simple, low-cost platform that you can use to experiment with and play with your own ideas. It won't feed you information; it will let you discover it firsthand.

This book takes everything I have found exciting and interesting with the Raspberry Pi and puts it in an easy-to-follow format.

I hope that people will read this book and start their own Raspberry Pi journey; it has so much to offer, and the book is aimed squarely at showing off what you can achieve with it.

Like any good cookbook, the pages should be worn and used, and it should be something that is always being pulled off the shelf to refer to. I hope it will become your own, personal, go-to reference.

What this book covers

Chapter 1, Getting Started with a Raspberry Pi Computer, introduces the Raspberry Pi and explores the various ways that it can be set up and used, including how it can be used on a network and connected to remotely with another computer.

Chapter 2, Starting with Python Strings, Files, and Menus, guides us on how to take our first steps using Python 3, start with the basics, manipulate text, use files, and create menus to run our programs.

Chapter 3, Using Python for Automation and Productivity, explains the use of graphical user interfaces to create our own applications and utilities.

Chapter 4, Creating Games and Graphics, explains how to create a drawing application and graphical games using the Tkinter Canvas.

Chapter 5, Creating 3D Graphics, discusses how we can use the hidden power of the Raspberry Pi's graphical processing unit to learn about 3D graphics and landscapes and produce our very own 3D maze for exploration.

Chapter 6, Using Python to Drive Hardware, establishes the fact that to experience the Raspberry Pi at its best, we really have to use it with our own electronics. It discusses how to create circuits with LEDs and switches, and use them to indicate the system status and provide control. Finally, it shows us how to create our own game controller, light display and a persistence of vision text display.

Chapter 7, Sense and Display Real-World Data, explains the use of an analog-to-digital convertor to provide sensor readings to the Raspberry Pi. We discover how to store and graph the data in real time, as well as display it on an LCD text display. Next we record the data in a SQL database and display it in our own webserver. Finally, we transfer the data to the Internet, which will allow us to view and share the captured data anywhere in the world.

Chapter 8, Creating Projects with the Raspberry Pi Camera Module, teaches us how to use the Raspberry Pi camera module, creating our own applications to produce time-lapse videos, stop-frame animations, and a bedtime book reader controlled with QR codes. Additionally we make use of the immensely powerful image processing library OpenCV to perform color recognition and object (or in this case, a tortoise) tracking.

Chapter 9, Building Robots, takes you through building two different types of robots (a Rover- Pi and a Pi-Bug), plus driving a servo-based robot arm. We look at motor and servo control methods, using sensors, and adding a compass sensor for navigation.

Chapter 10, Interfacing with Technology, teaches us how to use the Raspberry Pi to trigger remote mains sockets, with which we can control household appliances. We learn how to communicate with the Raspberry Pi over a serial interface and use a smartphone to control everything using Bluetooth. Finally, we look at creating our own applications to control USB devices.

Appendix, Hardware and Software List, provides us with the full list of the hardware components and modules used in the book, along with suitable places to purchase them from. A full list of the software used is also provided, along with links to documentation.

What you need for this book

This book focuses on using the Raspberry Pi with Python 3; therefore, a basic Raspberry Pi setup is required. Chapters 1 to 5 of this book make use of the Raspberry Pi only; no additional hardware is required beyond a standard setup.

The standard setup will consist of a Raspberry Pi (Model A or Model B, Version 1, 2 or 3); an SD card installed with Raspbian; a suitable micro USB power supply; and an HDMI-compatible screen, keyboard, and mouse. You will also be required to download and install various software packages; therefore, the Raspberry Pi should have a working internet connection.

Chapter 1, Getting Started with a Raspberry Pi Computer, also describes how to use the screen/keyboard/mouse of a laptop or another computer to access the Raspberry Pi (you just need a network cable and power).

Chapter 6, Using Python to Drive Hardware, and Chapter 7, Sense and Display Real-World Data, show how electronic components can be connected to the Raspberry Pi's interfaces. These components will be needed in order to complete these chapters.

Chapter 8, Creating Projects with the Raspberry Pi Camera Module, requires the Raspberry Pi camera module for each of the projects (although a compatible USB webcam could be substituted by adjusting the code).

Chapter 9, Building Robots, uses a range of hardware and electronics to build your own robots. You can either use your own parts or a suitable kit for this.

Chapter 10, Interfacing with Technology, shows how additional hardware can be connected to the interfaces of the Raspberry Pi using various modules and kits.

A full list of the hardware used (and the possible places to purchase it from) has been provided in the Appendix, Hardware and Software List.

Who this book is for

This book is intended for anyone who wants to make the most of the Raspberry Pi experience. The book gradually introduces Python, starting with the basics and moving towards more advanced topics, such as using 3D graphics and interfacing with hardware.

Although you do not need to be familiar with Python, the Raspberry Pi, or electronics, this book touches on a wide range of topics. Ideally, you should give each chapter a try, see what you enjoy, and use that as a starting point to discover and learn more.

Each example in the book consists of full setup instructions, complete code listings, and a walk-through of what you did and why. This will allow you to get results quickly, and most importantly, understand how you achieved them.

All the examples are written using Python 3, with clear and detailed explanations of how everything works so that you can adapt and use all the information in your own projects.

As you progress through the book, it will explain how to structure and develop your code efficiently, building on the various techniques that can be applied as you progress. By the end, you will have a toolset of skills that you can apply to whatever your imagination inspires you to do.

Safety and using electronics

This book encourages you to experiment and connect your own circuits to the general-purpose input/output Raspberry Pi GPIO pins. This is an excellent way to learn about electronics and software at the same time. However, it is important to remember that the GPIO pins are unprotected, and if wired incorrectly, can easily be damaged or even cause the Raspberry Pi to stop working altogether. Therefore, care should be taken to correctly follow the instructions and wiring diagrams and check everything carefully before switching the Raspberry Pi on.

All the circuits, modules, and components described in this book are intended as demonstration examples only. They have not been tested for extended use and should not be left unattended or should not be used in safety-critical applications without adequate safeguards in place. Remember that all electronics must undergo rigorous safety testing to ensure that in the event of failure, there will be no risk of harm to people or property.

You should never attempt to modify or alter devices that are connected to mains electricity without proper training, and you must never directly connect any homemade devices to the mains supply.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "On a freshly formatted or new SD card, copy the contents of the NOOBS_vX.zip file."

A block of code is set as follows:

network={ ssid="theSSID" key_mgmt=NONE }

Any command-line input or output is written as follows:

sudo mount –t vfat /dev/mmcblk0p1 ~/recovery

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "For OS X or Linux, click on Terminal to open a connection to the Raspberry Pi."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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

To send us general feedback, simply e-mail <[email protected]>, and mention the book'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 or contributing to a book, see our author guide at 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 this book 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.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Raspberry-Pi-for-Python-Programmers-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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 copyrighted 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

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting Started with a Raspberry Pi Computer

In this chapter, we will cover the following recipes:

Connecting the Raspberry PiUsing NOOBS to set up your Raspberry Pi SD cardNetworking and connecting your Raspberry Pi to the Internet via the LAN connectorUsing built-in Wi-Fi and Bluetooth on the Raspberry PiConfiguring your network manuallyNetworking directly to a laptop or computerNetworking and connecting your Raspberry Pi to the Internet via a USB Wi-Fi dongleConnecting to the Internet through a proxy serverConnecting remotely to the Raspberry Pi over the network using VNCConnecting remotely to the Raspberry Pi over the network using SSH (and X11 Forwarding)Sharing the home folder of the Raspberry Pi with SMBKeeping the Raspberry Pi up to date

Introduction

This chapter introduces the Raspberry Pi and the process to set it up for the first time. We will connect the Raspberry Pi to a suitable display, power, and peripherals. We will install an operating system on an SD card. This is required for the system to boot. Next, we will ensure that we can connect successfully to the Internet through a local network.

Finally, we will make use of the network to provide ways to remotely connect to and/or control the Raspberry Pi from other computers and devices, as well as to ensure that the system is kept up to date.

Once you have completed the steps within this chapter, your Raspberry Pi will be ready for you to use for programming. If you already have your Raspberry Pi set up and running, ensure that you take a look through the following sections as there are many helpful tips.

Introducing the Raspberry Pi

The Raspberry Pi is a single-board computer created by the Raspberry Pi Foundation, a charity formed with the primary purpose of reintroducing low-level computer skills to children in the UK. The aim was to rekindle the microcomputer revolution of the 1980s, which produced a whole generation of skilled programmers.

Even before the computer was released at the end of February 2012, it was clear that the Raspberry Pi had gained a huge following worldwide and, at the time of writing this book, has sold over 10 million units. The following image shows several different Raspberry Pi Models:

Raspberry Pi Model 3B, Model A+, and Pi Zero

What is with the name?

The name, Raspberry Pi, was the combination of the desire to create an alternative fruit-based computer (such as Apple, BlackBerry, and Apricot) and a nod to the original concept of a simple computer that can be programmed using Python (shortened to Pi).

In this book, we will take this little computer, find out how to set it up, and then explore its capabilities chapter by chapter using the Python programming language.

Why Python?

It is often asked, "Why has Python been selected as the language to use on the Raspberry Pi?" The fact is that Python is just one of the many programming languages that can be used on the Raspberry Pi.

There are many programming languages that you can choose, from high-level graphical block programming, such as Scratch, to traditional C, right down to BASIC, and even raw Machine Code Assembler. A good programmer often has to be code multilingual to be able to play to the strengths and weaknesses of each language in order to best meet the needs of their desired application. It is useful to understand how different languages (and programming techniques) try to overcome the challenge of converting "what you want" into "what you get" as this is what you are trying to do as well while you program.

Python has been selected as a good place to start when learning about programming, by providing a rich set of coding tools while still allowing simple programs to be written without fuss. This allows beginners to gradually be introduced to the concepts and methods on which modern programming languages are based without requiring them to know it all from the start. It is very modular with lots of additional libraries that can be imported to quickly extend the functionality. You will find that over time, this encourages you to do the same, and you will want to create your own modules that you can plug into your own programs, thus taking your first steps into structured programming.

Like all programming languages, Python isn't perfect; things such as adding a space at the start of a line will often break your code (indents matter a lot in Python; they define how blocks of code are grouped together). Generally, Python is slow; since it is interpreted, it takes time to create a module while it is running the program. This can be a problem if you need to respond to time critical events. However, you can precompile Python or use modules written in other languages to overcome this. It hides the details; this is both an advantage and disadvantage. It is excellent for beginners but can be difficult when you have to second-guess aspects such as data-types. However, this in turn forces you to consider all the possibilities, which can be a good thing.

Python 2 and Python 3

A massive source of confusion for beginners is that there are two versions of Python on the Raspberry Pi (Version 2.7 and Version 3.4), which are not compatible with one another, so code written for Python 2.7 may not run with Python 3.4 (and vice versa).

The Python Software Foundation is continuously working to improve and move forward with the language, which sometimes means they have to sacrifice backward compatibility in order to embrace new improvements (and importantly, remove redundant and legacy ways of doing things).

Note

Supporting both Python 2 or Python 3

There are many tools that will ease the transition from Python 2 to Python 3, including converters such as 2to3, which will parse and update your code to use Python 3 methods. This process is not perfect, and in some cases, you'll need to manually rewrite sections and fully retest everything. You can write the code and libraries that will support both. The import __future__ statement allows you to import the friendly methods of Python 3 and run them using Python 2.7.

Which version of Python should you use?

Essentially, the selection of which version to use will depend on what you intend to do. For instance, you may require Python 2.7 libraries, which are not yet available for Python 3.4. Python 3 has been available since 2008, so these tend to be older or larger libraries that have not been translated. In many cases, there are new alternatives to legacy libraries; however, their support can vary.

In this book, we have used Python 3.4, which is also compatible with Python 3.3 and 3.2.

The Raspberry Pi family – a brief history of Pi

Since its release, the Raspberry Pi has come in various iterations, featuring both small and large updates and improvements to the original Raspberry Pi Model B unit. Although it can be confusing at first, there are three basic types of Raspberry Pi available (and one special model).

The main flagship model is called Model B. This has all the connections and features, as well as the maximum RAM and the latest processor. Over the years, there have been several versions, most notably Model B (which had 256 MB and then 512 MB RAM) and then Model B+ (which increased the 26-pin GPIO to 40 pins, switched to using a micro SD card slot, and had four USB ports instead of two). These original models all used the Broadcom BCM2835 SOC (short for System On Chip), consisting of a single core 700 MHz ARM11 and VideoCore IV GPU (short for Graphical Processing Unit).

The release of the Raspberry Pi 2 Model B (also referred to as 2B) in 2015 introduced a new Broadcom BCM2836 SOC, providing a quad-core 32-bit ARM Cortex A7 1.2 GHz processor and GPU, with 1 GB of RAM. The improved SOC added support for Ubuntu and Windows 10 IoT. Finally we had the latest Raspberry Pi 3 Model B, using another new Broadcom BCM2837 SOC, which provides a quad-core 64-bit ARM Cortex-A53 and GPU, alongside adding on-board Wi-Fi and Bluetooth.

Model A has always been targeted as a cut-down version. While having the same SOC as Model B, there are limited connections consisting of a single USB port and no wired network (LAN). Model A+ again added more GPIO pins and a micro SD slot. However, the RAM was later upgraded to 512 MB of RAM and again only a single USB port/no LAN. The Broadcom BCM2835 SOC on Model A has not been updated so far (so is still a single core ARM11); however, a Model 3A (most likely using the BCM2837) is expected 2016/2017.

The Pi Zero is an ultra-compact version of the Raspberry Pi intended for embedded applications where cost and space are a premium. It has the same 40-pin GPIO and micro SD card slot as the other models, but lacks the on-board display (CSI and DSI) connection. It does still have HDMI (via a mini-HDMI) and a single micro USB OTG (on-the-go) connection. Although not present in the first revision of the Pi Zero, the most recent model also includes a CSI connection for the on-board camera.

Note

The Pi Zero was famously released in 2015 by being given away with the Raspberry Pi foundations magazine The MagPi, giving the magazine the kudos of being the first magazine to give away a computer on its cover! This did make me rather proud since (as you may have read in my biography at the start of this book) I was one of the founders of the magazine.

The special model is known as the compute module. This takes the form of a 200-pin SO-DIMM card. It is intended for industrial use or within commercial products, where all the external interfaces would be provided by a host/motherboard, into which the module would be inserted. Example products include the Slice media player (http://fiveninjas.com) and the Otto camera. The current module uses the BCM2835, although an updated compute module (CM3) is expected in 2016.

The Raspberry Pi Wikipedia page provides a full list of the all different variants and their specifications:

https://en.wikipedia.org/wiki/Raspberry_Pi#Specifications

Which Pi to choose?

All sections of this book are compatible will all current versions of the Raspberry Pi, but Model 3B is recommended as the best model to start with. This offers the best performance (particularly useful for the GPU examples in Chapter 5, Creating 3D Graphics, and the OpenCV examples used in Chapter 8, Creating Projects with the Raspberry Pi Camera Module), lots of connections, and built-in Wi-Fi, which can be very convenient.

The Pi Zero is recommended for projects where you want low power usage or reduced weight/size but do not need the full processing power of Model 3B. However, due to its ultra-low cost, the Pi Zero is ideal for deploying a completed project after you have developed it.

Connecting the Raspberry Pi

There are many ways to wire up the Raspberry Pi and use the various interfaces to view and control content. For typical use, most users will require power, display (with audio), and a method of input such as keyboard and mouse. To access the Internet, refer to the Networking and connecting your Raspberry Pi to the Internet via the LAN connector or Using built-in Wi-Fi and Bluetooth on the Raspberry Pi recipes.

Getting ready

Before you can use your Raspberry Pi, you will need an SD card with an operating system installed or with the New Out Of Box System (NOOBS) on it, as discussed in the Using NOOBS to set up your Raspberry Pi SD card recipe.

The following section will detail the types of devices you can connect to the Raspberry Pi and, importantly, how and where to plug them in.

As you will discover later, once you have your Raspberry Pi set up, you may decide to connect remotely and use it through a network link, in which case you only need power and a network connection. Refer to the following sections: Connecting remotely to the Raspberry Pi over the network using VNC and Connecting remotely to the Raspberry Pi over the network using SSH (and X11 Forwarding).

How to do it…

The layout of the Raspberry Pi is shown in the following figure:

The Raspberry Pi connection layout (Model 3 B, Model A+, and Pi Zero)

The description of the preceding figure is as follows:

Display: The Raspberry Pi supports the following three main display connections; if both HDMI and Composite video are connected, it will default to HDMI only.
HDMI

For best results, use a TV or monitor that has an HDMI connection, thus allowing the best resolution display (1080p) and also digital audio output. If your display has a DVI connection, you may be able to use an adapter to connect through the HDMI. There are several types of DVI connections; some support analogue (DVI-A), some digital (DVI-D), and some both (DVI-I). The Raspberry Pi is only able to provide a digital signal through the HDMI, so an HDMI-to-DVI-D adapter is recommended (shown with a tick mark in the following screenshot). This lacks the four extra analogue pins (shown with a cross mark in the following screenshot), thus allowing it to fit into both DVI-D and DVI-I type sockets:

HDMI-to-DVI connection (DVI-D adaptor)

If you wish to use an older monitor (with a VGA connection), an additional HDMI-to-VGA converter is required. The Raspberry Pi also supports a rudimentary VGA adaptor (VGA Gert666 Adaptor), which is driven directly off of the GPIO pins. However, this does use up all but 4 pins of the 40-pin header (older 26-pin models will not support the VGA output).

Analogue

An alternative display method is to use the analogue composite video connection (via the phono socket); this can also be attached to an S-Video or European SCART adapter. However, the analogue video output has a maximum resolution of 640 x 480 pixels, so it is not ideal for general use.

3.5mm phono analogue connections

When using the RCA connection or a DVI input, audio has to be provided separately by the analogue audio connection. To simplify the manufacturing process (by avoiding through-hole components), the Pi Zero does not have analogue audio or an RCA socket for analogue video (although they can be added with some modifications).

Direct Display DSI

A touch display produced by the Raspberry Pi Foundation will connect directly into the DSI socket. This can be connected and used at the same time as the HDMI or analogue video output to create a dual display setup.

Stereo Analogue Audio (all except Pi Zero): This provides an analogue audio output for headphones or amplified speakers. The audio can be switched via the Raspberry Pi configuration tool on the desktop between analog (Stereo Socket) and digital (HDMI), or via the command line using amixer or alsamixer.

Note

To find out more information about a particular command in the terminal, you can use the following man command before the terminal reads the manual (most commands should have one):

man amixer

Some commands also support the --help option for more concise help, shown as follows:

amixer --help
Network (excluding models A and Pi Zero): The network connection is discussed in the Networking and connecting your Raspberry Pi to the Internet via the LAN connectorrecipe later in this chapter. If we use the Model A Raspberry Pi, it is possible to add a USB network adapter to add wired or even wireless networking (refer to the Networking and connecting your Raspberry Pi to the Internet via a USB Wi-Fi dongle recipe).Onboard Wi-Fi and Bluetooth (Model 3 B only):The Model 3 B has built-in 802.11n Wi-Fi and Bluetooth 4.1; see the Using the built-in Wi-Fi and Bluetooth on the Raspberry Pi recipe.USB (x1 Model A/Zero, x2 Model 1 B, x4 Model 2 B and 3 B)—using a keyboard and mouse:

The Raspberry Pi should work with most USB keyboards and mice available. You can also use wireless mice and keyboards, which use RF Dongles. However, additional configuration is required for items that use the Bluetooth dongles.

If there is a lack of power supplied by your power supply or the devices are drawing too much current, you may experience the keyboard keys appearing to stick, and in severe cases, corruption of the SD card.

Note

USB power can be more of an issue with the early Model B revision 1 boards that were available prior to October 2012. They included additional Polyfuses on the USB output and tripped if an excess of 140 mA was drawn. The Polyfuses can take several hours or days to recover completely, thus causing unpredictable behavior to remain even when the power is improved.

You can identify a revision 1 board as it lacks the four mounting holes that are present the later models.

Debian Linux (upon which Raspbian is based) supports many common USB devices, such as flash storage drives, hard disk drives (external power may be required), cameras, printers, Bluetooth, and Wi-Fi adapters. Some devices will be detected automatically while others will require drivers to be installed.

Micro USB Power: The Raspberry Pi requires a 5V power supply that can comfortably supply at least 1000 mA (1,500 mA or more is recommended, particularly with the more power-hungry Model 2 and 3) with a micro USB connection. It is possible to power the unit using portable battery packs, such as the ones suitable for powering or recharging tablets. Again, ensure that they can supply 5V at 1000 mA or over.

You should aim to make all other connections to the Raspberry Pi before connecting the power. However, USB devices, audio, and network may be connected and removed while it is running without problems.

There's more…

In addition to the standard primary connections you would expect to see on a computer, the Raspberry Pi also has a number of other connections.

Secondary hardware connections

Each of the following connections provides additional interfaces for the Raspberry Pi:

20 x 2 GPIO pin header (Model A+, B+, 2 B, 3 B, and Pi Zero): This is the main 40-pin GPIO header of the Raspberry Pi used for interfacing directly with hardware components. We use this connection in Chapters 6, 7, 9, and 10. The recipes in this book are also compatible with older models of the Raspberry Pi that have a 13 x 2 GPIO pin header.P5 8 x 2 GPIO pin header (Model 1 B revision 2.0 only): We do not use this in the book.Reset connection: This is present on later models (no pins fitted). A reset is triggered when Pin 1 (reset) and Pin 2 (GND) are connected together. We use this in the A controlled shutdown button recipe in Chapter 6, Using Python to Drive Hardware.GPU/LAN JTAG: TheJoint Test Action Group (JTAG) is a programming and debugging interface used to configure and test processors. These are present on newer models as surface pads. A specialist JTAG device is required to use this interface. We do not use this in the book.Direct camera CSI: This connection supports the Raspberry Pi Camera module (as used in Chapter 8, Creating Projects with the Raspberry Pi Camera Module). Note that the Pi Zero has a smaller CSI connector than the other models, so it requires a different ribbon connector.Direct display DSI: This connection supports a directly connected display, a 7-inch 800 x 600 capacitive touch screen.

Using NOOBS to set up your Raspberry Pi SD card

The Raspberry Pi requires the operating system to be loaded onto an SD card before it starts up. The easiest way to set up the SD card is to use NOOBS; you may find that you can buy an SD card with NOOBS already loaded on it.

NOOBS provides an initial start menu that provides options to install several of the available operating systems onto your SD card.

Getting ready

Since NOOBS creates a RECOVERY partition to keep the original installation images, an 8-GB SD card or larger is recommended. You will also need an SD card reader (experience has shown that some built-in card readers can cause issues, so an external USB type reader is recommended).

If you are using an SD card that you have used previously, you may need to reformat it to remove any previous partitions and data. NOOBS expects the SD card to consist of a single FAT32 partition. If using Windows or Mac OS X, you can use the SD association's formatter, as shown in the following screenshot (available at https://www.sdcard.org/downloads/formatter_4/):

Get rid of any partitions on the SD card using SD formatter

From the Option Setting dialog box, set Format Size Adjustment. This will remove all the SD card partitions that were created previously.

If using Linux, you can use gparted to clear any previous partitions and reformat it as a FAT32 partition.

The full NOOBS package (typically just over 1 GB) contains the Raspbian, the most popular Raspberry Pi operating system image built in. A lite version of NOOBS is also available that has no preloaded operating systems (although a smaller initial download of 20 MB and a network connection on the Raspberry Pi are required to directly download the operating system you intend to use).

NOOBS is available at http://www.raspberrypi.org/downloads, with the documentation available at https://github.com/raspberrypi/noobs.

How to do it…

By performing the following steps, we will prepare the SD card to run NOOBS. This will then allow us to select and install the operating system we want to use:

Get your SD card ready.On a freshly formatted or new SD card, copy the contents of the NOOBS_vX.zip file. When it has finished copying, you should end up with something like the following screenshot of the SD card:

NOOBS files extracted onto the SD card

Note

The files may vary slightly with different versions of NOOBS, and the icons displayed may be different on your computer.

You can now put the card into your Raspberry Pi, connect it to a keyboard and display, and turn the power on. Refer to the Connecting up the Raspberry Pi recipe for details on what you need and how to do this.

By default, NOOBS will display via the HDMI connection. If you have another type of screen (or you don't see anything), you will need to manually select the output type by pressing 1, 2, 3, or 4 according to the following functions:

Key 1 stands for the Standard HDMI mode (the default mode)Key 2 stands for the Safe HDMI mode (alternative HDMI settings if the output has not been detected)Key 3 stands for Composite PAL (for connections made via the RCA analogue video connection)Key 4 stands for Composite NTSC (again, for connections via the RCA connector)

This display setting will also be set for the installed operating system.

After a short while, you will see the NOOBS selection screen that lists the available distributions (the offline version only includes Raspbian). There are many more distributions that are available, but only the selected ones are available directly through the NOOBS system. Click on Raspbian as this is the operating system being used in this book.

Press Enter or click on Install OS, and confirm that you wish to overwrite all the data on the card. This will overwrite any distributions previously installed using NOOBS but will not remove the NOOBS system; you can return to it at any time by pressing Shift when you turn the power on.

It will take around 20 to 40 minutes to write the data to the card depending on its speed. When it completes and the Image Applied Successfully message appears, click on OK and the Raspberry Pi will start to boot into the Raspberry Pi Desktop.

How it works…

The purpose of writing the image file to the SD card in this manner is to ensure that the SD card is formatted with the expected filesystem partitions and files required to correctly boot the operating system.

When the Raspberry Pi powers up, it loads some special code contained within the GPU's internal memory (commonly referred to as binary blob by the Raspberry Pi Foundation). The binary blob provides the instructions required to read the BOOT Partition on the SD card, which (in the case of a NOOBS install) will load NOOBS from the RECOVERY partition. If at this point Shift is pressed, NOOBS will load the recovery and installation menu. Otherwise, NOOBS will begin loading the OS as specified by the preferences stored in the SETTINGS Partition.

When loading the operating system, it will boot via the BOOT partition using the settings defined in config.txt and options in cmdline.txt to finally load to the desktop on the root Partition. Refer to the following diagram:

NOOBS creates several partitions on the SD card to allow installation of multiple operating systems and provide recovery

NOOBS allows the user to optionally install multiple operating systems on the same card and provides a boot menu to select between them (with an option to set a default value in the event of a time-out period).

If you later add, remove, or reinstall an operating system, ensure first that you make a copy of any files, including system settings you wish to keep, as NOOBS may overwrite everything on the SD card.

There's more…

When you power up the Raspberry Pi for the first time, it will start directly with the desktop. You can now configure the system settings using the Raspberry Pi Configuration program (under the Preferences menu on the Desktop or via the sudo raspi-config command), which will allow you to perform changes to your SD card and set up your general preferences.

Raspberry Pi Configuration program

Changing the default user password

Ensure that you change the default password for the pi user account once you have logged in, as the default password is well known. This is particularly important if you connect to public networks. You can do this with the passwd command, as shown in the following screenshot:

Setting a new password for the pi user

This gives greater confidence because if you later connect to another network, only you will be able to access your files and take control of your Raspberry Pi.

Ensuring that you shut down safely

To avoid any data corruption, you must ensure that you correctly shut down the Raspberry Pi by issuing a shutdown command, as follows:

sudo shutdown –h now

Or use this one:

sudo halt

You must wait until this command completes before you remove power from the Raspberry Pi (wait for at least 10 seconds after the SD card access light has stopped flashing).

You can also restart the system with the reboot command, as follows:

sudo reboot

Preparing an SD card manually

An alternative to using NOOBS is to manually write the operating system image to the SD card. While this was originally the only way to install the operating system, some users still prefer it. It allows the SD cards to be prepared before they are used in the Raspberry Pi. It can also provide easier access to startup and configuration files, and it leaves more space available for the user (unlike NOOBS, a RECOVERY partition isn't included).

The default Raspbian image actually consists of two partitions, BOOT and SYSTEM, which will fit into a 2 GB SD card (4 GB or more is recommended).

You need a computer running Windows/Mac OS X/Linux (although it is possible to use another Raspberry Pi to write your card, be prepared for a very long wait).

Download the latest version of the operating system you wish to use. For the purpose of this book, it is assumed you are using the latest version of Raspbian available at http://www.raspberrypi.org/downloads.

Perform the following steps depending on the type of computer you plan to use to write to the SD card (the .img file you need is sometimes compressed, so before you start, you will need to extract the file).

The following steps are for Windows:

Ensure that you have downloaded the Raspbian image, as previously detailed, and extracted it to a convenient folder to obtain an .img file.Obtain the Win32DiskImager.exe file available at http://www.sourceforge.net/projects/win32diskimager.Run Win32DiskImager.exe from your downloaded location.Click on the folder icon and navigate to the location of the .img file and click on Save.If you haven't already done so, insert your SD card into your card reader and plug it into your computer.Select the Device drive letter that corresponds to your SD card from the small drop-down box. Double-check that this is the correct device (as the program will overwrite whatever is on the device when you write the image).

Note

The drive letter may not be listed until you select a source image file.

Finally, click on the Write button and wait for the program to write the image to the SD card, as shown in the following screenshot:

Manually write operating system images to the SD card using Disk Imager

Once completed, you can exit the program. Your SD card is ready!

The following steps should work for the most common Linux distributions, such as Ubuntu and Debian:

Using your preferred web browser, download the Raspbian image and save it in a suitable place.Extract the file from the file manager or locate the folder in the terminal and unzip the .img file with the following command:
unzip filename.zip
If you haven't already done so, insert your SD card into your card reader and plug it into your computer.Use the df –h command and identify the sdX identifier for the SD card. Each partition will be displayed as sdX1, sdX2, and so on, where X will be a, b, c, d, and so on for the device ID.Ensure that all the partitions on the SD card are unmounted using the umount /dev/sdXn command for each partition, where sdXn is the partition being unmounted.Write the image file to the SD card with the following command:
sudo dd if=filename.img of=/dev/sdX bs=4M
The process will take some time to write to the SD card, returning to the terminal prompt when complete.