35,99 €
If you have already undertaken some simple projects with the Raspberry Pi and are looking to enter the exciting work of hardware interaction, then this book is ideal for you.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 270
Veröffentlichungsjahr: 2015
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: March 2015
Production reference: 1200315
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-290-1
www.packtpub.com
Author
Dan Nixon
Reviewers
Soumen Chandra Laha
Maryala Srinivas
Commissioning Editor
Akram Hussain
Acquisition Editor
Meeta Rajani
Content Development Editor
Shubhangi Dhamgaye
Technical Editor
Siddhi Rane
Copy Editor
Neha Vyas
Project Coordinator
Harshal Ved
Proofreaders
Simran Bhogal
Maria Gould
Paul Hindle
Indexer
Mariammal Chettiyar
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
Dan Nixon lives in England and is a 20-year old software engineering student who is currently studying at Newcastle University and is in his third year. He has long had an interest in electronics and embedded computing projects.
Previously, Dan has worked on a 360-degree camera system for the Raspberry Pi and this is where his interest in the platform started.
Currently, he is on a year-long work placement and is working on neutron data analysis software at the Rutherford Appleton Laboratory in Oxford, UK.
I would like to thank my mother and father for their support while writing this book. I would also like to thank the members of Maker Space, Newcastle, for providing the facilities to prototype the projects and allowing me to use some of their projects in this book.
Soumen Chandra Laha has been working as a senior embedded design engineer at Wine Yard Technologies since 2008. He started his career as a quality control engineer and gradually became an embedded design engineer. He has been working in the field of embedded systems and has industry experience of more than 6 years in various domains, including automotive, consumer electronics, healthcare, and so on. He has hands-on experience in various microcontrollers and microprocessors, such as 8051, PIC, AVR, PSoC, ARM Cortex, ARM7, ARM9, ARM11, and the TI-DSP microcontroller. He has development exposure to embedded Linux and Windows CE and knows how to port real-time operating systems on various ARM platforms.
He is an electronic hobbyist and designer and believes in continuous learning. His strengths lie in developing, maintaining, integrating, and debugging large sized C code of applications and system-level embedded software designs.
Maryala Srinivas is the founder and managing director of Wine Yard Technologies, which was founded in 2006. He has over 10 years of experience in the field of advanced embedded systems design and development. He is a passionate and enthusiastic entrepreneur. His passion to become an entrepreneur made him reject a great job offer from Delhi Metro Rail Corporation (DMRC), where he was to work for the signaling department in the R&D Division. He is associated with Junior Chamber International, India and Hyderabad Directors/CEO's Forum (HDCF). He received the Indira Gandhi Sadbhavana Award in 2012 for outstanding services, achievements, and contributions to the nation in the field of science and technology.
Many of his articles are published in national and international journals and technical magazines. He has addressed several technical conferences and seminars in the field of embedded systems and RTOS design. He was recognized as the star speaker at EFY Design Engineers' Conference, held at New Delhi in March 2012. Many of the faculty members from universities such as NITs, JNTU, AU, and OU and other private engineering colleges benefited immensely by the technology talent transformation workshops conducted by him at Wine Yard Technologies. The Wine Yard team led by him has achieved many milestones. More than 100,000 students and over 400 professionals, including the teaching faculty from universities and many working engineers, have immensely benefited from the talent transformation programs.
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.
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.
The Raspberry Pi is a small form factor, single board, ARM-based computer. It is capable of running on many desktop applications that can be run on a standard Linux computer. While the Pi is only slightly larger than a credit card, it uses very little power. As such, it has become very popular among the hacker and maker community, which uses the Pi to integrate more computing power in their projects.
The Pi is very easy to set up and in less than 20 minutes, you can run it on a modified version of popular, Linux-based operating systems. It will function just like you would expect a desktop PC to. Thanks to its small form factor, many people have used it as an alternative to a traditional PC for fast access to applications and the Internet. Since the Pi draws very little power, it can be left running.
Where the Pi really excels is that it brings more computing power to hardware and electronics projects. This is made possible by a wide range of interfaces on the Pi that are typically not found on conventional computers.
This has led to a rise in new projects that are made using the Pi, which otherwise would have been considerably more difficult or expensive to make.
Chapter 1, Raspberry Pi Pirate Radio, introduces the Pi and gives an overview of its setup and configuration procedure and some fundamental Linux concepts. This chapter then demonstrates the basic use of the GPIO header and Python scripting.
Chapter 2, Portable Speaker System, explores how to use the Pi as a portable, battery-powered speaker system with a self-contained media server that can be used without any ties to a power supply or home network.
Chapter 3, Mini Retro Arcade Cabinet, demonstrates how the Pi can be used to create a mini arcade cabinet complete with a traditional joystick and button controls and how it can be used to play a range of classic arcade and console games.
Chapter 4, GPS-enabled Time-lapse Recorder, covers how to use the Pi as a time lapse recorder that can also capture the location of each image and trigger the image capture based on the current position of and distance traveled by the camera.
Chapter 5, Home Theater PC, explores the way in which the Pi can be used as a home theater PC using the popular XBMC media center software and a custom, purpose-built enclosure.
Chapter 6, Outdoor Weather Station, delves into the topic of interfacing hardware to the Pi using intermediate devices, in this case, Arduino. We also take a look at Python web applications running on the Pi.
Chapter 7, Home Security System, explores how to use the Pi as a hub for a wireless network of sensors and how this data can be used and displayed on a web application.
Chapter 8, Remote-operated Robotic Arm, focuses on how to use the Pi to control and monitor devices remotely in the form of a robotic arm that can be controlled through a web application.
Chapter 9, Magic Mirror, expands your knowledge of woodworking and designing, which will prove to be important skills for any further projects that you do in the field of electronics and physical computing.
Chapter 10, Bottle Xylophone, covers how the Pi, several servos, and some empty bottles can be turned into a musical instrument driven by MIDI files.
This book assumes that you are familiar with the basics of the Raspberry Pi and Linux. Most of the code in this book is in Python with some C++. However, the source code for each of the projects is available alongside the book that can be used straight on the Pi.
Several of the projects will also deal with some basic electronics, and as such, some basic tools will be needed for the completion of some projects. However, note that at the start of each chapter, the procedure to build the electronics side of the project is explained step by step.
Some projects will also require access to woodworking tools in order to construct cases and enclosures. Usually, you will require just the common "garden shed" tools. However, there is information in the relevant chapters on what you can do if not having the correct tools causes an issue in the relevant chapters.
This book is aimed at those are just getting started with the Raspberry Pi, already have a few small projects under their belt, and are looking to get into the world of hardware and physical computing projects.
In this book, you will find a number of text styles 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 and user input are shown as follows: "Where path/to/raspbian_image.img is the extracted image file and sdX is the path to your SD card."
A block of code is set as follows:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Files can be uploaded by right-clicking on them and selecting Upload."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/2901OS_ColoredImages.pdf.
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 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.
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.
In this chapter, we will take a quick look at the Raspberry Pi hardware and some of the software that will be used both in this project and the majority of others throughout this book.
As the Pi was based on hardware that was to be included in embedded or portable electronics (such as smartphones and tablets), it has a few extra hardware features that are not found on a typical desktop or laptop PC, one of which is the General Purpose Input and Output (GPIO) header. This is a set of pins (26 on the model A and B, and 40 on the model B+) that allows you to communicate with external hardware such as GPS sensors, accelerometers, and motors through programming languages such as Python, C, and C++. When we get further in this chapter, we will take a look at a little trick that can be done to turn one of these pins into an FM radio transmitter.
You will need the following:
In order to get the Pi up and running, the bare minimum you will need is a USB power supply, micro USB cable, an Ethernet cable to connect the Pi to your network, and an SD card that has at least 4 GB memory. Although, later on, some projects will need a larger capacity of the SD card.
While a monitor, mouse, and keyboard can also be used for a lot of the projects in this book, they are not actually required assuming that you have a network that runs a DHCP server, which you can connect with the Pi in order to set it up over SSH.
It is worth mentioning now that for a USB-powered device, the Pi is quite power-hungry (drawing around 600-700 mA), therefore, while the Pi can be powered from a USB port, which is usually rated for around 500 mA, it is recommended that you use a mains powered adapter. Without this, the Pi can become unstable when additional devices are connected that draw more power, for example, a USB Wi-Fi dongle or camera module.
There are a wide range of Linux distributions available for the Pi, some of which are very general purpose while others are built for specific purposes (a couple of which will be used in the later projects of this chapter). For now, we will use the most standard distribution, Raspbian, which as the name suggests is based on the Debian distribution.
The Raspberry Pi downloads page (http://www.raspberrypi.org/downloads) has a good selection of general purpose distributions.
Another relatively new distribution that is worth mentioning is Minibian (http://minibianpi.wordpress.com), a distribution based on Raspbian, which has the majority of its default software removed. While this may not seem that helpful, it means that the Pi boots in a useable OS in around 25 seconds and saves the SD card space. This type of OS is more suited to a project that has finished being developed and is going into a more natural usage environment. You usually would not expect a Wi-Fi router to take 3 minutes to boot, so why should your Pi-based Internet radio?
When you have all the relevant hardware, head over to http://www.raspberrypi.org/downloads and download the ZIP archive for Raspbian and extract it.
The next steps vary depending on your operating system.
Windows does not natively include a tool used to write disk images, therefore, the Win32 Disk Imager (http://sourceforge.net/projects/win32diskimager) application is used to write images to an SD card.
First, go to the download link mentioned in the preceding paragraph, download, and install Win32 Disk Imager. As writing images to drives requires administrator permissions, you will need to run Win32 Disk Imager by right-clicking on its entry in the Start menu, and selecting Run as administrator:
Next, select the .img file that was extracted from the Raspbian ZIP file using the folder icon under Image File and the drive letter of the SD card from the drop-down box:
Ensure that the correct drive letter is selected, and the SD card does not contain any data that has not been backed up, as this operation will destroy all of the data already present in the card.
Finally, click on Write to write the image to the SD card.
Unix and Unix-like operating systems already have a tool to read and write images to external storage—dd.
First, you will need to find the path for your SD card. The easiest way to do this is to use the udev management tool, udevadm, to monitor the udev log, which logs activity from various devices on the system, including the SD card being inserted and will allow you to see the device path that was assigned to it and the partitions already existing on it. This can be done by running the following command:
Then, insert the SD card, at which point, you should see a set of log messages similar to the ones shown in the following screenshot:
Here, the important information can be seen on the last three lines, which tells us that in this case, the path for the entire card is /dev/sdb, with two partitions at /dev/sdb1 and /dev/sdb2.
We must now ensure that none of these partitions on the SD card are currently mounted, as some desktop managers (such as GNOME, the default desktop manager on Ubuntu) will try to automatically mount partitions when they are detected.
To do this, we will run the following command for every partition (that is, in my case, /dev/sdb1 and /dev/sdb2), where PATH is the path to the partition:
If the partition was mounted, you will not see any output from the command; however, if the partition was not mounted, you will get the following message:
Once you know the path for your SD card and have ensured that no existing partitions are mounted, you can then write the Raspbian image to your SD card using the following command, where PATH is the path to the SD card (/dev/sdb in my case):
Be certain that the path to the SD card is correct, and the card does not contain any data that has not been backed up as this operation will destroy all of the data already present on the card.
Where path/to/raspbian_image.img is the extracted image file and sdX is the path to your SD card. Note that this step can take up to 5-8 minutes, since no output is given on the screen, the SD card reader's busy/data LED is a good indication that the image is being written.
Since the GNU Coreutils (which include commands such as cp, mv, dd, and so on) do not provide much (or any) output to indicate the progress, you may want to take a look at the Coreutils Viewer tool (https://github.com/Xfennec/cv), which shows the progress of the Coreutils commands.
Once you have the image written to the card, it is time to boot the Pi and perform the initial setup. The most common way to do this is by using a keyboard, mouse, and monitor; however, if you have access to a network that provides DHCP (as most home networks do), then the setup can be done entirely over Secure Shell (SSH).
First, set up the hardware and boot the Pi by inserting the SD card, connecting the power, and the Ethernet cable. Within a few seconds, you will see that the ACT LED starts to flicker. If it flashes for very short pulses or does not light at all, then this indicates an issue with either the SD image, the connection between the card and the Pi (a common issue for the models A and B), or the card itself.
Once the Pi has booted (indicated by less frequent flashing of the ACT LED), you will need to determine its IP address. There are two main ways to do this: by accessing the DHCP allocations via your router or by scanning the local network.
The cross-platform tool, the Nmap utility (http://nmap.org) can be used to scan a network.
To do so, you will need to find the IP address of your PC (in order to find the subnet on your local network to search for the Pi in). On Windows, this can be done by opening the Command Prompt and executing this command:
This should give you the information about your network interfaces similar to the following:
On Unix, this can be done by using the following command:
This command gives output similar to the following:
The search IP range that is given to Nmap is obtained by replacing the last number of IPv4 or InetAddress with *. In our case, it will be 192.168.0.*.
Now that we know the address range in which we will be looking, we can open a terminal and run the following command:
Replacing the IP range with your search range will try to make contact with every host in the given IP address range and will return with a list of every host that is up, with a list of their open ports, and what services they correspond to. In our case, we are looking for any hosts that have an open SSH port:
Here, I have only shown the report for the Pi. Usually, after the first boot, SSH will be the only service that is started, so it is usually given away as the device that only provides SSH.
On Unix, accessing the Pi via SSH is as simple as executing the following:
Here, Pi IP is the IP address of the Pi. You may get a warning similar to this the first time you run the command:
This can safely be ignored by typing yes and pressing Enter. You will then be asked for a password, and as this is the first boot, the default is raspberry.
On Windows, PuTTY (http://www.putty.org) can be used to SSH into the Pi. Once downloaded, run PuTTY and enter the IP address of the Pi and the Host Name field, ensuring that Port is set to 22 and SSH is selected. Then, click on Open:
You will see a warning message similar to the following about the identity of the host:
Again, this can be ignored by clicking on Yes. You will then be asked for a username and password in the PuTTY terminal window. Since this is the first boot, the defaults are pi and raspberry.
At this point, it would be good to learn a few Linux shell commands, which you will no doubt come across while working with the Pi:
More information can be obtained about a given command via its man page, which can be accessed using the following command, where command is the command you wish to know more about:
Once you are able to SSH in the Pi, run the configuration utility using the following command:
This utility allows you to configure the Pi hardware and perform useful configuration tasks such as changing passwords and resizing the root partition on the SD card, both of which, we will do now.
First, select the Expand Filesystem option and press Enter. The utility will modify the partition table and report that it has completed, and that the changes made will only affect the filesystem after the next reboot. Press Enter again to return to the main menu.
Now, select Change User Password and hit Enter twice. You will be taken back to the shell and prompted to enter a new password, which has to be entered twice. Once done, a confirmation box will notify you that the password was changed successfully; press Enter to return to the menu.
As this is all that needs to be done in raspi-config for now, press the left arrow key twice to select Finish and Enter to confirm. You will be asked whether you want to reboot now; select Yes and press Enter. Once the Pi is rebooted, SSH back into it using your new password.
Once you have access again, check whether you now have access to the full storage space on the SD card using:
The command should report the size of rootfs much closer to the SD card capacity: