Raspberry Pi Hacks 1449362346 %7B2FBCBBD1%7D %5BSuehle %26 Callaway 2014 01 05%5D {2FBCBBD1} [Suehle & 05]

User Manual: 1449362346 %7B2FBCBBD1%7D Raspberry Pi Hacks %5BSuehle %26 Callaway 2014-01-05%5D

Open the PDF directly: View PDF PDF.
Page Count: 392 [warning: Documents this large are best viewed by clicking the View PDF Link!]

Ruth Suehle and Tom Callaway
Raspberry Pi Hacks
Raspberry Pi Hacks
by Ruth Suehle and Tom Callaway
Copyright © 2014 Ruth Suehle and Tom Callaway. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online
editions are also available for most titles (http://my.safaribooksonline.com). For more informa-
tion, contact our corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com.
Editors: Brian Sawyer and Rachel
Roumeliotis
Production Editor: Christopher Hearse
Copyeditor: Amanda Kersey
Proofreader: Jasmine Kwityn
Indexer: Ellen Troutman
Cover Designer: Mark Paglietti
Interior Designer: David Futato
Illustrator: Rebecca Demarest
December 2013: First Edition
Revision History for the First Edition:
2014-12-06: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449362348 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks
of O’Reilly Media, Inc. Raspberry Pi Hacks and related trade dress are trademarks of O’Reilly
Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc.,
was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors
assume no responsibility for errors or omissions, or for damages resulting from the use of the
information contained herein.
ISBN: 978-1-449-36234-8
[V]
This book is dedicated to Seth Vidal. Seth didn’t live long enough to see
this book finished, but within it, a little piece of his hacker spirit will live
on forever.
Table of Contents
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Configuration Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Hack 01. Choose and Format the Right SD Card 1
Hack 02. Mount the SD Card 3
Hack 03. Decode the LEDs 7
Hack 04. Update the Firmware 8
Hack 05. Monitor the Raspberry Pi Hardware 13
Hack 06. Overclock Your Pi 17
Hack 07. Overvolt for Higher Performance 20
Hack 08. Get More USB Ports 22
Hack 09. Troubleshoot Power Problems 24
Hack 10. Unbreak Your Raspberry Pi 29
Hack 11. Go Headless 31
Hack 12. Connect with SSH 32
Hack 13. Give Your Pi a Static IP Address 34
Hack 14. Learn to Speak GPIO 36
Hack 15. Connect GPIO Pins to a Breadboard 39
Hack 16. Add a USB Serial Console 47
Hack 17. Add a Reset Button 54
Hack 18. Get Power to the Pi on the Move 56
Hack 19. Test Your Might (in Volts) 57
Hack 20. Add Additional Memory with Swap 61
2. Hacking Linux for the Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . 63
Hack 21. Build a Cross-Compiler Toolchain 63
Hack 22. Build a Custom Kernel 76
Hack 23. Update to the Latest Prebuilt Kernel 87
Hack 24. Split Memory Between the GPU and Linux Userspace 91
v
Hack 25. Update the Firmware and Prebuilt Binary Kernel the Easy Way 96
Hack 26. Emulate the Pi 97
Hack 27. Try Occidentalis: The Raspberry Pi Distro for (Advanced)
Education 99
Hack 28. Monitor the Pi’s IP Address 102
Hack 29. Run Android on the Raspberry Pi 107
3. Raspberry Pi Around the House . . . . . . . . . . . . . . . . . . . . . . . . 111
Hack 30. Share Files with Samba 111
Hack 31. Use Your Raspberry Pi as a Remote Print Server 117
Hack 32. Make Calls with a Raspberry Pi Asterisk Telephone System 121
Hack 33. Build Your Own Web Server 127
Hack 34. Control a LEGO Robot 134
Hack 35. (Appear to) Survive a Gaping Chest Wound 150
Hack 36. Look for Aliens 157
4. Hacking the Outdoors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Hack 37. Tell the Temperature Outside (Without Going Out There) 165
Hack 38. Check on Your Plants 172
Hack 39. Make Your Pi Water-Resistant (with a Case) 176
Hack 40. Make Your Pi Water-Resistant (Without a Case) 178
Hack 41. Find Geocaches from Your Car 182
Hack 42. See the Light 188
Hack 43. Listen to Aircraft Transponders 198
Hack 44. Control Aerial Photography 204
Hack 45. Have the Best Holiday Lights Display 219
5. Multimedia Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Hack 46. Play Video Files 227
Hack 47. Enable Additional Video Codecs 231
Hack 48. Build a Pi MusicBox 232
Hack 49. Turn Your Pi into a Radio 244
Hack 50. Control the Pi via Touchscreen 247
Hack 51. Emulate Classic Video Game Consoles 255
Hack 52. Connect a DSLR 258
Hack 53. Set Up a Photobooth 262
Hack 54. Turn Your Pi into a Tiny Media Center 269
Hack 55. Watch Movies in the Backseat of Your Car 277
6. Extend Your Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Hack 56. Control GPIO from a Web Browser 287
Hack 57. Add a Tiny Screen 290
Hack 58. Connect Arduino Shields to Your Raspberry Pi 292
Hack 59. Control a 3D Printer 312
Hack 60. Add a Numeric Keypad 316
vi TABLE OF CONTENTS
Hack 61. Add a Heat Sink 322
Hack 62. Enable the Raspberry Pi Camera on Pidora 324
Hack 63. Build a Solar-Powered Lab 326
Hack 64. Build a MIDI Controller (on the Cheap!) 329
Hack 65. Build a Raspberry Pi Supercomputer 337
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
vii
TABLE OF CONTENTS
Foreword
In April 2011 I was coming to the end of an executive MBA program at Cambridge and
looking forward to spending some quality time with my wife, Liz. The old joke is that
MBA stands for married but absent, and after two years of barely seeing each other,
the last thing on our minds was jumping straight into another startup.
But after our accidental announcement of the Raspberry Pi educational computer
project the following month (see “Funny Story... sidebar), we had little choice but to
knuckle down and make it happen. Liz, a freelance journalist by background, dropped
everything to run our nascent community at www.raspberrypi.org. I, along with my
colleagues at Broadcom and my fellow Raspberry Pi Foundation trustee Pete Lomas,
started to figure out how to actually deliver the $25 ARM/Linux box that we’d so rashly
promised to build.
Funny Story
We went to see Rory Cellan-Jones at the BBC, in the hope that we might be
able to use the dormant “BBC Micro” brand. He put a video of our prototype
on his blog and got 600,000 YouTube views in two days. There’s nothing
quite like accidentally promising over half a million people that you’ll make
them a $25 computer to focus the mind.
Nine months later, we launched the Model B Raspberry Pi, taking 100,000 orders on
the first day and knocking out both our distributors’ websites for a period of several
hours. In the 18 months since then, we’ve sold nearly two million Raspberry Pis in over
80 countries.
So, how did our little educational computer, conceived as a way of getting a few hun-
dred more applicants to the Computer Science Tripos at Cambridge, get so out of
control? Without a doubt, the explosive growth of the Pi community has been thanks
ix
to the creativity and enthusiasm of hobbyists, who see the Pi as an easy way to connect
sensors, actuators, displays, and the network to build cool new things. Where for the
first year of the project Liz’s blog posts described work that was being done by us as
we struggled first to design the Pi and then to build enough of them to keep up with
demand, today the vast majority of her posts are about what you have been doing with
the Pi.
It’s hard to pick favorites from the vast number of projects that we’ve seen and fea-
tured on the website. As an unreformed space cadet, the ones that stand out most in
my mind are Dave Akerman’s high-altitude ballooning and Cristos Vasilas’s astropho-
tography experiments. Dave’s work in particular promises to put a space program
within the budgetary reach of every primary school in the developed world and is part
of a broader trend toward using the Pi to teach young people not just about computer
programming, but about the whole range of STEM (science, technology, engineering,
and mathematics) subjects. Another great development in this area was Mojang’s
decision at the end of 2012 to port Minecraft to the Pi, creating the scriptable Minecraft
Pi Edition and spawning a large range of educational software projects.
As we head into 2014 and toward the second anniversary of the launch, we’re looking
forward to seeing what you all get up to with the Pi. One thing is certain: it won’t be
anything I can imagine today.
—Eben Upton
Founder and Trustee, Raspberry Pi Foundation
xFOREWORD
Preface
The inspiration for the Raspberry Pi was born when Eben Upton was working with
computer science students at Cambridge University (see the Foreword for his own
account). He saw a need for incoming students to have greater opportunities to obtain
programming experience before they got to the university level. The first concept de-
signs for what would become the Pi we know now were born in 2006. Alpha boards
were demonstrated in late 2011, and the first 10 boards were auctioned off at the
beginning of 2012, raising £16,000.
The first batch of 10,000 Raspberry Pis went on sale February 29, 2012. Toward the
end of 2011, the SD card image for it had already been downloaded more than 50,000
times, hinting at its impending popularity. The two UK sellers at the time, Premier
Farnell and RS Components, sold out within minutes, with the latter reporting more
than 100,000 orders that day. Upton designed them for education—specifically
Python, hence the “Pi” part of the name. But the tiny board caught the eye of already-
experienced programmers and electronics hackers. As of this writing, a year and a
half after that first day of sale, more than two million have been sold.
And then roughly 1.95 million of them got stuck in an office drawer while their owners
gathered with hackerspace friends over beer and collectively lamented, “Yeah, I
bought a Pi, but I haven’t figured out what to do with it yet. I was thinking I might use
it to build a time machine and try to study the K-Pg event in person, but I’ll probably
just put XBMC on it.
We wrote this book for you, the ones who haven’t decided what to do with your lan-
guishing Pis yet. Of course, if you do just want to install XBMC, you can refer to Hack
#54 and then read the rest of the book to see the fun you’re missing. Alas, we haven’t
perfected the time machine hack yet, but follow @suehle and @spotrh on Twitter, and
we’ll let you know if we find a good source for flux capacitors.
We’re in what we hope is still the early stages of a return to a DIY culture. Those of you
deeply embroiled in it already, who have been to every Maker Faire and joined your
xi
local hackerspace the day it opened, might insist that, on the contrary, we are deep
in the midst of said return. But it hasn’t gone far enough yet. Beyond our little maker/
hacker/builder/doer niche is still a wide world of disposable goods and electronics
consumption and dump-tion. Our devices are increasingly designed to do what the
designer intended without the flexibility to do what the owner intends, needs, or wants.
Further, they often are sealed up boxes, keeping prying fingers from ripping them apart
and rebuilding them to suit new visions.
The acceptance of closed, unhackable, unfixable goods is relatively new in the course
of human culture. It’s not so long ago—perhaps even your own childhood if you’re over
30 or so—in which we were happily building our computers from kits and taking the
TV to the repair shop instead of buying a new one. Devices like the Raspberry Pi help
bring us back to that better time when we knew (or could find out) what was happening
inside the things that we owned, when we could change them for the better and give
them new life when they broke down.
The first chapter of this book is for everyone with a Raspberry Pi; it gives you a basis
on which to build all of the hacks. From there, we move on to the larger projects that
implement all of those smaller hack needs. And in the spirit of the Pi’s original purpose,
we hope you learn a lot.
Who This Book Is For
Despite the potentially intimdating word “hacks” in the title, we don’t expect you to
be a Linux kernel developer or electrical engineer to be able to use this book. Hacks
and hacking—not in the sense you hear those words used on the six o’clock news—
are how many of us learn best. Hands on, trying something new, possibly frying elec-
tronics in the process.
We’ve tried to write these hacks so that even the novice can follow along and become
a Raspberry Pi hacker. It will help greatly if you have at least a rudimentary under-
standing of how to use the Linux command line. For the most part, we walk you through
those steps, too, but in places where we haven’t, a quick look to Google or to the man
pages of a command should catch you up.
As to the electronics half of the hacking, we’ve tried to spell as much out in detail as
possible. For those who already have a workroom filled with jumper wires and strange
parts you picked up out of the electronics store clearance bin “because they might be
handy someday,” this level of detail might feel belabored. Just skip ahead to the parts
that are useful to you and be thankful that your less-knowledgeable friends will be
getting help from the book instead of calling you to ask if “GND” is really that impor-
tant, based on the assumption that it’s an amusing nod to their childhood and stands
for “Goonies Never (say) Die.
xii PREFACE
How to Use This Book
Although you can read this book cover to cover, each hack should stand alone, so feel
free to browse and jump to the different sections that interest you most. If there’s a
prerequisite you need to know about, a cross-reference will guide you to the right hack.
The hacks in the book are organized into the following chapters:
Chapter 1, Configuration Hacks
The first chapter introduces you to the common needs of Raspberry Pi users, like
making sure you have the right SD card for the project. It deals with the assorted
parts and issues you’re likely to encounter with any Raspberry Pi project, such as
power problems and getting aquainted with the GPIO pins. You’ll also find tips
and tricks for dealing with some of its more finicky aspects.
Chapter 2, Hacking Linux for the Raspberry Pi
The most basic description you can give of the Raspberry Pi is “small Linux com-
puter,” which means a lot of the things you’ll want to do will require some knowl-
edge of Linux, working from the command line, and getting into the system. Even
if you’re relatively new to Linux, we’ll help you walk through processes—like build-
ing a custom kernel and updating the firmware—that might sound challenging to
the novice but don’t have to be.
Chapter 3, Raspberry Pi Around the House
Now that you’ve gotten the hardware and operating system under control, you
can start looking for bigger projects. In this chapter, you’ll find some ways to use
it around the house, including in really useful projects that make your home com-
puting setup a little smoother.
Chapter 4, Hacking the Outdoors
Why should all the Pi fun be inside your house? You can use it to help out in the
garden, take it geocaching, or run an animated holiday lights display from it. And
that’s just the beginning. What if you could (nearly) waterproof it?
Chapter 5, Multimedia Hacks
Back inside (mostly), this chapter presents the many ways you can use your Pi
for entertainment. You can play music in a few ways, including by turning the Pi
itself into an FM radio or by using it to set up a home theater. Then you can take
it on the road and let the kids watch movies from the backseat by integrating a
touchscreen.
xiii
PREFACE
Chapter 6, Extend Your Pi
This final chapter addresses some larger projects (not that launching an aerial
photography rig isn’t big!). Use the hacks in this chapter to attach more things to
your Pi, get more control over the GPIO, and even build your own cluster of Rasp-
berry Pis with up to 64 nodes.
Hardware Requirements
Most of the hacks in this book use the Raspberry Pi Model B, version 2. Here is a little
information for you to consult and compare to the needs of your intended project
before deciding whether the board you have will serve your purpose.
Why “Model A” and “Model B”?
In keeping with the educational goals, these names are a nod to the inspiration for
the Raspberry Pi, the BBC Micro computer released with the same model names
in 1981.
The Broadcom BCM2835 chip, 700 MHz CPU, and GPU are the same across the
boards. All of them offer HDMI, composite RAC (PAL and NTSC), and a 3.5 mm audio
jack. They all also have the same SD card slot. The Model A sells for $25, while the
Model B sells for $35. See Table P-1 for a description of notable differences.
Table P-1. Differences between Model A and Model B
FEATURE MODEL A MODEL B
Memory 256 MB SDRAM 512 MB SDRAM
USB ports 1 2
Ethernet none 10/100 Ehternet RJ45
There are also two revisions of the Model B board, as shown in Figure P-1.
xiv PREFACE
Figure P-1.
For visual comparison, the two Model B boards: revision 1 (top) and revision 2 (bottom)
xv
PREFACE
Changes made for rev 2 include:
2 2.5 mm nonplated mounting holes added
LED labeling: D9 (yellow) corrects 10 label to 100, and D5 (green) says ACT for
Activity” instead of OK.
Reset circuit added (see Hack #17 for how to use it)
USB fuses removed (this helps with USB hubs that backfeed power, as long it’s
no more than 2.5A under fault conditions)
GPIO pin changes:
CAM_GPIO: GPIO27 now GPIO21 routed to S5 pin 11 (S5 is the camera inter-
face)
GPIO_GEN2: GPIO21 now GPIO27 routed to P1 pin 13 (P1 is the main, long strip
of GPIO pins)
Additional GPIO added on P5 (see Figure P-2), which maps as follows:
P1 - 5V0
P2 - 3.3V
P3 - GPIO28
P4 - GPIO29
P5 - GPIO30
P6 - GPIO31
P7 - GND
P8 - GND
Primary and secondary I2C channels switched (see Table P-2)
Figure P-2.
P5 pin order (Note that “P5” label is on bottom of the board)
xvi PREFACE
Table P-2. I2C channels in Rev 1 and Rev 2
REV 1 REV 2
SCL0 (GPIO 1) routed to P1 pin 5 routed to S5 pin 13
SDA0 (GPIO 0) routed to P1 pin 3 routed to S5 pin 14
SCL1 (GPIO 3) routed to S5 pin 13 routed to P1 pin 5
This information is applicable for most of the hacks in the book. But, of course, just
because they were tested (and possibly designed for) the Model B, it doesn’t mean
that the hacks won’t work with a different model or revision (unless otherwise speci-
fied). Feel free to use what you have, but know you might need to refer to additional
information online about older boards.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, and email addresses.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele-
ments such as variable or function names, databases, data types, environment
variables, statements, filenames, file extensions, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter-
mined by context.
This element signifies a tip, suggestion, warning, caution or general note.
Using Code Examples
All code listings are also available at the book’s GitHub repository.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not need
to contact us for permission unless you’re reproducing a significant portion of the
code. For example, writing a program that uses several chunks of code from this book
xvii
PREFACE
does not require permission. Selling or distributing a CD-ROM of examples from
O’Reilly books does require permission. Answering a question by citing this book and
quoting example code does not require permission. Incorporating a significant
amount of example code from this book into your product’s documentation does re-
quire permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: For example: "Raspberry Pi Hacks by Ruth
Suehle and Tom Callaway (O’Reilly). Copyright 2014 Ruth Suehle and Tom Callaway,
978-1-449-36234-8.
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that delivers
expert content in both book and video form from the world’s lead-
ing authors in technology and business.
Technology professionals, software developers, web designers, and business and cre-
ative professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi-
zations, government agencies, and individuals. Subscribers have access to thousands
of books, training videos, and prepublication manuscripts in one fully searchable da-
tabase from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley
Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press,
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press,
FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Tech-
nology, and dozens more. For more information about Safari Books Online, please visit
us online.
xviii PREFACE
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/Raspberry-Pi-Hacks.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our web-
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Ruth and Tom would like to thank the following people for their inspiration, ideas, help,
and support:
Le Dernier Bar Avant Le Fin Du Monde, which we affectionately refer to as “the
greatest bar in the world,” where this book’s initial hack list was born with the help
of Josh Boyer, Dennis Gilmore, a few pitchers of French beer, and a Pan Galactic
Gargle Blaster
Every Fedora contributor, as one of the four foundations is friends and so many
of you friends have helped us along the way
Rodney Radford, both contributor and new friend, for tirelessly answering what
he no doubt thought were absurd questions, driving many miles to tinker in per-
son, and for trying to help moderately dangerous X-Men costume ideas come
true without harm to the wearer or to the book’s deadline
Ruth thanks Scott, for being the kind of husband who understands when she runs off
to places with nicknames like “the greatest bar in the world” and events like Maker
Faire while he stays home with two awesome kids, who, while awesome, neither serve
xix
PREFACE
Pan Galactic Gargle Blasters nor build massive fire-based art installations (yet). Those
awesome kids are the ones this is really for—the next generation of hackers and mak-
ers—so even greater thanks to Hannah, who QAed the XBMC instructions in this book
(proving they’re easy enough for a seven-year-old) and Ian, who can always say he
learned to spell his first word during the writing of this book: a 12-character login
password.
Tom would like to thank his wife Pam for putting up with him. He was writing this book
in the midst of traveling the world, presenting at conferences, having a second child,
and moving across the United States. He’d also like to dedicate his parts of this book
to his sons, Jimmy (3) and Danny (0.5), who will hopefully read this book one day and
think, “Dad, this stuff is so old, it doesn’t even respond to my brain WiFi signals.
Contributors
Emmanuel Ackerman is a retired computer programmer who now spends his time
doing Sufi meditation and exercises, making pottery, and doing volunteer work for
Powering Potential and related groups. Ackerman contributed Hack #63.
David Bordonada works for Libelium, which runs Cooking Hacks, a site full of both
tutorials and parts for your Raspberry Pi and other hardware projects. Bordonada
contributed Hack #58.
Simon Cox is professor of computational methods and head of the Computational
Engineering Design Research Group (CED) Group within the Faculty of Engineering
and the Environment (FEE) at the University of Southampton. He is also the associate
dean for enterprise in engineering and the environment. Cox contributed Hack #65.
Lori Easterly is currently an information security engineer with a background in Linux
and systems administration, currently residing in central Florida. Among numerous
hacky interests, she is a shortwave and radio-listening enthusiast with a passion for
technology, tinkering, and discovery. Easterly contributed Hack #43.
Oliver Mattos is a search engine mechanic at Google by day and a Pi hacker by night
who loves to make anything do something it wasn’t made for. Mattos contributed Hack
#49 with Oskar Weigl.
Joe Ottinger is a principal engineer on the Open Source and Standards team at Red
Hat. Ottinger contributed Hack #64.
Rodney Radford is an embedded software developer and collector of hobbies, bounc-
ing between hardware tinkering, nearspace telemetry, high altitude rocketry, geo-
caching, SCUBA diving, woodworking, time travel, and robotics as time (and time
travel) permits. Radford contributed Hack #44 and Hack #45.
xx PREFACE
Jared Smith is an open source enthusiast. He enjoys programming, systems admin-
istration, documentation, VoIP, and teaching others how to use open source software.
Smith contributed Hack #32.
Wouter van Wijk (www.woutervanwijk.nl) is the creator of Pi MusicBox. He combines
being a journalist for the second biggest newspaper in the Netherlands with being a
techie who is fascinated by the interaction of people and computers. He enjoys de-
signing user interfaces and experimenting, and likes to make computers and services
easier to use. van Wijk contributed Hack #48.
Oskar Weigl is a master’s student at Imperial College and ARM engineer whose
greatest passions are playing with hardware and software (and building robots)—a
true forward- and reverse-engineer. Weigl contributed Hack #49 with Oliver Mattos.
xxi
PREFACE
1
Configuration Hacks
They say the beginning is usually a good place to start anything, but this is a Hacks
book. You’re likely to skip around to things with interesting titles, or perhaps the one
that starts in Old English because you were flipping through the pages and it looked
like the book had some terrible printing errors.
That said, there are some things that it’s nice to keep in the back of your head before
you start building things, and the Raspberry Pi has a few unexpected quirks that it’s
good to be aware of. If you’re entirely new to Linux, electronics hacking, or both, it’s a
good idea to give this chapter a read-through before proceeding with any of the other
hacks. You just might learn something that will save your Pi (and the $35 of having to
replace it).
HACK 01 Choose and Format the Right SD Card
The Raspberry Pi does not have any built-in flash storage; it needs an SD
card to do anything. Picking the right one might seem simple, but we’re
here to help you make the right choice.
Your SD card choice is an important one. After all, when it comes to the Raspberry Pi,
it’s the equivalent of choosing a hard drive. Being able to change the entire system
quickly by inserting a new SD card is also one of the Pi’s most interesting strengths,
especially when it comes to education. A few factors should weigh into your card se-
lection, though, and even if you think you’ve chosen well, you might still need to trou-
bleshoot minor problems.
SD cards are sold with a class number (e.g., 4, 6, 10), in which a higher class number
equates to a faster card. Most high-quality, Class-4-or-greater SDHC cards (i.e., a
recognized name brand) should work for most purposes. Vendors that sell cards with
a Linux distribution meant for the Raspberry Pi largely use SanDisk or Kingston brand
SDHC Class 4 cards. You can find a thorough list of known, tested cards (as well as
cards that don’t work) at http://elinux.org/RPi_VerifiedPeripherals. That said, a faster
card can as much as double your transfer rate (in terms of MB/sec), so if speed is
critical to your use, you should go with a higher class card.
1
Class 10 Too Classy?
The early Raspberry Pi firmware and bootloader didn’t like Class 10 SD cards. This
problem is supposed to have been fixed, but you’ll still see people occasionally
running into problems with Class 10 cards, so just be aware that it’s a potential
issue. If you have your heart set on a Class 10 card and the first one doesn’t work,
try a different brand. In addition, overclocking has been found to cause errors with
Class 6 and Class 10 SD cards, regardless of size or brand, and the errors might
not appear for a few days or weeks. Keep this in mind if you plan to overclock your
Pi.
If decision making isn’t your strong suit, you can also keep multiple cards around, each
with a different purpose, for a single Raspberry Pi. If you’d like easy peace of mind,
several vendors sell SD cards preloaded with Linux distributions for the Raspberry Pi,
including a card containing NOOBS (New Out-Of-Box Software), which has several
distro options on it. RS Components and element14 offer a card preloaded with
NOOBS as an add-on when you purchase a Raspberry Pi.
NOOBS
NOOBS was designed to make setting up a Raspberry Pi super easy. It supports
multiple OS installations and re-installations, as well as config file editing and web
browsing (to research answers to boot problems) in a pre-boot environment. After
all, this thing was designed for education, and you’re not going to learn much if you
can’t even get started. It fits on a 4 GB card and gives you multiple choices about
which distro you’d like to set up. After you’ve chosen, you can always return to the
menu and make a different selection by holding down Shift during boot, either to
try something new or to get a mulligan on a corrupted card. If you don’t buy it on
a preloaded card, you can download it from http://www.raspberrypi.org/down
loads.
If you used one of the SD cards that’s known to work and you’re still having problems,
you should check a few other things. Be sure that you’ve updated the firmware on the
Pi (see Hack #04). If it was not a new SD card, be sure you fully formatted it first, and
make sure you do so for the whole card and not just a partition.
First, find the card’s device name:
$ su -c 'fdisk -ls'
or:
$ df -h
2RASPBERRY PI HACKS
You’re looking for something like /dev/sdd or /dev/mmcblk0 with the size of your SD
card. To format, run the mkdosfs command, replacing /dev/mmcblk0 with the location
of your card:
$ mkdosfs -I -F32 /dev/mmcblk0
This will make a single FAT formatted partition on the SD card. To be honest, it really
doesn’t matter very much how you format or partition the SD card in most cases,
because when installing any of the system images for Raspberry Pi OS distributions
that include partitions (such as Pidora or Raspbian), the partition table on the SD card
will be completely overwritten by the installed OS image. The exception to that is
NOOBS. By partitioning the disk with a single FAT partition, it is possible to install
NOOBS to the SD card by simply copying the NOOBS files directly onto the SD card.
If you find that you have, say, an 8 GB card, and your computer thinks it’s only 2 GB,
you need to “grow” it to match. Or you might have found that your card’s device name
ends in p1 (followed by p2 and so forth):
/dev/mmcblk0p2 1.6G 1.5G 54M 97% /run/media/wwatson/rootfs
/dev/mmcblk0p1 50M 18M 33M 35% /run/media/wwatson/boot
This means your card is partitioned, and you should get down to one partition before
formatting. Adjusting partitions and their sizes is most easily accomplished with a GUI
tool called Gparted, a visual version of the command-line parted.
HACK 02 Mount the SD Card
While you can certainly access the files on the Raspberry Pi directly from
within a running instance, mounting the SD card on a separate computer
with an SD card reader makes many tasks (such as adding or editing
files) easier.
The Raspberry Pi is a standalone Linux computer, but it really helps to have another
computer on hand. In some cases, it might even be necessary. Fortunately, many
computers now come with SD card readers built in, and if yours didn’t, they’re inex-
pensive and easy to come by. So, even if you buy your SD cards preloaded, you should
probably still have an SD card reader and a second computer for interacting with your
Raspberry Pi build.
Most Linux distributions for the Raspberry Pi create at least two partitions on the SD
card. The first partition is always /boot, because the Raspberry Pi GPU reads its firm-
ware from the beginning of the SD card. The second partition is usually / (also known
as the root partition).
3
CHAPTER 1: CONFIGURATION HACKS
Pidora labels the partitions on the SD card boot and root, but Raspbian does not
use disk labels, so it is especially important to note the device names for that dis-
tribution.
Modern Linux distributions (on your separate computer), such as Fedora or Ubuntu,
will auto-mount the partitions on the SD card when it is inserted and provide some
sort of notification of this event. However, if you’re not sure, running the mount com-
mand should list all mounted partitions on the system. You are looking for something
like /dev/mmcblk0p1, which means the first partition (p1) on the MMC block (mmcblk)
device:
[spot@wolverine ~]$ mount
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
...
/dev/sda3 on / type ext4 (rw,relatime,data=ordered)
/dev/sda1 on /boot type ext4 (rw,relatime,data=ordered)
/dev/mmcblk0p1 on /run/media/spot/boot type vfat (rw,nosuid,nodev,rela
time,uid=1000,gid=1000,fmask=0022,dmask=0077,codepage=437,iocharset=as
cii,shortname=mixed,showexec,utf8,flush,errors=remount-ro,uhelper=udisks2)
/dev/mmcblk0p2 on /run/media/spot/rootfs type ext4 (rw,nosuid,nodev,rela
time,data=ordered,uhelper=udisks2)
The last two lines in the output identify the MMC block device partitions mounted
in /run/media/spot/boot and /run/media/spot/rootfs, respectively.
Linux uses the term MMC to describe the driver for both MultiMediaCard and Se-
cure Digital (SD) formats.
If your SD card is not mounted automatically, make sure it’s inserted and look at the
output from the dmesg command. You do not need to pass any options to dmesg (al-
though piping it through less is always a good idea). When you run it, it will print out
quite a bit of stuff, but the output is in order from the last time you have booted your
Linux system.
You’ll want to look at the end of the output. Specifically, you look toward the end of
the output to figure out the name of the MMC block device. Figure 1-1 shows an ex-
ample of the sort of messages you are looking for.
4RASPBERRY PI HACKS
Figure 1-1.
Output from dmesg on Fedora 19, with the MMC block device messages highlighted
In Figure 1-1, the MMC block device name is mmcblk0, and it has two partitions, p0 and
p1. This gives you enough information to determine the Linux device names for these
partitions: /dev/mmcblk0p0 and /dev/mmcblk0p1. You can confirm these are the correct
device names by running:
brw-rw---- 1 root disk 179, 1 Aug 20 20:42 /dev/mmcblk0p1
brw-rw---- 1 root disk 179, 2 Aug 20 20:42 /dev/mmcblk0p2
If they exist, they’re probably the ones you want (unless you have multiple SD cards
inserted into your system somehow).
SD card readers connected via SPI interfaces are generally designated /dev/
mmc*, but SD card readers connected via USB are designated /dev/sd* (and some
laptops’ internal SD card readers are connected via USB). Be careful when ac-
cessing a /dev/sd* device, as it’s then much easier to accidentally specify a hard
disk drive instead.
Once you’ve identified the Linux device names for the MMC block device partitions
on your system, you should be able to manually mount them by creating two mount
point directories (as root):
5
CHAPTER 1: CONFIGURATION HACKS
$ su -c 'mkdir /mnt/raspi-boot'
$ su -c 'mkdir /mnt/raspi-root'
These directories will serve as anchors for mounting the partitions from the MMC
block device.
Then, use the mount command to mount the boot and root partitions:
$ su -c 'mount /dev/mmcblk0p1 /mnt/raspi-boot'
$ su -c 'mount /dev/mmcblk0p2 /mnt/raspi-root'
If these mount commands return without errors, it means they have mounted suc-
cessfully. You can confirm they have mounted by running mount again and piping the
output through a grep for the MMC block device name (mmcblk0):
$ mount | grep mmcblk0
/dev/mmcblk0p1 on /mnt/raspi-boot type vfat (rw,rela
time,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,er
rors=remount-ro)
/dev/mmcblk0p2 on /mnt/raspi-root type ext4 (rw,relatime,data=ordered)
You should also now be able to see files in the /mnt/raspi-boot and /mnt/raspi-root
directories.
It is also possible to mount the /boot partition inside the mounted / partition, but we
recommend keeping them separate. That way, if you forget to mount the boot parti-
tion, it is more obvious, and you avoid the problem of accidentally copying files into
the /boot directory on the root partition. Remember, Linux mounts the boot partition
on top of that /boot directory, and any files that get copied into that directory when
the boot partition is not mounted are not visible!
Mounting the SD card is especially useful to make quick changes to the config.txt
file that lives in the Raspberry Pi Linux /boot partition. If you need to change the ouput
display settings for a new monitor (or an old HDMI TV with less than amusing quirks),
it’s a lot easier to do it from a mounted SD card than from a headless Raspberry Pi.
Just make sure the boot partition is mounted, and then change into that directory
(/mnt/raspi-boot) and directly edit config.txt (as root). Save your changes, and then
run sync to make sure the buffers get written back to the SD card.
When that finishes, change out of the directory (if you do not, Linux will not let you
cleanly unmount the partition) and unmount both of the partitions (as root) with the
umount command:
$ cd /mnt/raspi-boot/
$ su -c 'vi config.txt'
$ sync;sync;sync;
$ cd /mnt
6RASPBERRY PI HACKS
$ su -c 'umount /mnt/raspi-boot'
$ su -c 'umount /mnt/raspi-root'
If the umount commands both return without any errors, it is now safe to remove your
SD card. Just put it back in your Raspberry Pi, power it on, and hope for the best.
HACK 03 Decode the LEDs
Each Raspberry Pi has a set of LEDs in one corner that give you clues
about what’s happening (or not happening!) with the device. The Model
A had only two lights, but the Model B offers a lot more insight and val-
uable troubleshooting information.
The Raspberry Pi Model B has five status LEDs (shown in Figure 1-2 and described in
Table 1-1) that will help you troubleshoot problems when it won’t boot or other prob-
lems arise. Since the Pi has no BIOS, the screen won’t show you anything at all until
the Pi successfully boots. That’s where these little lights come in handy.
Figure 1-2.
Model B LEDs
Table 1-1. Status LEDs on the Raspberry Pi Model B
NUMBER LABEL COLOR FUNCTION
D5 OK (Rev 1.0) ACT (Rev 2.0) Green SD card access, connected to GPIO 16
D6 PWR Red 3.3 V Power, connected to 3.3 V
D7 FDX Green Full Duplex LAN
D8 LNK Green Link/Activity LAN
D9 10M (Rev 1.0) 100 (Rev 2.0) Yellow 10/100Mbit LAN
The first two lights (D5 and D6) are the most important pair when you want to make
sure that your problem isn’t as simple as “it’s not plugged in.Table 1-2 describes the
most common indicators you’ll see on these lights.
7
CHAPTER 1: CONFIGURATION HACKS
Table 1-2. Common LED Error Codes
LIGHT INDICATION MOST LIKELY PROBLEM
Red PWR light off No power
Red PWR light on, green OK light off The Pi can’t read the image on the card. The voltage is below 5V.
Green OK light blinks 3 times* start.elf was not found
Green OK light blinks 4 times* start.elf did not launch
Green OK light blinks 7 times* kernel.img was not found
Note that the flash patterns identified with an asterisk in Table 1-2 are accurate for
the firmware available since October 20, 2012. Earlier firmware used different pat-
terns, and later firmware may change these indicators as well.
The two files it’s looking for, start.elf and kernel.img, absolutely must be on the boot
partition. The first, start.elf, is the GPU binary firmware image, and kernel.img, as
its name implies, is the Linux kernel. If the red PWR light is on, you know have power;
then it’s up to the green light to tell you what’s gone wrong.
If the green light doesn’t flash at all, the first thing you shuld do is check your SD card
in another computer. Make sure that the image is written correctly. If all of the file-
names look like somebody leaned on the keyboard, it did not write correctly! Format
it and start again. If it does look OK, plug in nothing but the power and the SD card,
then each of your other peripherals one at a time to see which is causing the problem.
If the green light does blink, refer to Table 1-2 for information about what has gone
wrong. Note that once start.elf has loaded, you’ll see “the rainbow” (four large
squares of color bleeding together). It should quickly go away as your Linux distro
continues to boot, but if it doesn’t, your problem is in the kernel.img file.
Blink Your IP Address Through the LEDs
Pidora offers some features specifically for running in headless mode, including
the use of the LEDs to communicate your IP address. See Hack #11 to learn how.
HACK 04 Update the Firmware
The firmware your Raspberry Pi requires comes with any Linux distribu-
tion you choose, but it’s frequently updated upstream, and your project
might benefit from (or require) a more recent version.
8RASPBERRY PI HACKS
The Raspberry Pi is a little different from your laptop, and even different from a lot of
traditional embedded computers. The heart of the Raspberry Pi is the Broadcom
BCM2835 system-on-chip, which is the CPU, GPU, and memory all combined in a
single component. This detail is important, because the Raspberry Pi actually boots
from the BCM2835 GPU. When you provide power to the Raspberry Pi, the CPU in the
BCM2835 system-on-chip is actually disabled!
The Raspberry Pi boots like this:
1. First-stage bootloader: A bootloader programmed into the BCM2835 system-
on-chip hardware mounts the FAT32 boot partition from the Linux distribution on
the SD card. Note that this first-stage bootloader is programmed at manufacture
time and is not modifiable or replaceable. A small, dedicated RISC core on the
Raspberry Pi GPU starts this process.
2. Second-stage bootloader: Read off the boot partition on the SD card, this firm-
ware (bootcode.bin) accesses the additional GPU firmware files, programs those
firmware files into the Raspberry Pi GPU, and then starts it.
3. GPU firmware: This firmware (start.elf) allows the GPU to enable the CPU. An
additional file, fixup.dat, configures the SDRAM partition between the GPU and
the CPU. At this point, the CPU is released, and execution is transferred to it from
the GPU.
4. User code: The CPU boots any supported binary, but the Linux kernel is the de-
fault. It assumes the filename is kernel.img, but you can be override the default
in config.txt.
Versions of the Raspberry Pi firmware prior to October 19, 2012 contained an ad-
ditional third-stage bootloader (loader.bin), but this is no longer required or used.
Previous builds also had different versions of the GPU firmware that had to be
swapped in and out to enable different memory splits between the ARM CPU and
GPU, but this is now configured in config.txt.
Because of how the Raspberry Pi boots, you must use an SD card to boot the Rasp-
berry Pi; you cannot boot it from any other device (such as network or USB storage)
alone. But this is a good thing. It prevents you from rendering the device unusable,
because you cannot override the first-stage bootloader. If you end up with damaged,
broken, or incomplete firmware, you can simply start over with a clean SD card.
The Raspberry Pi Foundation provides the firmware files that the GPU loads, which
then enable the Raspberry Pi to boot a specially formatted Linux kernel image. All the
Linux distribution images intended for use on the Raspberry Pi come with a copy of
this firmware, but it is constantly updated upstream. To enable new functionality (or
9
CHAPTER 1: CONFIGURATION HACKS
boot newer Linux kernels), you will want to make sure you are running the latest revi-
sion of the firmware.
The upstream home for the Raspberry Pi firmware is https://github.com/raspberrypi/
firmware/. There is currently no source code available for these firmware files, so this
repository contains only binary versions. Because the Raspberry Pi is so slow (espe-
cially for Git operations), we strongly recommend that you check out these files to
your x86 laptop.
First, you need to make sure you have a Git client installed by running the following
command on Fedora:
$ yum install git
or this command on Debian/Ubuntu:
$ apt-get install git-core
Next, create a working directory for Raspberry Pi related files, such as ~/raspi:
$ mkdir ~/raspi
Go into the raspi directory:
$ cd ~/raspi
Use Git to get a local copy of the firmware files:
$ git clone https://github.com/raspberrypi/firmware.git
This will create a checkout in a new directory, named firmware. By default, this checks
out the master branch, which at the time of this writing was synced up to the version
of the firmware currently used by the Raspbian Linux kernel (3.2). If you are using a
3.2 kernel, this is the firmware you want to use. Another branch (named next) enables
the updated drivers in the 3.6 Linux kernel. If you want to use this branch, change into
the firmware directory and enter:
$ git checkout next
To switch back to the master branch, enter:
$ git checkout master
If you want to update your firmware again later, you don’t need to check out this tree
again. Simply go to the top-level checkout directory (~/raspi/firmware) and enter:
$ git pull
Remember, this will pull changes for the current branch only. If you want to pull
changes for the other branch, you will need to switch to the other branch with the Git
checkout command and run git pull there as well.
10 RASPBERRY PI HACKS
Now that you have checked out the repository and chosen your branch, your next step
is to copy the boot firmware onto the SD card that has the Raspberry Pi Linux distri-
bution image. To do this, you’ll need to make sure the partitions on that SD card are
properly mounted (covered in detail in Hack #02).
From here on, we will assume that the boot partition from your SD card with the Rasp-
berry Pi Linux distribution image is mounted at /mnt/raspbi-boot. Current versions of
Fedora (including Pidora) will automount it to /run/media/$USERNAME/boot, where
$USERNAME is your username, so if you have it mounted somewhere else, substitute that
mount point in the next set of instructions.
To update the firmware on the boot partition, all you need to do is copy the right files
from the firmware/boot directory into the mounted boot partition (as root).
You probably do not want to copy all of the files from this directory.
You’re looking for these critical firmware files in the firmware/boot directory:
bootcode.bin
fixup.dat
start.elf
We strongly recommend that you back up the existing (and presumably) working
copies of these files at this point. You can accomplish this by renaming these files (as
root) in the mounted boot partition first:
$ su -c 'mv /mnt/raspi-boot/bootcode.bin /mnt/raspi-boot/bootcode.bin.back
up'
$ su -c 'mv /mnt/raspi-boot/fixup.dat /mnt/raspi-boot/fixup.dat.backup'
$ su -c 'mv /mnt/raspi-boot/start.elf /mnt/raspi-boot/start.elf.backup'
Copy each of these firmware files (as root) into the mounted boot partition:
$ cd ~/raspi/firmware/boot/
$ su -c 'cp -a bootcode.bin fixup.dat start.elf /mnt/raspi-boot/'
su versus sudo
The command example used here for copying firmware files (along with
most other command examples in this book) use su. The su command will
prompt you for the root password of your Linux laptop. If you have config-
ured sudo for use on your Linux laptop, you can replace the su -c command
with sudo and the command to copy the firmware files (as root) will look like
this instead:
11
CHAPTER 1: CONFIGURATION HACKS
$ sudo cp -a bootcode.bin fixup.dat start.elf /mnt/raspi-boot/
Whichever method you prefer is fine, as they are both valid methods for
Linux operations as the root user. We use the su -c syntax in most examples
throughout the book for all root operations because it will work in all cases,
whereas sudo works only if it is configured for your user on that Linux dis-
tribution. If you an encounter instructions prefaced with sudo, know that su
is an option when you don’t have sudo configured.
When the new Raspberry Pi firmware finishes copying onto the boot partition, run the
sync command to ensure the data has all arrived onto the SD card:
$ sync
Then it should be safe to unmount the SD card partition(s) and eject the SD card. You
can unmount these partitions from the GUI interface of your Linux laptop, or you can
manually unmount them from the terminal by changing into a directory that is not in
either of the mounted partitions and then enter:
$ cd ~
$ su -c 'umount /mnt/raspi-boot'
$ su -c 'umount /mnt/raspi-root'
At this point, the SD card will contain the new firmware. You’ll know that the update
worked if the Raspberry Pi still boots into the Linux image, but at a minimum, the
firmware will draw a multicolored “rainbow” box (see “Somewhere Over the Rain-
bow... sidebar) to the configured output device (usually an HDMI connected one) as
its first step in the boot process (unless you have explicitly disabled this behavior in
config.txt). If that occurs, the firmware is properly installed onto the SD card.
Somewhere Over the Rainbow
Hopefully, if everything goes well with your Raspberry Pi, you’ll never have
to see the “rainbow” screen (shown in Figure 1-3) for more than a fraction
of a second when it boots up. The screen is generated by the Raspberry Pi
firmware as it initializes the GPU component of the BCM2835 system-on-
chip.
To test that the output works successfully, the GPU draws four pixels on the
screen and then scales those pixels to be very large, resulting in the multi-
color screen. If your Raspberry Pi ever refuses to go over the rainbow and
into a proper Linux boot, it means that the configured Linux kernel image
(default: kernel.img) was not able to boot.
12 RASPBERRY PI HACKS
Figure 1-3.
The “rainbow” screen (uploaded to http://elinux.org/File:Debug-screen.jpg by user Popcorn-
mix and shared under the terms of the Creative Commons Attribution-ShareAlike 3.0 Unpor-
ted License)
Some optional versions exist for some of the Raspberry Pi firmware files. It is possible
to configure the Raspberry Pi to dedicate the minimum amount of memory to the GPU
(16 MB). When this is done, the Raspberry Pi Second Stage Bootloader looks for
start_cd.elf and fixup_cd.dat instead of start.elf and fixup.dat. Hack #24 provides
a longer discussion on GPU/CPU memory splitting.
HACK 05 Monitor the Raspberry Pi Hardware
Worried that your Pi is throwing wild parties while you’re out of the house?
Here’s how to point a webcam at it and stream the video to the Internet.
Just kidding! These tools can monitor the physical state of your tiny
hardware.
A “normal” Linux computer would likely include onboard health monitoring sensors.
Quite a few monitoring chips and components are used in various systems, but on the
Raspberry Pi, all of that hardware is entirely hidden inside the Broadcom system-on-
chip, so you can’t access it with those usual methods.
To reach those components to monitor your Pi’s health, you need to use the vcgencmd
utility. It should be preinstalled with any of the general-purpose Raspberry Pi Linux
distributions available, but if it’s not, you can get a copy from the firmware tree at
https://github.com/raspberrypi. If your distribution is compiled for ARM hardware
floating point, look in the hardfp/ subdirectory; otherwise, look in the opt/ subdirec-
tory.
Checking for Hard Float
At the time of this writing, most Linux distributions (including Pidora, Rasp-
bian, Occidentalis, OpenELEC, and RaspBMC) are built for the ARMv6 hard-
float architecture, because that gives the best possible performance on the
Raspberry Pi. However, some older releases of these targets (and other OS
platforms) were built with optimization for ARMv6 soft-float. These two op-
13
CHAPTER 1: CONFIGURATION HACKS
timization levels are not compatible with each other. On Linux, there is a
good way to check for support for ARMv6 hard-float, using the readelf
command:
$ readelf -a /usr/lib/libc.so.6 | grep FP
You can run this command directly on the Raspberry Pi Linux distribution
(you might need to install the elfutils package first), or you can copy a
binary or library from within the Raspberry Pi Linux distribution and onto
another system with readelf handy.
If the binary has support for ARMv6 hard-float optimization, you will get
output that looks like this:
Tag_FP_arch: VFPv2
Tag_ABI_FP_rounding: Needed
Tag_ABI_FP_denormal: Needed
Tag_ABI_FP_exceptions: Needed
Tag_ABI_FP_number_model: IEEE 754
Tag_ABI_HardFP_use: SP and DP
Tag_ABI_VFP_args: VFP registers
The important line is the last one, Tag_ABI_VFP_args: VFP registers. It will
show up only if the binary being checked is built with ARMv6 hard-float
optimization.
Once you’ve installed it (if necessary), look at the options that vcgencmd offers:
$ vcgencmd commands
This will output a list of all the commands that you can pass to the vcgencmd tool:
commands="vcos, ap_output_control, ap_output_post_processing,
vchi_test_init, vchi_test_exit, pm_set_policy, pm_get_status,
pm_show_stats, pm_start_logging, pm_stop_logging, version, commands,
set_vll_dir, led_control, set_backlight, set_logging, get_lcd_info,
set_bus_arbiter_mode, cache_flush, otp_dump, codec_enabled, get_camera,
get_mem, measure_clock, measure_volts, measure_temp, get_config,
hdmi_ntsc_freqs, hdmi_status_show, render_bar, disk_notify, inuse_notify,
sus_suspend, sus_status, sus_is_enabled, sus_stop_test_thread, egl_plat
form_switch, mem_validate, mem_oom, mem_reloc_stats, file, vctest_memmap,
vctest_start, vctest_stop, vctest_set, vctest_get"
Unfortunately, it doesn’t actually tell you anything about those commands or what
they do. Some of them seem obvious, but then when you run them, they return things
like this:
error=2 error_msg="Invalid arguments"
14 RASPBERRY PI HACKS
The tool is poorly documented, but the Raspberry Pi community has come together
and figured some of them out.
Measure Component Voltage
The vcgencmd measure_volts command shows the voltage for some of the key Rasp-
berry Pi components, specifically:
core
The GPU processor core
sdram_c
The SDRAM controller
sdram_i
The SDRAM input/output (I/O)
sdram_p
The SDRAM physical memory
Each of these components can be passed as an option to the vcgencmd meas
ure_volts command (if you don’t specify one, it will return the value for core).
You might be wondering why you’d care about measuring these voltages, and in most
cases, you probably don’t. They’ll sit happily as shown in Table 1-3.
Table 1-3. Components voltage
COMPONENT VOLTAGE
core 1.20
sdram_c 1.20
sdram_i 1.20
sdram_p 1.23
The only time you might care about the component voltages is if you decide you want
to overclock your Raspberry Pi. All of these voltages are configurable (as covered in
detail in Hack #06).
You might expect this command to return the system board voltage (which varies
between 4.75V and 5.25V under normal conditions), but it doesn’t. See Hack #09 for
how to do that manually.
15
CHAPTER 1: CONFIGURATION HACKS
Measure Temperature
The vcgencmd measure_temp command reports the core temperature of the BCM2835
system-on-chip on your Raspberry Pi (in Celsius):
temp=44.4'C
Alternatively, you can get the same temperature reading by reading this value directly
from /sys/class/thermal/thermal_zone0/temp:
$ cat /sys/class/thermal/thermal_zone0/temp
44388
Fun with Math and Science
To convert that value to the Celsius temperature, simply divide it by 1,000.
To get Fahrenheit, multiply the Celsius temperature by 1.8 and add 32. To
get Kelvin, add 273.15 to the Celsius temperature. Is it getting hot in here,
or is it just us?
From the perspective of monitoring the Raspberry Pi hardware, this reading is prob-
ably sufficient. Since there is really no separation of the CPU/GPU (at least not from
a physical or heating perspective), this gives you an idea of how hot the board is run-
ning. That said, if you want a more detailed (or just an additional) temperature reading,
you can wire in an additional temperature sensor, as described in Hack #37.
Monitor Memory Split
Whether hardcoded or dynamically allocated, the vcgencmd get_mem command returns
the value for either the ARM CPU or the video GPU.
To see the amount of memory currently split off for the ARM CPU, run:
$ su -c 'vcgencmd get_mem arm'
arm=448M
To see the amount of memory currently split to the video GPU, run:
$ su -c 'vcgencmd get_mem gpu'
gpu=64M
Check Custom Configuration Overrides
Have you forgotten what configuration changes you have made to your Raspberry Pi?
Specifically, the ones that change settings in the firmware? While you could look
in /boot/config.txt, the vcgencmd get_config command is here to help you.
16 RASPBERRY PI HACKS
To see all configurations with a number (integer) datatype, run:
$ su -c 'vcgencmd get_config int'
arm_freq=900
To see all configurations with a text (string) datatype, run:
$ su -c 'vcgencmd get_config str'
There are very, very few configuration options that store string values instead of
integers. Don’t be too surprised if the vcgencmd get_config str command doesn’t
return anything.
If you just want to check the value of a specific configuration, pass that config name
instead:
$ su -c 'vcgencmd get_config arm_freq'
arm_freq=900
The vcgencmd utility is not the most user-friendly tool, but it does have a deep con-
nection into the inner workings of the Raspberry Pi. Since this tool is open source (and
the source code is available in the aforementioned Raspberry Pi GitHub firmware
checkout), if you want to go very deep into the inner workings of the Raspberry Pi
hardware, looking at the vcgencmd source code is a good jumping-off point.
HACK 06 Overclock Your Pi
The Raspberry Pi is not a notably fast computer. For most projects, it is
more than capable of providing enough performance to get the job done,
but for other projects, you might want to overclock the hardware to get
a little bit more horsepower.
The Raspberry Pi hardware is preconfigured to what the manufacturer believes is the
best balance of reliability and performance. Now that we’ve stated that for the record,
it also comes with a lot of tuning knobs, and if you are feeling brave, you can turn them
up to get extra performance out of the hardware.
This is what the cool kids call overclocking. People have been overclocking their com-
puters since the beginning of the PC era, but it really became common when owners
realized that the only difference between the high-end and low-end model of the same
Intel CPU was whether it passed speed tests. The ones that passed got labeled at the
higher clock speed, while the rest got the lower clock speed. If you were lucky, you
could adjust settings to get a higher clock speed.
17
CHAPTER 1: CONFIGURATION HACKS
These days, overclocking refers to changing any sort of setting to get performance
above and beyond the default configuration of the hardware. As an example, some
people have resorted to any number of tricks and hacks to get a performance boost,
including immersing the entire system in liquid nitrogen cooled Flourinert. Some peo-
ple are crazy.
This is an excellent time to warn you: trying to overclock your Raspberry Pi will
almost certainly make the hardware burn out quicker, possibly immediately. It will
also probably not double your performance, and if by some miracle it did, you
probably wouldn’t be able to run anything reliably on the overclocked Raspberry
Pi.
Then again, this is a $35 PC. You live only once. (When you decide to really take
that advice to heart, try Hack #40.)
Remember that the heart of the Raspberry Pi is a Broadcom system-on-chip, with an
ARM CPU, a Videocore IV GPU, and 512 MB of RAM. Each of these parts have its own
clock frequencies, and the GPU has adjustable clock frequencies for its subcompo-
nents. Specifically, the GPU has a core frequency, an H264 frequency (the H264
hardware video decoder block), a 3D processor frequency, and an image sensor pro-
cessor frequency.
You can tweak all of these settings by changing options in /boot/config.txt. This file
may or may not exist; if it does not, just create a new empty file.
Increase ARM CPU Frequency
Let’s start with the most obvious overclock: the ARM CPU. The frequency of the ARM
CPU (arm_freq) defaults to 700 MHz. To speed it to 900 MHz, add this line to /boot/
config.txt:
arm_freq=900
Then, when you reboot, the hardware will try its best to honor your request. But re-
member, this isn’t magic. No matter how badly you want to put 30000000 as the fre-
quency, it isn’t going to work. People with a lot of experience overclocking hardware
have determined that the Raspberry Pi does not usually successfully overclock be-
yond 900 MHz, unless you use overvolting (see Hack #07).
Increase SDRAM Frequency
Another simple way to overclock is to increase the frequency of the SDRAM memo-
ry. The frequency of the SDRAM memory (sdram_freq) defaults to 400 MHz. You can
usually increase this value to 500 Mhz without issue by adding this line to /boot/
config.txt:
18 RASPBERRY PI HACKS
sdram_freq=500
Just like with arm_freq, you’ll need to reboot your Raspberry Pi for this to take effect.
Increase GPU Frequency
Your last major overclocking option is the GPU components, the frequencies of which
are all defined by gpu_freq and default to 250 MHz.
gpu_freq is a sort of super setting. Setting it assigns the same value to the core_freq
(GPU processor core frequency), h264_freq (hardware video block frequency),
isp_freq (image sensor pipeline block frequency), and v3d_freq (3D block frequen-
cy). If you have a GPU-intensive task, you might get some extra performance by in-
creasing the gpu_freq to 325. You can do this by adding this line to /boot/config.txt:
gpu_freq=325
That said, we don’t recommend changing the gpu_freq value, because it will take per-
formance away from the CPU. Instead, you might try just changing the core_freq value.
If you do this, it is important to keep all of the GPU frequencies (listed previously)
either the same or different by a factor of an integer multiplier. If you do not do this,
the GPU components will receive a mixture of incompatible pulses and things will stop
working very quickly.
However, because the core_freq value also includes the L2 cache and some of the
SDRAM memory clock cycles, increasing just that value could give the ARM CPU a
performance boost. Multiply the default value by 2 (the largest integer that will really
work) and set the value to 500 in /boot/config.txt like this:
core_freq=500
Note that this might not work. Some people report success, while others report
failure. If you try to mix this core_freq change in with the other overclocking fea-
tures, it might work only when they are set low (or left at the default).
We cannot emphasize this enough: sometimes, when overclocking fails, it does so
in less-than-obvious ways. Reliable programs become buggy, hardware devices
stop working at random, and the system might just reboot for no good reason.
When you do overclock, you’ll want to have a quantifiable test case that you can run
over and over again to see what gives you the best performance for the workload that
you care about on your specific Raspberry Pi. Do not simply download a canned
benchmark and trust it. A benchmark designed to show GPU performance will not
help you optimize your overclocked Raspberry Pi system for tasks that are CPU-
bound.
19
CHAPTER 1: CONFIGURATION HACKS
Pretested Overclock Presets
Newer versions of the Raspberry Pi firmware contain the option to choose between
five overclock (turbo) presets that try to get the most performance out of the SoC
without impairing the lifetime of the Pi. This is done by monitoring the core temper-
ature of the chip and the CPU load and dynamically adjusting clock speeds and the
core voltage.
So, when there is a low demand on the CPU, or it is getting too hot, the performance
is throttled down, but if the CPU has much to do, and the chip’s temperature allows
it, performance is temporarily increased, with clock speeds up to 1 GHz, depending
on the individual board and which of the turbo settings is used. Table 1-4 details the
current settings of the five overclock presets.
Table 1-4. Overclock presets
PRESET ARM CORE SDRAM OVERVOLT
None 700 250 400 0
Modest 800 250 400 0
Medium 900 250 450 2
High 950 250 450 6
Turbo 1000 500 600 6
If you are running a current version of Raspbian, you will notice that the raspi-
config tool has support for configuring your Pi into any of these five presets. For other
distributions, you will need to define the preset you want to use in /boot/config.txt
by passing the values for each option individually. For example, to set the Medium
preset, add these lines to your /boot/config.txt:
arm_freq=900
core_freq=250
sdram_freq=450
over_voltage=2
Also, just because the Turbo setting has been known to work with some Raspberry Pi
units, that doesn’t mean it will work with yours. Quite a few users have reported SD
card corruption when trying to run their Raspberry Pi at that overclock preset.
HACK 07 Overvolt for Higher Performance
Overvolting, also known as “dynamic voltage scaling to increase voltage,
is a trick to get more performance out of an electrical component.
The circuits in your Raspberry Pi are made up of transistors that act as logic gates or
switches. The voltage at these nodes switches between a high voltage and a low volt-
20 RASPBERRY PI HACKS
age during normal operation. When the switch changes, the capacitance of the tran-
sistor and the voltage applied affect how quickly the switch output changes. Config-
uring a circuit to use higher voltage (“overvolting”) allows the circuit to react faster,
which permits you to overclock the hardware further than what would normally be
possible.
The Raspberry Pi firmware exposes some configurable voltages, which map up with
the following values in /boot/config.txt:
over_voltage (core)
over_voltage_sdram_c
over_voltage_sdram_i
over_voltage_sdram_p
If you do overvolt your Raspberry Pi by changing any of these settings, it might
permanently set a fuse in your BCM2805 system on chip. That means that the
vendor will know if you overvolt the hardware, it burns out, and you try to return it
as defective. We shouldn’t have to say that it’s not OK to return things as defective
when you were responsible, but you should be aware that this is warranty-voiding
behavior.
The biggest change comes from adjusting the over_voltage value, which is the core
voltage for the ARM CPU and GPU in the BCM2835. The possible values for over_volt
age run from -16 (0.8 V) to 8 (1.4 V), with default value at 0 (1.2 V). Each integer above
(or below) 0 steps the voltage by 0.025 V. You cannot go over 6 without also setting
force_turbo=1 (note that this will probably trip the “warranty voided fuse”).
The over_voltage configuration setting is a super-setting; changing it applies the value
to the over_voltage_sdram_c (SDRAM controller voltage), over_voltage_sdram_i
(SDRAM I/O voltage), and over_voltage_sdram_p (SDRAM physical voltage) settings.
It is possible to set those settings independently, but you are far more likely to get
them wrong (or mismatched) and end up with memory corruption, so we strongly
recommend that you use the over_voltate super-setting instead.
If you decide to overvolt, just set these configuration options in /boot/config.txt, and
then reboot.
When you’re overvolting (or overclocking as well), monitoring the voltage levels of the
components you’ve bumped up suddenly makes more sense. These methods can
nudge out a tiny bit more performance from the hardware, but you’re trading that
extra bit of performance for a reduction in hardware lifetime (and possibly stability as
well).
21
CHAPTER 1: CONFIGURATION HACKS
HACK 08 Get More USB Ports
The Raspberry Pi Model B has two dedicated USB connector ports, but
really, that just isn’t enough for an awful lot of use cases. Here’s how you
can hack in a few more.
Universal Standard Bus (USB) has become the de facto standard connector for com-
puting accessories. Keyboards, mice, hard drives, joysticks, flashlights, and even foam
missile launchers all connect via USB. The Raspberry Pi (Model B) comes with two
dedicated USB 2.0 ports to allow you access to this wide world of peripheral goodness,
but these ports get used up quickly. The normal use case of a keyboard and mouse
will use up both of these connectors, and you’re left with no place to put anything else!
This is not a new problem for computer users. Laptops usually come with one to three
USB connectors as well, even though a single USB host controller can support many
more devices running simultaneously on the same BUS (up to 127 devices, to be pre-
cise). The trick to getting more is to use a USB hub.
Once upon a time, USB hubs were expensive. That time is long past. In fact, they’re
regularly given away for free. But there is a catch with these USB hubs. They come in
two flavors:
Bus powered
This type of USB hub draws all its power from the host computer’s USB interface
and is the type you’re likely to acquire as a free giveaway or in the cheap-stuff bin
at the electronics store.
Externally powered
Also known as self-powered, this type of USB hub has an external power supply
and uses it to provide full power to each USB connector on the hub.
USB 2.0 current is allocated in units of 100 mA (called unit loads), up to a maximum
total of 500 mA per port. This means that if you are using a bus-powered hub, in the
best possible scenario (getting 500 mA from the host computer), it can power four
devices. That’s what the specification says, so it must be true, right? But in the real
world, this isn’t quite the case.
For starters, the USB hub needs some power to run, so it won’t be able to take the
500 mA from the host computer and give it all to the ports. Even if we assume it is an
extremely efficient device (they usually are not), that means it can provide one unit
load to four devices at once. But that’s not the whole story.
The USB specification is pretty loose as specifications go (partially as a result of its
ubiquity), and lots and lots of devices want more than 100 mA to work properly—most
notably, wireless networking USB devices and keyboards with fancy features (LCD
displays, integrated USB hubs, backlights, blenders, etc.). These devices are classified
22 RASPBERRY PI HACKS
as high-power USB devices and can use up to the maximum of five unit loads (500
mA) per port. They are rarely (if ever) labeled as such, and they look visually identical
to low-power (single-unit load) devices.
On top of all that, the dedicated USB connectors on the Raspberry Pi provide only one
unit load (100 mA) per port instead of the five unit loads that a “normal” computer
would. This amount isn’t nearly enough to power a bus-powered hub with anything
else connected to it, so that won’t work for you at all. The free (or extremely cheap)
USB 2.0 hubs? They are always bus powered. Sorry. You’re going to have to buy
something a little nicer.
This is why if you connect a high-power USB device directly to the Raspberry Pi, it will
either attempt to operate in low-power mode (sometimes these devices can do that),
or the Raspberry Pi will simply power off or refuse to see the device. The majority of
high-power devices will detect at low power, then try to pull additional power when
put into active use (this is particularly common with wireless devices), resulting in a
confusing scenario where the device appears to work, and the Linux kernel drivers
load, but it doesn’t actually work reliably or properly.
The solution to this problem space for the Raspberry Pi is to use an externally powered
USB hub. You will want to use a good one, though, because there are plenty of awful
choices here as well. It is common for the manufacturers of these USB hubs to cut
corners and design the hub to run off of a low-amperage power supply. They do this
because they assume that most of the devices you will connect to it are low powered
and that you will not have all of the ports used at once.
It is not uncommon for inexpensive, seven-port hubs to use a 1 A power supply. If each
of those seven ports is connected to a high-power (five unit loads, 500 mA) device,
they would need a 3.5 A power supply. More, really, because the hub needs power too!
To be safe, you should assume the opposite from what these cost-cutting manufac-
turers do. Just assume that any USB device you want to connect to your Raspberry
Pi is high powered and that each port in your USB hub will have a high-powered device
connected to it. Then it is a simple math problem to confirm if a USB hub will be a
good choice:
1. Take the number of ports on the USB hub, and add 1 (to account for the USB hub
itself).
2. Multiply that number by the size of a high-power load (.5).
The result will be the number of amps that the power supply for your USB hub should
be providing (at a minimum).
23
CHAPTER 1: CONFIGURATION HACKS
Even if you do use an externally powered USB hub, you might still run into issues using
it with the Raspberry Pi. Some hubs will send power across the USB interconnect cable
(the cable connecting the USB hub to the Raspberry Pi). This is called backpower.
The standard says that hubs aren’t supposed to do this, but plenty of them do. Back-
power can result in a situation where the connected USB hub has power before the
Raspberry Pi has power (across the standard micro-USB power connector), which
would cause the Raspberry Pi to be in a partially powered-on state. While partially
powered on, your Raspberry Pi might start to make unwanted writes to the SD card.
To avoid this, you can plug the USB hub’s power supply and the power supply for your
Raspberry Pi into the same power strip, then use the switch on the power strip to
power them on simultaneously.
The Pi Hut sells a seven-port USB hub designed specifically to be ideal for the Rasp-
berry Pi. It avoids the need for careful power-on ordering, because it will never feed
any power back over the interconnect cable. Sadly, however, it has only a 2 A power
supply, which means you can have high-power devices (using five unit loads) on only
three ports at once, with the leftover power going to the hub. Still, this unit is designed
not to backpower, so you’ll never have to worry about that.
There is also a four-port hub that is known to not have backpower issues. Even though
it also has a 2 A power supply, you’re arguably less likely to exceed that on a four-port
USB hub than you would be on a seven-port USB hub.
The best hub for the Raspberry Pi that we’ve seen so far is the PIHUB. It is a four-port
externally powered hub with a 3 A power supply, and it is in the shape of the Raspberry
Pi logo. They don’t have a U.S. version at the time of this writing, but they say it is
coming soon!
HACK 09 Troubleshoot Power Problems
The Pi doesn’t need a lot of power, but that also means that it needs what
it’s asking for, and you can run into trouble when it gets too much or too
little.
The Raspberry Pi runs off a 5 V (DC) power source, pulled either from a dedicated
Micro USB Type B port (labeled as Power on the board) or via the GPIO expansion
(labeled as P1 on the board) pins, specifically the 5 V pins at P1-02 and P1-04.
24 RASPBERRY PI HACKS
If you have a charger for most Android phones, you have the Pi’s power cable (sorry,
iPhone fans). It is possible (but not the best scenario and might not work at all) to plug
the other end into the USB port of your computer rather than the wall. And for other
projects, you’ll want to get power through the GPIO. That said…
Think Twice Before Using the GPIO to Power the Pi
Before you rush to input 5 V over the GPIO pin, remember that when you do this you’re
bypassing the hardware’s input fuse. That fuse is there to protect your hardware in
case of malice or stupidity.
For example, imagine that you think you’re passing 5 V, but you’re actually passing
more than that into the Raspberry Pi via the GPIO. That might be because you weren’t
entirely clear on what you were doing, or it could just be an accident. Either way, out
comes magic smoke! And by “magic,” we mean, “that project just disappeared like a
bunny in a hat!”
Plenty of power supplies aren’t perfectly “clean,” meaning it might say “5 V,” but what
it means is “more or less 5 Vish.” Even if it just spikes above 5 V, you’re bypassing
the transient-voltage-suppression (TVS) diode!
That diode is what would normally protect the Raspberry Pi from those unexpected
voltage spikes (by shunting away the excess current when it exceeds the avalanche
breakdown potential), but you’re just going right around it. And then out comes the
magic smoke.
Last, but not least, you have to put regulated 5 V into the GPIO, and most power
adapters do not output regulated voltage. This means you need to have a voltage
regulator circuit between the GPIO pin and the power adapter.
For all of these reasons, we highly recommend you just feed power into the Micro USB
Type B port, unless you have a truly excellent reason not to.
Do Not Backpower the Pi over USB
Hack #08 explains how some USB hubs will backpower over the interconnect cable,
which can actually partially power the Raspberry Pi. Do not do this.
USB hubs are not supposed to backpower. This is not regulated or reliable power in
any real sense. It can (and likely will) result in unpredictable behavior including (but
not limited to) unexpected program failures, kernel panics, and SD card corruption.
25
CHAPTER 1: CONFIGURATION HACKS
I Still Want to Backpower the Pi!
OK, fine. There is a reasonably reliable way to do this. Some industrious
hackers in Australia had a custom USB 3.0 hub produced with the explicit
purpose of providing backpower for a Raspberry Pi.
Specifically, the interconnect port on their hub will send over the 1000 mA
(1 A) that the Raspberry Pi needs for normal operation. This will power the
Pi entirely off the connection to the USB hub (no separate power source is
necessary). You can check it out here:
http://www.buyraspberrypi.com.au/shop/4-port-usb-3-0-powered-usb-
hub/
The only downside to using this hub is that it has only a 2 A power supply,
and 1 A is going to the Raspberry Pi, leaving a little less than 1 A (some of
that needs to go to the hub itself) for the connected devices. That doesn’t
leave a lot of room for too many high-power devices (.5 A at maximum five-
unit load).
Get Power Through GPIO Safely
Note that there is a big difference between using the Raspberry Pi GPIO pins to power
an attached device and pushing 5 V into the GPIO to power the Raspberry Pi. Lots of
the hacks in this book need to draw some current from the GPIO pins, and this is safe
to do.
There are 3.3 V pins (P1-01 and P1-17), in addition to the 5 V pins (P1-02 and P1-04).
Maximum permitted current draw from the 3.3 V pins is 50 mA. Maximum permitted
current draw from the 5 V pins varies between the Raspberry Pi Model A and Model
B hardware. The value for the maximum permitted current draw from the 5 V pins is
calculated by starting with the USB input current (nominally 1 A), then subtracting
the current draw from the rest of the board.
On the Model A, the board has a current draw of 500 mA, so the max current draw off
the 5 V pin is 500 mA. On the Model B, because it has a higher current draw on the
board of 700 mA, the max current draw off the 5 V pin is 300 mA.
Remember, be very, very careful with those 5 V pins! If you short 5 V to any of the other
GPIO P1 pins, you’re likely to fry the entire Raspberry Pi. While deep-fried raspberry
pie sounds like a delightful carnival snack, a fried Raspberry Pi circuit board is neither
tasty or desirable.
26 RASPBERRY PI HACKS
Solve Power Problems
Now that you’ve reviewed your power options, you have to figure out what to do when
things go awry.
When the power is too low (or the current is too low), the Raspberry Pi starts to act…
well, the technical term is “weird.” USB devices might not show up, or they might blink
in and out randomly. Software might not run reliably. Cats and dogs living together,
mass hysteria!
If things are just being “weird,” there’s a good chance insufficient power is to blame.
There are two main reasons why this can happen, even when you think you’ve done
everything right: a subpar power supply or a faulty Micro USB cable.
Get a better power supply
It’s the opposite of that power spiking problem mentioned in “Think Twice Before
Using the GPIO to Power the Pi” on page 25. It says “5 V,” but what it means is, “I might
consider delivering 5 V on my best day when all the stars are aligned and you perfectly
hum the Doctor Who theme song backward to appease my cranky nature.” But they
couldn’t fit all those words on the plug, so they just put “5 V.” (Or at least that’s our
theory.)
Sadly, this is a common scenario. A lot of cheap Micro USB cell phone chargers are
cheap for a good reason: they don’t work very well. (Did you buy it at a dollar store?
That could be a clue it’s a cheap one.)
When it’s for your phone, it’s no big deal. It just takes longer to charge your battery.
But the Raspberry Pi won’t take so kindly to the drop in desired power.
The best way to avoid this is to buy a proven reliable power supply. For example, Ada-
fruit sells an excellent 5 V 1A power supply that actually outputs 5.25, which makes up
for any voltage drop across the resistance of the USB cable between the power supply
and the Raspberry Pi.
Get a better micro USB cable
Your Micro USB cable is less likely to be subpar in quality than the power supply, but
it does happen. Cables have conductors in them that provide some resistance, but
that’s usually irrelevant.
For example, at 5 ohms and 50 mA of current, the voltage drop across the cable might
be about 250 mV. Most devices are OK with that, because the USB specifications
require that they be tolerant of voltage drops of that amount. However, some devices,
like the Raspberry Pi, want more power (especially if you have some hungry USB
devices plugged directly into the Raspberry Pi’s USB ports).
27
CHAPTER 1: CONFIGURATION HACKS
As mentioned previously in this hack, the Model B draws a peak current of 700 mA,
so if your USB cable has 5 ohms of resistance, it would result in a 3.5 V voltage drop.
As far as the Pi is concerned, that’s huge.
The good news is that most USB cables don’t have 5 ohms of resistance, and the really
good ones will be very close to 0. We haven’t really had problems with cables that
came with modern phones, which seems to be most people’s source of such cables.
If you need to purchase a USB Micro B cable, Mediabridge’s “USB charging cables”
test with a low resistance and are available on Amazon. Adafruit’s USB Micro B cables
also work fine in peak-current draw on the Model B.
Why Do USB Devices Cause My Pi to Reboot?
Hotplugging (plugging in a USB device when the Pi is already running) will
often cause the Pi to reboot. Plugging in the device causes a power spike,
which means a drop in power to the Pi, which leads to the reboot.
The Rev 1 board had two 140 mA polyfuses on the USB ports that prevented
this but caused other problems, so Rev 2 boards do not. If you do anticipate
the need to hotplug a device, do it through a powered USB hub.
Test Your Cable’s Resistance
If you have a cheap power supply, you can almost guarantee that’s your problem. But
if you think you have a problem with your cable and want to test its resistance, you
can either take the cable apart or you can use an accessible Micro USB Type B device
(something that has ground pins on it).
The USB Type A connector is big enough that you can get to the ground pin directly.
(It’s Pin 4, the first pin on the left if you’re looking down the cable with the hollow space
at the top of the connector.) Measure resistance with a calibrated multimeter set to
the lowest ohm setting from ground on the Micro USB-B connected device to ground
on the USB Type A connector to get a good idea of the cable’s resistance.
You can also get a little hardware tool to simplify this. Bitwizard B.V. makes a USB
prodder just for this purpose.
Some people have even made their own cables by soldering low-resistance wires to a
power supply and a Micro USB Type B connector. This is a neat hack if you just want
to try making cables, but it’s not really necessary.
28 RASPBERRY PI HACKS
Most modern USB cables do not seem to have serious resistance issues. If it will
charge a Micro USB Type B cell phone quickly and reliably, it is probably good enough
for the Raspberry Pi. If it won’t, a new one is generally easy and cheap to come by.
HACK 10 Unbreak Your Raspberry Pi
The Raspberry Pi hardware is pretty rugged for its size, but it does have
one notable weak point that you might discover. Here’s how to find it and
how to hack it back to life if it breaks.
The Raspberry Pi comes with a built-in self-destruct button that many people have
accidentally triggered the first time they plugged it in. OK, that’s not precisely true.
But the placement of one of the Pi’s fragile components makes it really easy to destroy
your new toy before you’ve gotten to play with it. Here’s what to do in case you broke
it before you got around to reading this hack.
Just behind the power connection on the board is a small silver cylinder (see
Figure 1-4). It’s called capacitor C6, and it’s a 220 μF, 16-volt, surface-mount electro-
lytic capacitor that smooths out the voltage going to the Pi. It also seems like a really
good spot to grip when you’re plugging in or unplugging your micro USB cable. It’s
not. Don’t touch it. It’s not a critical component, and your Pi could still work without
it, but it also might not.
Figure 1-4.
C6 is the black and silver cylinder beside the power connector
29
CHAPTER 1: CONFIGURATION HACKS
If you’re looking for a replacement in online stores, try searching with the terms
“220 uF 16v electrolytic capacitor.
The relative fragility of this piece’s connection is one of several good reasons to make
or buy a good case for your Raspberry Pi. Meanwhile, if you need to carry it around,
use the original static bag and box it came in.
Test Your Power Supply
If you do happen to break off the capacitor, and your Pi stops working, take consolation
in the knowledge that you’re not the only one, and though it’s not covered under war-
ranty, you have a few options. First, a new and better power supply might fix the prob-
lem. With a stable power supply, you shouldn’t have any problems.
If you don’t know whether your power supply is doing what it should (beyond the
obvious evidence of “it works” or “it doesn’t work”), you can test it. The first sign that
you’re not getting consistent or strong enough power is not an unworking Pi, but rather
an unreliable one.
When things start acting up mid-stream—all was fine at first, then maybe when you
get into the GUI, the peripherals stop working—that’s when it’s time to check your
voltage. The Pi has test points labeled TP1 and TP2 to help you. TP1 is just under the
Raspberry Pi logo, and TP2 is between the GPIO and the RCA out.
Set your multimeter to 20V in the DC range and touch the leads to TP1 and TP2. The
reading should be near 5 volts and certainly no more than 0.25 volts away in either
direction.
Replace the C6 Capacitor
If your Pi is still not working or if you just want the capacitor back on there, you can
solder a new one on.
Soldering on a new capacitor might make your Raspberry Pi as good as new. It
definitely will void your Raspberry Pi warranty.
When you solder it back on, note that the capacitor is polarized, and thus it is critical
to have the black stripe facing the edge of the board. For some basic soldering tips,
check out “Soldering Reminders” on page 42.
30 RASPBERRY PI HACKS
HACK 11 Go Headless
Even though the Raspberry Pi supports 1080p HDMI video out, there are
lots of projects where it is not cost effective or practical to connect it to
a video display. Here’s how to go without a monitor.
The Raspberry Pi is often touted as an inexpensive computer, but if you don’t have a
monitor and other assorted peripherals already available, the cost soars quickly. Also,
since one of the most appealing features of the Raspberry Pi for creative projects is
its diminutive size, you’re likely to discover that you need to run in “headless” mode:
no monitor, no keyboard, and no mouse. Just a Pi flying solo (perhaps literally if you’re
building Hack #44!). That’s when it’s time to run headless.
Change Your Root Password
Don’t forget to change your root password early on. It’s a good practice in general,
but it’s particularly important in headless mode. Most Raspberry Pi distros have
well-known default root passwords.
In general, your eventually headless Pi projects will begin life connected to a monitor
and input devices just to get everything ready. If nothing else, it seems like the easiest
way to get the IP address, which is the first step to being able to SSH to the Raspberry
Pi. However, if you use Pidora, you can go headless from the beginning, thanks to a
configuration option that bypasses the first boot process and is meant specifically for
going headless.
Once you’ve installed Pidora on your SD card (you can download the latest version
from http://www.pidora.ca), create a file called headless in the partition named boot.
For a static IP address, list it along with the netmask and gateway in the headless file:
IPADDR=192.168.1.123
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
You can also use this file to initiate rootfs-resize by adding:
RESIZE
If you would like to set the swap amount, add it here as well:
SWAP=512
If your Pi should obtain its IP address dynamically (DHCP), headless should stay emp-
ty. But then how do you find out what the IP address is? This is where Pidora’s headless
mode comes through for you!
31
CHAPTER 1: CONFIGURATION HACKS
Once you boot the Raspberry Pi with this headless file, the IP address will first flash
through the speakers two minutes after powering on. Thirty seconds later, it will flash
the IP address through the green OK/ACT LED. These functions are provided through
ip-info, a package that contains the aptly named ip-read and ip-flash. The flashes
indicate numbers in the following way:
Digits 1–9 are indicated with short flashes (e.g., three short flashes is a 3).
0 is indicated with 10 short flashes.
Digits are separated by a pause.
Dot (.) is indicated with a long flash.
You can read more about the ip-info package and download it at https://github.com/
ctyler/ip-info/.
As mentioned earlier, Pidora would usually run through the first boot process and have
you set up a root password and another user. But that script will run only if input
devices are found. Otherwise, the system configures the ethernet interface via IPv4
DHCP and assumes you’ll set up any other preferences you would have made at first
boot on your own.
HACK 12 Connect with SSH
For any headless project, as well as a matter of convenience when you’re
away from your project or just too lazy to walk across the room, you’ll
need to know how to SSH to your Raspberry Pi.
OpenSSH, the open source set of tools for secure communcation created by the
OpenBSD project, is likely available in any distro you choose.
If you’re going a little retro, note that “Squeeze,” the version of Raspbian before
“Wheezy,” didn’t have SSH running by default.
If you aren’t certain, all you have to do is attempt to SSH to your Pi, and you’ll find out
pretty quickly. Attach a monitor and keyboard, and then run:
$ service sshd status
'Redirecting to /bin/systemctl status sshd.service
sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: active (running) since Wed 2013-02-13 13:06:40 EST; 28min
ago
32 RASPBERRY PI HACKS
Process: 273 ExecStartPre=/usr/sbin/sshd-keygen (code=exited, sta
tus=0/SUCCESS)
Main PID: 280 (sshd)
CGroup: name=systemd:/system/sshd.service
└─280 /usr/sbin/sshd -D
If your output doesn’t look similar to that, it’s quick to install. Here’s the command on
Fedora:
$ su -c 'yum install openssh-server openssh-clients'
And here’s how to install it on Debian/Ubuntu:
$ su -c 'apt-get install ssh'
Once you’ve determined that it is installed, set it to start the daemon automatically
at each boot:
$ su -c 'chkconfig sshd on'
If you’re not going headless from square one with the Pi, you can connect it to a monitor
and run ifconfig. That’s the simple way, assuming you’ve got a monitor and keyboard
handy. Note that if you’re using a newer version of Fedora or Pidora, you’ll need to use
ip addr instead.
Or check your router’s default IP address, which is probably on a sticker somewhere
on it or on a website if you search for your router brand. (192.168.0.1 is a common
one.) You can also run route -n to find it. The numbers under Gateway on the line
flagged UG are the default IP. Go to that address in a web browser, and you’ll almost
certainly find some sort of router control panel where you can see connected devices,
including your Pi.
You could also use nmap, the network mapper tool. This is a fun way to learn a new tool
if you haven’t used it. That said, you should do your nmap learning only on your home
network and not at the office, in the coffee shop, or anywhere else you’re not in charge
of said network. When you run su -c nmap 192.168.1.1/24, replacing the IP address
with that of your network, you’ll see a list of everything connected to that network.
One of them will have a MAC address labeled Raspberry Pi Foundation, and it will list
your Pi’s IP address as well.
If you’re going to frequently connect via SSH, you’ll want to simplify things by giving
your Pi a static IP address (see Hack #13).
And now you’re ready to connect to your Pi by running ssh username@host, where
username is an account you’ve set up on the Raspberry Pi and host is the IP address
you found or configured. If you haven’t yet set up a user, you might need to refer to
33
CHAPTER 1: CONFIGURATION HACKS
the default login. On Pidora, it’s root/raspberrypi. On Raspbian-based systems, it’s
pi/raspberry.
The first time you connect to any machine, it will store a record of that machine in .ssh/
known_hosts. This list is checked on each connection. That means the first time you
connect, you’ll see a dialog that asks you:
The authenticity of host '192.168.1.174 (192.168.1.174)' can't be establish
ed.
RSA key fingerprint is 78:75:1d:1c:a1:79:11:18:15:e5:04:08:15:16:23:42.
Are you sure you want to continue connecting (yes/no)?
It sounds a little ominous, but “yes” is the right answer, despite the “warning” that
follows.
Now you’re ready to use the command line to transfer files to and from your Raspberry
Pi and to work on it almost as if you were working directly on it. If you’d like to be able
to launch GUI interfaces over SSH, use -X when you connect:
$ ssh -X ruth@192.168.1.118
Most (but not all) graphical applications will work with this method, known as “X for-
warding.
HACK 13 Give Your Pi a Static IP Address
If you always want to be able to connect to your Pi through the same IP
address without looking it up, you’ll need to assign it a static IP address
(as opposed to a dynamically assigned one).
Many ISPs use dynamic IP addressing, which means that you get a different IP address
each time you connect to the Internet. If you’re connecting to the Pi over SSH regularly
(see Hack #12), using VoIP (see Hack #32), or have other reasons to always have the
same IP address, you’ll want to set up static IP addressing.
In Pidora, you can either follow the instructions in Hack #11 if you’re running headless,
or if you’re not, edit the files in /etc/sysconfig/network-scripts.
If you’re usually a Debian user, these files are analgous to /etc/network/inter
faces.
You’ll see the available network interfaces configurations listed as ifcfg-<interface-
name>. Choose the one you’ll be using for the connection and edit it in your favorite
text editor, for example:
34 RASPBERRY PI HACKS
$ vi ifcfg-eth0
You’ll see something like this:
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
NM_CONTROLLED=yes
You need to change the BOOTPROTO line from dhcp to static. Also make sure ONBOOT is
set to yes. Then add IPADDR, NETMASK, BROADCAST, and NETWORK information like you would
have in the headless file. Remember not to choose an IP address already in use else-
where in your network. NETMASK is always 255.255.255.0. GATEWAY is your router’s IP
address:
IPADDR=192.168.1.123
NETMASK=255.255.255.0
BROADCAST=192.168.1.255
GATEWAY=192.168.1.1
Finally, restart the network service to apply your new settings:
$ systemctl restart network.service
If you’re using a Raspbian-based distro, you’ll follow similar steps, just in a different
place. Rather than looking for separate files, open /etc/network/interfaces (as root):
$ su -c 'vi /etc/network/interfaces'
Then look for the line:
iface eth0 inet dhcp
Change dhcp to static, and add your static IP address, gateway, broadcast, and net-
mask:
iface eth0 inet static
address 192.168.1.123
gateway 192.168.1.1
broadcast 192.168.1.1
netmask 255.255.255.0
network 192.168.1.0
If you need a little help gathering these, you can find the current IP address, netmask,
and broadcast by running ifconfig and noting the inet addr, mask, and bcast, respec-
tively, while route -n will give you the gateway and network, which it calls Destina
tion. (Again, on newer Fedora and Pidora versions, use ip addr instead of ifconfig.)
35
CHAPTER 1: CONFIGURATION HACKS
Choosing a Unique Static IP Address
You should be sure to pick an IP address that is not already in use by any other
devices on your network. Otherwise, your network connection will not work prop-
erly. When DHCP is in use, duplication is prevented, but it is possible to accidentally
do it when setting the IP statically.
Additionally, you will need to manually specify a DNS server when setting a static IP
address. DHCP configurations usually configure the DNS server for you, but there is
no way for a static IP configuration to know what the DNS server is. To set the DNS
server, edit /etc/resolv.conf (as root), and add the following line:
nameserver 11.23.58.13
Replace 11.23.58.13 with the IP address of your DNS server. If you have multiple DNS
servers, you can have multiple nameserver $IP lines in this file.
After saving your changes, restart networking for the new settings to take effect:
$ su -c '/etc/init.d/networking restart'
You now have a static IP address that won’t change each time you access the Internet.
HACK 14 Learn to Speak GPIO
GPIO stands for General-Purpose Input/Output, and its presence on your
Raspberry Pi makes many hacks in this book possible. This hack helps
dymystify it.
The Raspberry Pi contains standard connectors that you are probably familiar with
(Ethernet, HDMI, audio, and USB), but it also includes 26 pins (in two rows of 13) that
are intended to connect directly to lower level devices. These pins are called the GPIO
(general-purpose input/output) pins, because they are programmable input/output
pins intended for a wide range of purposes.
Practically, this means we can use the GPIO pins to connect almost anything to a
Raspberry Pi. The header of these pins is labeled on the Raspberry Pi as P1, as shown
in Figure 1-5.
36 RASPBERRY PI HACKS
Figure 1-5.
Raspberry Pi Model B with the GPIO header in the upper-left corner
Simple enough, right? Well, here’s where it gets a little more confusing. There are two
ways of numbering the GPIO pins on the Raspberry Pi.
Pin-Number Labeling
The first way to label the GPIO pins is to refer to the pin numbers on the P1 header on
the Raspberry Pi board. If you look at the pins in Figure 1-5, Pin 1 is the first pin to the
left in the bottom row, Pin 2 is the first pin to the left in the bottom row, and they
continue to alternate in values to the right. In table form, the board pin numbers look
like Table 1-5.
Table 1-5. Board pin numbers
2 4 6 8 10 12 14 16 18 20 22 24 26
1 3 5 7 9 11 13 15 17 19 21 23 25
This method of labeling the Raspberry Pi GPIO pins by their board numbers is simple
to understand by looking at the hardware. If you use this numbering scheme, you
should prefix the pin numbers with the board label, “P1-”.
37
CHAPTER 1: CONFIGURATION HACKS
BCM Labeling
But another labeling system for the Raspberry Pi GPIO pins uses the channel numbers
on the Broadcom SOC. This system is referred to as the BCM system. It is the most
common system in use, especially because the GPIO pins are not completely inter-
changeable and they are wired differently between the various models and revisions
of the Raspberry Pi.
Table 1-6 shows the mappings of the BCM pin labels to the pins as shown in Figure 1-5
(for the Raspberry Pi Model B Revision 2, the current revision as of this writing).
Table 1-6. BCM pin labels (Raspberry Pi Model B revision 2)
5 V 5 V GND 14 (TXD) 15 (RXD) 18 GND 23 24 GND 25 8 7
3.3 V 2 (SDA) 3 (SCL) 4 GND 17 27 22 3.3V 10 (MOSI) 9 (MISO) 11 (SCKL) GND
Let’s dig a little deeper. As you can see from the labeling, some of the pins are pre-
configured for special purposes. The pins marked as 3.3 V and 5 V are power pins,
with the voltage as labeled. The GND pins provide ground for wiring up circuits. BCM
Pins 2 (P1-03) and 3 (P1-05) are pre-setup to provide I2C bus 1. BCM Pins 14 (P1-08)
and 15 (P1-10) are configured to provide a serial console. BCM pin 18 (P1-12) supports
Pulse-Width Modulation (PWM).
For these reasons (and also because it is the most common Raspberry Pi GPIO la-
beling scheme used on the Internet), this book uses the BCM pin labels.
We realize this might be confusing when you are wiring up devices to your Pi, but see
the next section for a clever way to help you remember what is what.
Label Your Own GPIO Pins
GPIO should be simple, but the common labeling scheme (BCM) is so confusing and
easy to forget. Here’s a simple hack to make sure you always remember which pin
goes where.
Dr. Simon Monk had a problem: he wanted to wire all sorts of temporary connections
to his Raspberry Pi GPIO pins, but every time he wanted to do so, he had to go online
and look up the BCM pin labels. Then there was the task of counting down the pins to
find the right one, and while this sounds easy, trust us, you’ll likely get this wrong just
as he did.
38 RASPBERRY PI HACKS
To solve this problem, he created something called the Raspberry Leaf (shown in
Figure 1-6). The Raspberry Leaf is a perfectly sized and scaled diagram of the Rasp-
berry Pi GPIO pins, with the BCM labels next to them.
Figure 1-6.
Raspberry Leaf, created by Simon Monk
You can photocopy and use this image for reference, but it’s probably easier to down-
load from this book’s Git repository or the original PDF from Dr. Monk’s website.
HACK 15 Connect GPIO Pins to a Breadboard
A solderless breadboard is a helpful friend when building electronics
hacks, especially when you are prototyping or just testing out a device.
Let’s hack a simple connector to our Raspberry Pi.
While you can simply connect your Raspberry Pi GPIO pins to devices via common
jumper wires, or solder wires directly between your add-on device and the GPIO pins,
it is almost always helpful to have a little more space to work. Enter our old reliable
friend, the solderless breadboard, shown in Figure 1-7. Even if you’ve never done an
electronics project before, you may have seen this fellow with rows and columns of
little holes in a rectangle of white plastic.
39
CHAPTER 1: CONFIGURATION HACKS
Figure 1-7.
A breadboard
A breadboard works by providing horizontal rows of connector holes (often separated
by a gap) that are wired together. When you want to connect two wires together, you
can simply insert them into holes along the same horizontal row. Need more holes?
Just jump a wire from one row to another.
Additionally, most breadboards have vertical “rails” down each side, marked with red
and black. These rails are intended to be used for power and ground connections, to
simplify wiring circuits.
Our friends at Adafruit built a handy kit called the Pi Cobbler, which allows you to
connect a standard 26 pin ribbon cable (just like you’d use on a PC motherboard) to
a labeled printed circuit board (PCB) with a cable connector and individual pin break-
outs. That PCB breakout board has pins that allow it to push right into your bread-
40 RASPBERRY PI HACKS
board. Then, connect the cable to the Raspberry Pi GPIO pins and to the Cobbler PCB
breakout board, and you can start connecting devices directly through your bread-
board.
The instructions in this hack are also inspired by Limor “Ladyada” Fried’s excellent
assembly tutorial.
Adafruit sells the Pi Cobbler in a couple variants:
Compact version
Comes preassembled, so you can use it as soon as it arrives in the mail. (They
used to sell this as an unassembled kit, but it doesn’t look like they do anymore.)
T-Cobbler version
Slightly larger, but covers less of the pins on the breadboard due to its “T” layout.
At the time of this writing, the T-Cobbler is sold only as part of a kit (not preas-
sembled).
If you end up with an unassembled kit for either of these versions, do not fret. It is easy
to assemble it yourself. Here’s everything you need:
A soldering iron
Some solder
A breadboard
Your Pi Cobbler kit, containing a blue PCB, a 26-pin ribbon cable, a black con-
nector, and some male header pins (this might be in a single stick or in two smaller
sticks)
If your male header pins (these are the metal pins with black plastic header in the
middle, splitting the pins into one short and one long end) are in a single long stick,
gently break off two pieces of 13 pins each. You can do this with your fingers or pliers.
These correspond to the two pairs of 13 holes on the long edges of the Pi Cobbler PCB.
Also, go ahead and plug in your soldering iron and set it on a stand (see “Soldering
Reminders” on page 42 if you need some help or if it’s been a while). Give it 5–10 minutes
to come up to full temperature. If you have a fancy soldering iron with a temperature
setting, Adafruit recommends you set it to 700 degrees Fahrenheit.
Place the Pi Cobbler PCB in front of you so that the pin labels (e.g., GND) are legible
and oriented normally. On the T-Cobbler kit, the board is aligned like a T. On the original
kit, the board’s longer sides should be parallel to you.
The PCB is labeled with a box, indicating where the black header connector should be
placed. Gently press the header into the box, making sure to align the notch in the
41
CHAPTER 1: CONFIGURATION HACKS
header with the notch indicated in the box. On the original Cobbler PCB, the notch
must be right next to the “21/27” label; on the T-Cobbler PCB, the notch must be
between the two large round holes at the T junction point. You need to get this right,
because if you get the notch backward, this will cause the pins to be reversed when
the cable is connected between the Cobbler and the GPIO pins, and the labels on the
Cobbler will all be wrong.
Soldering Reminders
Soldering might seem scary at first, but it really isn’t very difficult if you’re
careful and respectful of the iron. Keep a few things in mind:
Solder, when heated, releases mildly toxic smoke. You should always
solder in a well-ventilated area.
The soldering iron gets hot. Very hot. (The actual temperature varies
on the type, quality, and condition of your soldering iron.) It will burn
you if you touch the tip of the iron, so always hold it by the handle, and
don’t lean in too close.
Always assume a plugged-in soldering iron is hot and treat it that way.
Heck, we usually assume unplugged soldering irons are hot, too.
Every soldering iron should come with a stand. Use it. This keeps you
from accidentally burning holes in your workstation, project, hand, leg…
Keep a small, moist sponge handy, and as needed, use it to wipe off
excess solder from the tip of the hot iron. If the tip of the iron becomes
coated in solder, it will no longer work effectively.
You don’t need to put a giant blob of solder down to make a good con-
nection. When heated, solder quickly becomes a liquid and will flow into
heated connections. Just a tiny bit will do. Practice will help you realize
how much to apply.
Flip over the PCB, with header connector still in place, so that it is now sitting on the
header. You should see little bits of the 26 connector pins poking out from 26 metal
rings on the PCB. Press the tip of your soldering iron simultaneously against a pair of
the rings and pins. Hold it there for a few seconds to heat up the metal, and then touch
some solder against the tip of the iron. The solder will melt instantly, liquify, and flow
between the pin and the ring, making a complete connection.
42 RASPBERRY PI HACKS
You want to use enough solder so that you cannot see air between the pin and the ring,
but not so much that you make a connection between neighboring pins. Really, it
doesn’t take much, just a tiny bit. This solder will be completing the electrical con-
nection, but it will also be providing a mechanical bond that holds the device together.
Repeat this process for all 26 pins, until the header connector is neatly soldered to
the PCB, and then put your soldering iron back on its stand (you’ll use it again in a
moment).
Get your breadboard and place it in front of you. Place the two sets of male header
pins into the breadboard, with the long ends into the breadboard, until the middle
header plastic on each pin is resting against the breadboard.
You want to do this so that they are in the same spacing and alignment as they appear
on the PCB Cobbler. For the original Cobbler, this is about five breadboard rows apart;
for the T-Cobbler, this is only three rows apart.
Flip the PCB back over and set it into the short ends of the male header pins. The
breadboard is acting as a stand for us now. Push the PCB gently down until all of the
pins are poking through the labeled rings, and the PCB is resting up against the plastic
header middles. Pick your soldering iron up again, and solder each of these 26 rings
and pins.
When you’re finished, clean off the tip of your soldering iron with a moist sponge and
unplug it. Put it back on the stand to cool off. You can now connect the ribbon cable
between the completed Pi Cobbler and the Raspberry Pi GPIO pins. You’ll notice that
the cable will only go into the Pi Cobbler one way, because of the notch on the con-
nector. However, be careful, because the Raspberry Pi GPIO pins do not have any
connector, and the cable can connect two possible ways. The ribbon cable included
in your kit will have two indicators to help you align it properly:
The ribbon cable has one wire of a different color. This uniquely colored wire
should be on the edge closest to the SD card slot on the Raspberry Pi.
Both ends of the ribbon cable have a notched connector. The notch on the con-
nector going to the Pi should be pointed toward the Raspberry Pi logo on the
board, as shown in Figure 1-8, never away from it.
The finished and connected Pi Cobbler will look something like Figure 1-9 (this is an
original Pi Cobbler).
43
CHAPTER 1: CONFIGURATION HACKS
Figure 1-8.
Close-up of a properly connected Cobbler ribbon cable
Figure 1-9.
Completed and connected Pi Cobbler
44 RASPBERRY PI HACKS
It might not seem like much, but trust us, when you are wiring up multiple devices to
the Raspberry Pi GPIO pins, being able to easily use a breadboard (and see the GPIO
labels at a glance) will make you happy that you completed this hack.
GPIO Quick Reference
If you turn your Pi so that the GPIO pins are in the upper right, the pins are numbered
from top to bottom, with odd numbers on the left and even on the right (thus, the first
row is 1 and 2, second row is 3 and 4, etc.). Note that these do not correspond to GPIO
numbers; for example, GPIO 22 is on pin 15. Table 1-7 explains the purposes of the pins
of a Version 2 board.
Table 1-7. GPIO pin purposes for Version 2 board
PIN NUMBER PURPOSE
1 3.3 V power
2 5 V power
3 GPIO 2 (SDA)
4 5 V power
5 GPIO 3 (SCL)
6 Ground
7 GPIO 4 (GPCLK0)
8 GPIO 14 (TXD)
9 Ground
10 GPIO 15 (RXD)
11 GPIO 17
12 GPIO 18 (PCM_CLK)
13 GPIO 27
14 Ground
15 GPIO 22
16 GPIO 23
17 3.3 V power
18 GPIO 24
19 GPIO 10 (MOSI)
20 Ground
21 GPIO 9 (MISO)
22 GPIO 25
45
CHAPTER 1: CONFIGURATION HACKS
PIN NUMBER PURPOSE
23 GPIO 11 (SCLK)
24 GPIO 8 (CE0)
25 Ground
26 GPIO 7 (CE1)
The pins are meant for input no higher than 3.3 V, and there is no overvoltage
protection.
Inter-Integrated Circuit (I2C)
The I2C interface (SDA and SCL), which you can access through pins 3 and 5, is a
connection for low-speed peripherals or sensors. You can have multiple devices con-
nected through the same pins.
Pulse-Width Modulation (PWM)
Pin 12 offers control for motors similar to analog control through pulse-width modu-
lation (labeled PCM_CLK). For some purposes, you can achieve the same effect
through software, which may be useful since the Pi has only one PWM pin.
Universal Asynchronous Receiver/Transmitter (UART)
The UART pins (14/TXD and 15/RXD) are used for serial console access. If you don’t
need that, you can switch them to GPIO for an extra two GPIO pins. This is also true
of the I2C and SPI pins, but you’re least likely to want to use the UART pins.
Serial Peripheral Interface Bus (SPI)
The SPI pins are the pins you’ll use for some types of sensors or attaching other de-
vices. SPI operates in master/slave fashion:
19 - Master Out, Slave In (MOSI)
21 - Master In, Slave Out (MISO)
23 - Serial Clock (SCLK)
24 - CE0 (chip select)
26 - CE1 (chip select)
46 RASPBERRY PI HACKS
The two chip select pins mean you can control two SPI devices.
For those who would like to better understand GPIO and to effectively use this feature
of the Raspberry Pi, we recommend looking through this page, which provides an
access library for the Pi’s GPIO. It will be particularly useful if you are already familiar
with Arduino wiring.
HACK 16 Add a USB Serial Console
Arguably the most common way to access embedded devices like the
Raspberry Pi is via the built-in serial device. This easy hack gives you a
USB serial console from your Raspberry Pi.
Almost all of the common embedded computers and microcontrollers available today
have built-in Universally Asynchrononous Receiver/Transmitters (UARTs). The UART
provides a mechanism for receiving and transmitting serial data, one bit at a time.
This method of serial communication is sometimes referred to as transistor-transistor
logic (TTL) serial. The data rate varies by device, but it is measured in bits per second.
The Raspberry Pi has a built-in UART connected to BCM Pins 14 (TXD) and 15 (RXD),
with a data rate of 115200bps (or baud).
Hey, That’s Not Really Baud!
OK, from a semantic point of view, yes, baud is the unit of symbol rate, which
is not always identical to gross bit rate (bps). Wikipedia says that baud is
“the number of distinct symbol changes (signaling events) made to the
transmission medium per second in a digitally modulated signal or a line
code.” Then it goes on for several more pages of mathematical distinction
about baud, which may be fascinating to you or may put you to sleep.
The key takeaway is this: the computer and electronics industry has been
widely misusing the term baud for about 40 years now. As a result, lots of
software and hardware uses bps and baud interchangeably. In the specific
case of the USB serial console on the Raspberry Pi, the data rate in bps and
the baud rate are the same. The units here don’t matter to us as much as
making sure you have a functional serial console, and for that, you need to
know that the data rate is 115200. Bits, baud, giant hamsters of doom, pick
your units as you will, but 115200 is the magic number for the Raspberry Pi
UART serial device.
47
CHAPTER 1: CONFIGURATION HACKS
If you’ve been using computers for a few years, you probably remember when almost
every computer came with an RS-232 serial port, but in the last few years, these ports
have been disappearing, and most laptops no longer include them (or they only have
them on the optional laptop dock). Believe it or not, for connecting to the Raspberry
Pi UART serial port, this is actually a good thing. The Broadcom chip that the Rasp-
berry Pi depends on uses 0 and 3.3 V logic levels, not the +/- 3 to 15 V range used by
PC RS-232 serial ports. This means even if you have one of those RS-232 serial ports
on your computer, you’d need a board or adapter to convert the signal levels before it
would work.
RS-232 or Bust!
Here’s a pretty good tutorial on how to build a 3.3 V to RS-232 level converter.
The good news is that there is a better way to connect the Raspberry Pi UART serial
port to your computer: USB! Adafruit sells a wonderful USB-to-TTL Serial Cable, which
connects directly to the GPIO pins on the Raspberry Pi and provides a USB serial
device on the other end. This cable has four female jumper connectors on one end
(the end that doesn’t have a USB connector). These jumpers have color-coded wires:
red for 5 V power, black for ground (GND), green for receiving data into the Raspberry
Pi (RXD), and white for transmitting data from the Raspberry Pi (TXD). You might also
notice that the USB connector end is larger than normal, because it also has a USB-
to-Serial conversion chip inside it.
To make the physical connection, you simply need to connect three of the female
jumper connectors directly to the appropriate pins on the Raspberry Pi GPIO. The
white transmitting wire goes into the TXD port (BCM Pin 14 (P1-08)), and the green
receiving wire goes into the RXD port (BCM Pin 15 (P1-10)). The black ground wire can
go into any of the GND pins, but for simplicity, we recommend you put it in the GND
pin immediately to the left of the TXD port (P1-06). You can confirm your wiring by
comparing it to Figure 1-10.
A Hack for the Red Wire
You may note that we did not ask you to connect the red power wire. This
is because the USB serial device will power itself with 5 V at 500 mA directly
from the USB port. You may also note that we said that the Raspberry Pi
UART uses 3.3 V logic levels, not 5 V, and this is true, but the receiving and
transmitting wires are already converted to 3.3 V. It all works fine, stop not-
ing and move on.
There is, however, a cool mini hack you can do with that red power wire.
Because 5 V is going across that red wire, you can use it to power the Rasp-
berry Pi, instead of doing so via the normal mini-B USB connector. Just
48 RASPBERRY PI HACKS
connect the red wire to the 5 V pin (P1-04), then without any other power
source connected, plug the USB-to-TTL Serial cable into your laptop. The
Raspberry Pi will boot up!
This is really just a parlor trick, because the power coming off that red wire
is not the ideal way to power the Raspberry Pi for a number of reasons, as
discussed in “Think Twice Before Using the GPIO to Power the Pi” on page
25.
Figure 1-10.
A properly wired USB to TTL serial cable
Now, go ahead and connect the USB connector to your computer.
To connect to the UART serial device, you first need to know its device name. The
kernel assigns it a device name when the USB serial driver successfully loads (which
it should have already done when you inserted the USB end of the cable), so you just
need to look through the output from dmesg.
Specifically, we know that the device name will be ttyUSB#, where # is a number. It’s
probably ttyUSB0, but let’s look to be sure. If you have multiple USB serial devices
present on your system (you naughty super hacker, you), you’re looking for the one
with the pl2303 converter type. If you have more than one pl2303 converter type USB
serial device present, pick one at a time and try until you find the right one. Anyway,
here’s how you can check:
$ dmesg | grep -B2 ttyUSB
[23882.896558] usbserial: USB Serial support registered for pl2303
[23882.896578] pl2303 1-1.5.1:1.0: pl2303 converter detected
[23882.898285] usb 1-1.5.1: pl2303 converter now attached to ttyUSB0
Sure enough, our device is ttyUSB0. This means that the full device node name is /dev/
ttyUSB0. Unprivileged users do not normally have access to /dev/ttyUSB# devices; you
need to be in a special group. If you look at the file permissions on the device node
49
CHAPTER 1: CONFIGURATION HACKS
name, you will see that it is owned by root and access is granted to users in the dialout
group:
$ ls -l /dev/ttyUSB0
crw-rw----T 1 root dialout 188, 0 Aug 22 19:11 /dev/ttyUSB0
You can either connect to the /dev/ttyUSB0 device using the root account (via su or
sudo), or you can add your normal user to the dialout group. To add your user to the
dialout group, run:
$ su -c 'usermod -a -G dialout $USER'
This will not take effect in your terminal sessions until they are restarted. Either log
out and log in again, or reboot your Linux system.
Not Using Linux to Connect to the Serial Port?
You can imagine the face the authors are making right now. It is a disap-
proving face. _ However, we can give you a few tips anyway.
Windows and Mac OS X systems will need to install PL2303HXA drivers,
which you can download for Windows XP/Vista/7 and Mac OS X.
According to the vendor, Windows 8 is not supported for this device. Maybe
if you’re a Windows 8 user, this is a good time to consider dual booting to
Linux?
As far as terminal software goes, if you are using Windows XP or older, it
comes with a program called Hyperterminal that can connect to a serial
console. If you are using a newer version of Windows, you’ll need to down-
load a third-party terminal program. We recommend PuTTY. For Mac OS X,
you can either use screen in the same way that we’ve described for Linux,
or you can try ZOC.
Now it’s time to connect to the Raspberry Pi UART serial device. You’ll need to use a
client that supports a serial connection; there are lots and lots out there, but the two
common ones are minicom and screen.
Minicom
Minicom was written to look like Telix, a popular MS-DOS terminal program that was
probably written before you were born. We now feel old(er). It has that MS-DOS look
and feel to it—namely, it is old, crufty, and confusing—but it does work. To install it on
Fedora:
$ su -c 'yum install minicom -y'
50 RASPBERRY PI HACKS
or on Debian/Ubuntu:
$ su -c 'apt-get install minicom'
Once installed, to use minicom to connect to the Raspberry Pi UART serial device, run:
$ minicom -b 115200 -o -D /dev/ttyUSB0
To test it, reboot the Raspberry Pi while it is connected; you should see Linux kernel
messages scroll down the screen, and it will look similar to Figure 1-11.
Figure 1-11.
minicom interfacing with the Raspberry Pi UART serial device
You can exit minicom with Control-A X, or get into its somewhat helpful help menu
with Control-A Z. If you end up manually configuring minicom, just leave the Parity/
Bits at 8N1, and disable the Software Flow Control. You don’t need to go in there
though. There are bats in there.
Screen
Screen is a powerful utility, normally used to multiplex multiple virtual consoles. If this
were Linux in a Nutshell, we’d have a whole chapter about using screen. Since this is
a different book, we’ll just focus on using it as a serial terminal client.
To install it on Fedora, run:
$ su -c 'yum install screen -y'
51
CHAPTER 1: CONFIGURATION HACKS
or on Debian/Ubuntu:
$ su -c 'apt-get install screen'
Once installed, to use screen to connect to the Raspberry Pi UART serial device, run:
$ screen /dev/ttyUSB0 115200
To exit the screen session, type Control-A K.
Using the Serial Device as a Login Console
Raspbian preconfigures the UART serial device as a login-capable console, but Pidora
does not. To enable the UART serial device as a login console session, run:
$ su -c 'systemctl start serial-getty@ttyAMA0.service'
This will turn it on immediately. If you have a serial cable connected, you should see
a login prompt appear. To make this login session permanent (and automatically
loaded on boot), simply run:
$ su -c 'ln -snf /usr/lib/systemd/system/serial-getty@.service \
/etc/systemd/system/getty.target.wants/serial-getty@ttyAMA0.service'
By making that symbolic link in the systemd directory tree, you are telling systemd to
start the ttyAMA0 device as a “getty” or login console.
Fun Serial Console Trivia
The name “getty” comes from the term “get teletype.” A teletype was originally a
device with a typewriter for input and a printer for output for use as telegraph
machines, but as computers evolved, these devices found a use as a method of
inputting data to a computer. The teletype was also widely used in a “receive only”
format in newsrooms in the 1940s and 1950s. The “clickety clack” sound effect of
news coming in “over the wire” is that of a teletype. Eventually, these devices be-
came proper serial consoles, and they are the reason why we call console devices
in Linux “TTYs”.
Both Pidora and Raspbian come with the UART serial device preconfigured as a con-
sole for kernel messages. You can see this in the /boot/cmdline.txt file:
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 con
sole=tty1 root=/dev/mmcblk0p2 ro rootfstype=ext4 rootwait quiet
The console value tells the Linux kernel where to output messages at boot time, and
the kgdboc value enables kernel debugging over that console.
52 RASPBERRY PI HACKS
If you are working on a project that wants dedicated access to the UART serial device,
you will probably want to remove the console=ttyAMA0,115200 and kgdboc=ttyA
MA0,115200 entries from /boot/cmdline.txt and reboot your Raspberry Pi. If you do
not, you will get unexpected line noise across the serial line from the Linux kernel that
your program/project is probably not ready to deal with.
If you have enabled the serial devices as a login console, you will also want to disable
that. To disable it on Raspbian, comment out the following lines in /etc/inittab (by
changing the line to start with a #):
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
On Pidora, you simply need to remove the systemd getty service symlink for the
ttyAMA0 device, by running:
$ su -c 'rm -f /etc/systemd/system/getty.target.wants/serial-
getty@ttyAMA0.service'
On either Linux distribution, after making these changes, reboot for them to take ef-
fect.
Weird Noise (or Missing Signal) on the Serial Connection?
Both Ubuntu and Fedora include a piece of software called ModemManager, which han-
dles setting up all sorts of modem devices, from old dial-up modems to more modern
3G/4G devices. Unfortunately, quite a few current modems just have the same generic
converter chip that our USB serial connector cable uses (the pl2303) stuck in front
of the modem.
As a result, ModemManager will try to access it (and keep trying, and keep trying …),
because it has no way of knowing that the device behind /dev/ttyUSB0 is a modem, or
a Braille terminal, or in our case, a Raspberry Pi. This might prevent you from being
able to open /dev/ttyUSB0, or it might simply cause noise to appear across the console.
Since we know what that USB device is connecting to, we can tell ModemManager to leave
it alone and explicitly blacklist our connector device with udev rules.
53
CHAPTER 1: CONFIGURATION HACKS
As root, edit the /lib/udev/rules.d/77-mm-usb-device-blacklist.rules file, and add
these lines before the LABEL="mm_usb_device_blacklist_end" line at the bottom:
# Adafruit USB to TTL Serial Cable (PL2303HXA)
ATTRS{idVendor}=="067b", ATTRS{idProduct}=="2303", ENV{ID_MM_DEVICE_IG
NORE}="1"
If you use a different USB serial cable from the Adafruit cable, and you’re trying to fix
this problem, you should be able to run the lsusb application (from the usbutils pack-
age) to determine the idVendor and idProduct string (they will show up in the output
in the syntax XXXX:YYYY where XXXX is the idVendor and YYYY is the idProduct).
For example, the lsusb value for the Adafruit USB serial cable looks like this:
Bus 003 Device 002: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial
Port
Udev automatically detects changes to rules files, so changes take effect immediately
without requiring udev to be restarted. That said, sometimes you need to reboot the
Linux system for udev to reread its rules. Either way, whenever udev reads in its new
rules, the USB serial converter device should now be blacklisted, and ModemManager
should ignore it from then on out.
HACK 17 Add a Reset Button
Perhaps you’ve noticed your Pi lacks something pretty common among
electronics: a power switch. The Model B revision 2 boards come with a
small fix.
It’s somewhere between vaguely uncomfortable and outright inconvenient to remove
the power supply from your computer as an on/off switch, but that’s what you do on
the Raspberry Pi. One easy fix, regardless of what board you have, is to plug it into a
power strip with an on/off switch and use that. But with the Model B revision 2 boards,
you have another option.
54 RASPBERRY PI HACKS
One of the added features on these boards is labeled P6. It’s easy to miss. P6 is just
two small holes on the opposite side of the board from the GPIO, near the HDMI port
(see Figure 1-12).
Figure 1-12.
P6 holes
If you solder a pair of header pins into these two holes (see “Soldering Reminders” on
page 42 if you’re new to soldering), you have a reset switch, as shown in Figure 1-13.
Just use a metal object to connect the two pins and short them.
55
CHAPTER 1: CONFIGURATION HACKS
Figure 1-13.
Reset pins in place
This short will also reset the CPU from shutdown, causing the Pi to start.
HACK 18 Get Power to the Pi on the Move
Power doesn’t have to mean a plug in the wall. You have a few more op-
tions to increase portability.
To get power to your Pi, you need five stable volts at 700 mA through a Type B Micro
USB plug. As mentioned elsewhere, it’s not a bad idea to get a power adapter specif-
ically intended for the Raspberry Pi, though your phone charger or other similar
adapter will likely work.
Less-than-Recommended Power Options
Much like trying to substitute anything for eggs in a recipe, there are options
that aren’t particularly recommended but work out for some people. For
example, powering your Pi through your laptop’s USB port. It doesn’t offi-
cially work and isn’t recommended, but we’ve seen it work. Trying to push
power through the GPIO isn’t a great idea either. See Get Power Through
GPIO Safely” on page 26 for more on power and the GPIO pins.
We’ve also heard of success with power over Ethernet and even intentionally
backpowering through USB to power the Pi. Again, not the recommended
56 RASPBERRY PI HACKS
method, but hacks are about trying something new. As long as you conduct
your electrical experimentation safely, the worst you’ll end up with is the
loss of a $35 board but the gain of a good story, possibly featuring smoke,
which enhances any story.
But if you want portability, what you need is a battery pack. You might think of these
devices as emergency power for your cell phone. They come in assorted strengths,
shapes, sizes, and colors, but in the end, they’re two things: power and a USB port,
which are the two things that you need to power the Pi.
Look for one that has 5V regulated output. We use the New Trent iCarrier (IMP120D),
a 12,000 mAh pattery pack with two USB ports and an on/off button. Depending on
activity on the Pi, that’s enough power to last 14– 16 hours or more.
This portable power is critical to some of the hacks in this book, most notably Hack
#44. It’s an enhancement for others. And worst case, it’s spare juice for your phone.
HACK 19 Test Your Might (in Volts)
If you aren’t already friends with a multimeter, you will be soon. Pi
projects all need power, and the Pi provides a way for you to check the
voltage of the board on the board.
Assuming you don’t have a few power supplies around to swap out, or if you’re deter-
mined to get a particular and unusual power source working, you’re going to want to
check the voltage on the Raspberry Pi.
There are two test points on your Raspberry Pi for just such a need, as shown in
Figure 1-14. TP1 is the 5 V point and TP2 is ground.
They’re in slightly different but nearby places on the Model A board, but they’re
still labeled TP1 and TP2 in that tiny white PCB label text.
57
CHAPTER 1: CONFIGURATION HACKS
Figure 1-14.
Test point locations (a.k.a. “electronics vision test”)
58 RASPBERRY PI HACKS
To test the voltage:
1. Plug in all the peripherals you expect to use, and power on the Pi (and the pe-
ripherals).
2. Set your multimeter range to 20 V.
3. Touch the red lead of your multimeter to TP1 and the black lead to TP2 (as shown
in Figure 1-15).
Figure 1-15.
Testing the voltage
The Pi needs a good 5 V supply but has a tolerance of +/-0.25 V or so. That means
that, at a minimum, you should be seeing 4.75 V, preferably more like 4.8 V or more.
Below that, and either your peripherals will start acting up or the Pi might not even
boot at all. It might also reboot spontaneously.
You can also try unplugging various peripherals, using different monitors, removing
Ethernet, etc. Test again to see how the result changes.
It’s Electric!
It’s entirely possible that the Raspberry Pi is the first place you’ve gotten
this close to the electricity part of your electronics. If that’s the case, it’s
worth some light reading about how all this power stuff works. But at the
most basic level, you’ll want to understand these three terms and the rela-
tionship among them:
59
CHAPTER 1: CONFIGURATION HACKS
Voltage
The difference in charge between two points
Current
The rate at which charge is flowing
Resistance
A material’s tendency to resist the flow of charge (current)
If you know two of them, you can figure out the third, thanks to Ohm’s law,
which says that V=I*R, or the voltage (volts) is equal to the current (amps)
times the resistance (ohms). Those who are mathematically disinclined can
get an assist from the handy tool at the online Ohm’s Law Calculator.
Keep this in mind when things act funny and you’re not sure why: it might be worth a
quick power check.
You can also use the Pi’s test points to test its polyfuse. A polyfuse is a type of fuse
that can repair itself after it has been blown. The Raspberry Pi has at least one of these,
labeled F3 on the bottom of the board, as shown in Figure 1-16.
Figure 1-16.
F3 polyfuse beneath SD card slot
Earlier Pis also had two on the USB ports, which have since been replaced by 0
Ohm resistors. They were known as F1 and F2.
You’ll find F3 to the left of the SD card slot if you turn the Pi over and hold the SD slot
toward you.
60 RASPBERRY PI HACKS
How long it takes for it to “heal” is variable, as much as a few days, and they can be
permently damaged. They are replaceable, though. To test whether you’re having a
problem with the F3 polyfuse:
1. Remove the SD card and all of the peripherals, unlike testing the voltage, but leave
it plugged in.
2. Turn the board upside down.
3. With the same settings (range 20 V), touch one lead to the back side of TP2 (since
the board is upside down) and the other to the metallic part of F3 facing the SD
card slot. This will tell you the voltage coming from the fuse.
4. Next, touch one lead to the back side of TP2 and the other to the metallic part of
F3 facing the outside of the board. Check the voltage. This will tell you the voltage
coming in.
It’s normal for the reading on F3 to be 0.2 V lower than the power coming in, but any
more than that indicates a problem with the polyfuse.
HACK 20 Add Additional Memory with Swap
Need a little more memory on your Raspberry Pi? Swap will let you trade
disk space for memory.
Linux has long inclued the concept of swap, where the kernel is capable of moving
memory pages between RAM and disk. In practical application, this provides more
usable memory to the OS (at the cost of disk space). Because the Raspberry Pi Model
B only has 512 MB of memory, the idea of adding swap files (or partitions) to increase
the usable memory is compelling.
Swap Hazards
Before we begin, you should be aware of a downside to this approach. Swap
is only as fast as the speed of the storage device that it is written to. It also
is a highly write-intensive operation. From a practical perspective, this
means that if you add swap to your SD card in your Raspberry Pi, it will cause
the overall disk performance to drop significantly and notably shorten the
life of the SD card.
Because the entire OS on the Raspberry Pi runs off the SD card, we strongly
recommend that you not place swap files or partitions on the SD card. These
downsides also apply to a USB flash drive connected to the Raspberry Pi.
Because they are also flash-based storage devices, adding swap files from
USB flash drives will cause the same overall performance slowdowns and
61
CHAPTER 1: CONFIGURATION HACKS
shortening of life span. If you really want to add swap, the best possible case
is over an actual external hard drive connected via a SATA-to-USB converter.
Raspbian comes preconfigured with a 100 MB swap file enabled, via dphys-swapfile.
You can change the settings of this swapfile by editing /etc/dphys-swapfile. It has only
one option: CONF_SWAPSIZE. If you want to increase the size of the swapfile, change the
value from 100 to a larger value (depending on the free space on your SD card). Alter-
natively, you can disable this option by changingthe value to ++0.
Any changes to this value will not take effect until you run the following commands:
$ /etc/init.d/dphys-swapfile stop
$ /etc/init.d/dphys-swapfile start
Pidora configures 512 MB of swap by default at firstboot (unless the user specifies
otherwise). This is placed in the file /swap0 and configured in /etc/fstab by the rootfs-
resize service.
For other Linux distributions (or to place a swapfile on a different location), you will
need to manually create the swapfile:
$ sudo dd if=/dev/zero of=/path/to/swapfile bs=1M count=1024
$ sudo mkswap /path/to/swapfile
$ sudo swapon /path/to/swapfile
These commands will generate a 1 GB swap file (1024 x 1 M = 1 GB) at /path/to/
swapfile, which you should change to the location of your swapfile. To make the swap
file automatically enabled on boot, add a new line to your /etc/fstab file:
/path/to/swapfile none swap defaults 0 0
You will see the additional memory (as swap) in the output of the free command:
$ free
total used free shared buffers cached
Mem: 448688 436960 11728 0 6776 395392
-/+ buffers/cache: 34792 413896
Swap: 1048572 0 1048572
62 RASPBERRY PI HACKS
2
Hacking Linux for the
Raspberry Pi
While there are many available operating systems for the Raspberry Pi, the most sup-
ported one is Linux. The Raspberry Pi Foundation maintains a Linux kernel source tree
with support for the Raspberry Pi hardware.
Linux is famous for its flexibility and support for a large number of devices. Whether
you are just interested in learning Linux, or if you need to make some modifications
in order to enable an awesome hack, this chapter will help you through the process.
HACK 21 Build a Cross-Compiler Toolchain
The Raspberry Pi is well-suited for many things, but compile speed is not
one of them. To build anything of consequence from source in a reason-
able amount of time, you’ll need to to use a cross-compiler running on a
faster computer.
A cross-compiler is a compiler (and dependent libraries) built to run on one architec-
ture but that generates binaries for a different architecture, usually an incompatible
one. In this case, you need a cross-compiler that will allow you to build binaries opti-
mized for the Raspberry Pi Linux environment.
Like most tasks in Linux, you can generate a cross-compiler in a few ways, but to
ensure that you end up with a toolchain optimized for the best performance on the
Raspberry Pi, we suggest not installing prepackaged cross-compilers that come with
your Linux distribution. Instead, the following sections will walk you through the pro-
cess of using crosstool-ng to build it from scratch.
Install crosstool-ng
crosstool-ng is designed to assist you in the complicated task of generating a compiler
toolchain. It provides a powerful frontend and build scripts that let you choose what
you need your toolchain to do, then automate the build, while keeping you from need-
63
ing to understand exactly how the numerous pieces of the toolchain hook together.
Compared to building cross-compilers manually, this is a lifesaver.
crosstool-ng is built using the same configuration frontend technology as the
Linux kernel source, so the menu structure that it uses will likely be familiar to you.
Just like the Linux kernel, many options might not make sense to you or might
seem confusingly similar. Never fear, brave hackers! You’ll need to change only a
few of these options from their defaults.
You can put your Raspberry Pi aside; you won’t need it. Instead, start with an x86-
based system running your preferred Linux distribution. Any distribution you are
comfortable working with that includes a working compiler will be fine. As far as the
system goes, the bigger, the better. More CPU cores and more memory will result in
faster builds, and x86_64 is always preferred. Also, you’ll want to have a healthy
amount of available disk space (10 GB should be more than sufficient).
To build the cross-compiler toolchain, you first need to make sure you have some
development components. Specifically, you’ll need a native compiler (in this
case,GCC with support for C & C), libstdc (standard C++ libraries, both shared and
static), libtool and make (for the build infrastructure), GNU MP (for fast precision
mathematics), gperf (a perfect hash function generator), bison (a C grammar parser),
flex (a lexical pattern recognition engine), ncurses (a terminal graphics library), sed
(a stream editor), subversion (client tooling for accessing SVN code repositories),
and texinfo (a documentation generation and parsing tool).
Don’t worry too much about these pieces: you do not need to know how they work (or
even why you need them), just know that you do. Really, all you need to do is install
them, and you accomplish that by running the following commands.
On Fedora, enter:
$ su -c 'yum install gcc gcc-c++ bison make ncurses-devel texinfo flex
gperf \
libtool sed subversion gmp-devel libstdc++-devel libstdc++-static'
For Ubuntu, enter:
$ su -c 'apt-get install gcc g++ bison make ncurses-dev texinfo flex
gperf \
libtool sed subversion libgmp-dev libstdc++-dev'
Next, download a copy of the crosstool-ng source code. At the time of this writing, the
latest version is 1.18.0.
64 RASPBERRY PI HACKS
Unpack the crosstool-ng source tarball into your home directory:
$ tar xvfj crosstool-ng-1.18.0.tar.bz2
Fix for PPL Bug
The version of the Parma Polyhedra Library (PPL) that crosstool-ng uses
(0.11.2) has a bug in it. Specifically, it is not compatible with newer versions
of the GNU Multiple Precision Arithmetic Library (GMP). We have provided
a fix for this, to allow PPL to compile properly against more recent versions
of GMP. There is a patch file named 101-gmp-build-fix.patch in our GitHub
repository. First, clone a local copy of our GitHub tree into your home di-
rectory, then copy the patch file into the crosstool-ng source directory:
$ cd ~
$ git clone https://github.com/spotrh/rpihacks
Cloning into 'rpihacks'...
remote: Counting objects: 247, done.
remote: Compressing objects: 100% (190/190), done.
remote: Total 247 (delta 75), reused 206 (delta 37)
Receiving objects: 100% (247/247), 251.84 KiB | 0 bytes/s, done.
Resolving deltas: 100% (75/75), done.
$ cp -a rpihacks/101-gmp-build-fix.patch ~/crosstool-ng-1.18.0/patch
es/ppl/0.11.2/
By placing this patch file in the crosstool-ng-1.18.0/patches/ppl/
0.11.2/ directory, it allows crosstool-ng to apply this fix to PPL 0.11.2 before
it builds it.
On systems with older GMP versions, this patch may not be necessary, but
applying it will not cause any problems. We strongly recommend that you
copy this patch into the crosstool-ng patches tree before proceeding.
Configure crosstool-ng
Go into the crosstool-ng-1.18.0 source directory and run configure. The only option
you will need to pass to it is a prefix value for where you want to install crosstool-ng.
We strongly recommend that you use /opt/crosstool-ng-1.18.0, just to give it a space
that is guaranteed to be far, far away from the rest of your Linux system:
$ ./configure --prefix=/opt/crosstool-ng-1.18.0
65
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
This configure script, like virtually every configure script ever created, will check your
Linux system to ensure that all of crosstool-ngs dependencies are present and ac-
counted for. If it fails, simply use your Linux distribution tools (yum or apt-get, as ap-
propriate) to install the missing packages. Once this completes successfully, it will
create a Makefile. To build the crosstool-ng code, run:
$ make
This should result in success, because crosstool-ng isn’t difficult to build. Once it
finishes, you just need to make install it into its new home (/opt/crosstool-
ng-1.18.0). Don’t forget to run this as root:
$ su -c 'make install'
Add crosstool-ng to Your PATH
Now that you have the crosstool-ng software installed and configured, add it to your
PATH. This will allow you to run commands specifically for crosstool-ng without need-
ing to type a long command string.
The easiest way to accomplish this varies by Linux distribution and shell choice. On
Fedora, using the default bash shell, you need to make a change to the ~/.bash_pro
file. On Ubuntu, edit ~/.profile. What you’re looking for is a configuration (or dot)
file that lives in your home directory and sets the PATH. Usually, this file will contain a
line that explicitly exports the PATH variable, like this:
export PATH
Just above that line, add this line:
PATH=$PATH:/opt/crosstool-ng-1.18.0/bin
This will append /opt/crosstool-ng-1.18.0/bin to the end of the existing value of PATH
($PATH). Save the file, and then you can either open a new shell instance or source the
modified file. Since we’re brave hackers, we’ll just source the new file like this:
$ source ~/.bash_profile
These directions will vary if you’re using a shell other than bash, but if you have made
that choice, most of the previous section is common sense to you, and you should be
able to add a directory to your PATH in the shell of your choice.
66 RASPBERRY PI HACKS
Configure the Cross-Compiler
Now it is time to actually build the Raspberry Pi cross-compiler. In the process of doing
so, crosstool-ng will download quite a lot of source files from the Internet. To keep
things clean, you should make a temporary home (a sandbox) and work in that direc-
tory:
$ mkdir ~/cross-sandbox
$ cd ~/cross-sandbox
Now you can safely launch the crosstool-ng configuration utility by running:
$ ct-ng menuconfig
crosstool-ng supports a wide variety of different toolchains and subvariants of tool-
chains. For the best optimization, we recommend using the Linaro variant of the GCC
compiler. Linaro is a nonprofit organization that specializes in optimizing and improv-
ing open source technologies for the ARM platform, and they tend to make the nicest
ARM Linux compilers.
On that recommendation, next you’re going to build a Linaro GCC cross-compiler
specifically optimized for the hardware inside the Raspberry Pi.
In GCC language, this is an arm-bcm2708hardfp-linux-gnueabi toolchain. The
bcm2708 describes the specific CPU type (Broadcom 2708), hardfp means that it
is using a hardware floating point unit (specifically, it means that values are being
passed to functions in the floating-point registers), linux is the OS, and gnueabi
means that it supports the GNU Embedded Application Binary Interface (EABI).
The EABI allows for different compilers to generate compatible code.
While most of the crosstool-ng settings are fine at their default values, you will need
to double-check some of them. When you launch ct-ng menuconfig, it will open a Text
User Interface (or TUI for short) in your terminal window. It will present you with a
series of menus that you can navigate using the arrow keys, the Enter key (to select
an item or menu), and the spacebar (to enable or disable specific items). Items which
are enabled have either an asterisk or a set value next to them.
The top menu looks like Figure 2-1.
67
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Figure 2-1.
Main configuration menu
The following sections describe the changes you’ll need to make, grouped by menu
sections from the top down.
Paths and Misc Options
In this section of the crosstool-ng menu (shown in Figure 2-2), make the following
changes:
Enable “Try features marked as EXPERIMENTAL.
Set “Prefix directory” to the location where you want your cross-compiler tool-
chain to be installed. We suggest putting this either in its own subdirectory
in /opt or your home directory to ensure you don’t get your cross-compiler tool-
chain confused with your system native toolchain. We leave this at the default
value of ${HOME}/x-tools/${CT_TARGET}, which evaluates to ~/x-tools/arm-rpi-
linux-gnueabi/.
68 RASPBERRY PI HACKS
Set “Number of parallel jobs”. This value will be passed to make to accelerate the
build time for the cross-compiler toolchain. Setting this value too low will make
the build take longer than it needs to, but setting it too high will result in the CPU
resources being spread too thin (and will also make the build take longer than it
needs to). The magic value seems to be the number of CPU cores in your system
multiplied by 1.5. On our 8 core laptop, this is 12. If you’re not sure how many CPU
cores your system has, run:
$ cat /proc/cpuinfo |grep processor
Count the number of lines, as each CPU core will appear to Linux as a unique pro-
cessor.
Figure 2-2.
Paths and misc options configuration submenu
Target Options
In this menu (shown in Figure 2-3), make sure the following settings are set:
69
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Set “Target architecture” to arm.
Set “Endianness” to Little endian.
Set “Bitness” to 32-bit.
Figure 2-3.
Target options configuration submenu
All of these should be the defaults, but the settings that follow are probably not. Making
the following changes will tune the cross-compiler toolchain to generate the best
possible binaries for the Raspberry Pi:
Set “Architecture level” to armv6zk. This is the specific ARM architecture revision
of the Raspberry Pi ARM CPU.
Set “Emit assembly for CPU” to arm1176jzf-s.
Set “Tune for CPU” to arm1176jzf-s.
Set “Use specific FPU” to vfp.
Set “Floating point” to hardware (FPU).
70 RASPBERRY PI HACKS
Set “Default instruction set mode” to arm.
Enable “Use EABI”.
Toolchain Options
Make the following change to the Toolchain options (shown in Figure 2-4):
Set “Tuple’s vendor string” to rpi. Really, we could put anything we wanted in
here. We strongly recommend doing this to ensure that you know you’re using
the Raspberry Pi cross-compiler toolchain.
Figure 2-4.
Toolchain options configuration submenu
Operating System Options
Make the following changes to the Operating Systems Options (shown in Figure 2-5):
71
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Set “Target OS” to linux.
Set “Linux kernel version” to 3.6.11. (Your Raspberry Pi might not be running the
3.6.11 kernel yet, but this is a safe value.)
Figure 2-5.
Operating system configuration submenu
Binary Utilities Options
Make the following changes to the Binary Utilities (shown in Figure 2-6):
Set “Binary format” to ELF.
Set “binutils version” to 2.22
72 RASPBERRY PI HACKS
Figure 2-6.
Binary utilities configuration submenu
C Compiler Options
Make the following changes to the C Compiler options (shown in Figure 2-7):
Enable “Show linaro versions”.
Set “gcc version” to linaro-4.7-2013.01. (Feel free to try newer ones if they are
available when you are reading this.)
Enable “C++”.
Set “gcc extra config” to --with-float=hard.
Enable “Link libstdc++ statically into gcc binary”.
73
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Figure 2-7.
C compiler configuration submenu
C-library Options
Make the following changes to the C-library options (shown in Figure 2-8):
Set “C library” to “eglibc”.
Set “eglibc version” to “2_13”.
74 RASPBERRY PI HACKS
Figure 2-8.
C-library configuration submenu
That completes the configuration portion. Go to the main screen, exit, and save the
configuration file when prompted.
Disable CT_WANTS_STATIC_LINK
On some systems, crosstool-ng sets the CT_WANTS_STATIC_LINK value to Y,
even though you didn’t select that. This will cause it to fail early in the build
process, but you can use sed to ensure it is disabled. Run this command:
$ sed -i 's|CT_WANTS_STATIC_LINK=y|# CT_WANTS_STATIC_LINK is not set|
g' .config
This command might look complicated, but all it is doing is disabling the
CT_WANTS_STATIC_LINK feature in the crosstool-ng configuration file by
searching for the string that exactly matches the CT_WANTS_STATIC_LINK
75
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
option when it is enabled and, if found, replacing it with the string that dis-
ables it.
Begin the Build
Now you just need to kickoff the build process:
$ ct-ng build
It will then download everything it needs and build your Raspberry-Pi-optimized cross-
compiler toolchain. This is the longest part. The time will vary depending on your
system specifications and Internet speeds, but 45 minutes to an hour or more on a
powerful laptop is not unreasonable.
When this completes successfully, you will now have a cross-compiler toolchain in the
~/x-tools/arm-rpi-linux-gnueabi/bin directory. You will want to add this directory to
your PATH, in the same manner that you added the crosstool-ng directory previously.
Change the line you added from:
PATH=$PATH:/opt/crosstool-ng-1.18.0/bin
to:
PATH=$PATH:$HOME/x-tools/arm-rpi-linux-gnueabi/bin:/opt/crosstool-
ng-1.18.0/bin
Save the file, and then source it again to update the PATH value. Now you can test your
toolchain by running:
$ arm-rpi-linux-gnueabi-gcc -v
It will return a lot of information on how gcc is configured and optimized, along with
printing the compiler version. If you see that, your Raspberry Pi cross-compiler tool-
chain is ready to go.
HACK 22 Build a Custom Kernel
For many hacks, the standard prebuilt Linux kernel images are sufficient,
but some require options or drivers that are not enabled. This hack turns
on some additional options that will be useful for other hacks in this book.
The Linux kernel is a fantastic operating system core for a number of reasons, starting
with its versatility, its native support for a large number of architectures and devices,
and its open source code base. The Raspberry Pi Foundation provides prebuilt Linux
kernel images customized to support the Raspberry Pi hardware, as well as the cor-
responding source code tree, so that you can build a custom kernel image of your own
that will work on the Raspberry Pi. This is necessary, because not all of the code
76 RASPBERRY PI HACKS
needed for the Linux kernel to work on the Raspberry Pi is yet merged into the official
Linux kernel source tree.
The first step to building your own kernel is to decide whether you want to do so
natively from within the Linux instance running on the Raspberry Pi or to build it on
an x86 Linux system with a properly configured cross-compiler toolchain. We strongly
recommend the latter approach, because it will go much much faster (several hours
faster) and it is not that much more complicated.
We’ll assume that you’re building your new kernel with a cross-compiler toolchain—
specifically, the one described in Hack #21. You will also need to have the make and
ncurses-dev (or ncurses-devel) packages installed on your x86 Linux system.
If you really prefer to build the kernel natively on the Raspberry Pi, make sure that
you have the gcc, make, and libncurses-dev (or ncurses-devel) packages in-
stalled. Then, simply omit the ARCH=arm CROSS_COMPILE=arm-rpi-linux-
gnueabi- flags from each command-line invocation. You will also need to have a
copy of the Raspberry Pi Linux kernel source tree present in the running Linux
filesystem.
Download the Kernel Source Tree
First you’ll need to download a copy of the Raspberry Pi Linux kernel source tree. There
are currently several branches under development:
rpi-3.2.27
This was the original kernel source that the first Raspberry Pi Linux distributions
were using, but it is rather out of date at this point.
rpi-3.6.y
This is the active development kernel source tree, based on the kernel indicated
(3.6.11 as of this writing).
rpi-3.8.y, rpi-3.9.y, rpi-3.10.y, and rpi-3.11.y
These branches were created to track the various newer kernels. If you need
something specific with a newer branch, these might help you out.
The instructions in this hack will work for any kernel branch, but we strongly recom-
mend that you start with the rpi-3.6.y source tree, because it is still getting new
functionality and has the added advantage of several additional upstream releases’
worth of bug fixes and features.
Either way, you need to check out the Raspberry Pi Linux kernel source tree from Git.
We recommend you put this checkout in your ~/raspi working directory on your Linux
laptop (which you created in Hack #04), but if it doesn’t exist, just run mkdir ~/raspi):
77
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
$ cd ~/raspi
$ git clone git://github.com/raspberrypi/linux.git
This currently defaults to a 3.6.y checkout, but you can always confirm that by trying
to manually switch to the rpi-3.6.y branch:
$ cd ~/raspi/linux
$ git checkout rpi-3.6.y
If you want to use a different version of the source tree (e.g., 3.2.27-based), manually
switch to the rpi-$VERSION branch using the same method, but substitute rpi-
$VERSION for the Git checkout.
Alternatively, you can download a tarball from the GitHub website, which contains a
current copy of the code tree:
rpi-3.2.27: https://github.com/raspberrypi/linux/archive/rpi-3.2.27.tar.gz
rpi-3.6.y: https://github.com/raspberrypi/linux/archive/rpi-3.6.y.tar.gz
These links should never go stale, because GitHub generates these tarballs each time
you request them. This method has the advantage of being slightly faster, but we
usually prefer to checkout the full Git source tree, because we can then use the Git
tools to apply the latest changes from the upstream repository without needing to
download a new Linux kernel source tree again.
If you download these tarballs (into ~/raspi), simply unpack them using the following
tar command:
$ cd ~/raspi
$ tar xvfz rpi-3.6.y.tar.gz
This will create a linux-rpi-3.6.y/ (or linux-rpi-$VERSION) directory in ~/raspi (the
Git checkout will create a linux/ directory instead).
Next, you need to make sure you have a clean working kernel source tree. Change into
your Raspberry Pi Linux kernel source directory and run:
$ make mrproper
Linux Kernel Trivia
The Linux kernel contains a make clean target as well as the make mrprop
er target. The make mrproper target is a sort of “super clean,” as it does
everything that the clean target does, but a whole lot more (the clean target
leaves generated artifacts behind, while mrproper brings the kernel source
tree back to a pristine state).
78 RASPBERRY PI HACKS
But why is it called mrproper? It’s named after Mr. Proper, the internationally
used name of a well-recognized mascot for cleaning products. In the United
States, he is known as Mr. Clean.
Configure the Linux Kernel
Now you’re ready to start configuring the Linux kernel. This can be a daunting task if
you have never done it before, but that doesn’t mean you shouldn’t give it a shot!
(That’s the whole reason you bought a book called Hacks, right?)
The key to success is to start with a good default configuration that is known to work
properly on the Raspberry Pi. A base default configuration file is included in the Linux
kernel source checkout. This config file has the options enabled to support the hard-
ware embedded within the Raspberry Pi. Just copy it to the top-level Raspberry Pi
Linux kernel source directory (as .config):
$ cp arch/arm/configs/bcmrpi_defconfig .config
We recommend this approach, because it will minimize the number of questions that
you have to answer later.
Other Sources for Kernel Config Files
There are other places to get kernel config files. If you have an active Rasp-
berry Pi Linux instance that you just want to make minor kernel changes to,
you can get a copy of the configuration file that corresponds to that running
kernel image. To do this, type the following from within the Raspberry Pi
Linux instance:
$ zcat /proc/config.gz > ~/.config
Then, copy ~/.config from the Raspberry Pi Linux instance onto your Linux
laptop and place that copy in your Raspberry Pi Linux kernel source direc-
tory (as .config).
You should be aware that if you take this .config file from a kernel that is of
a different version than the source tree you are working on, this .config file
will not match up with the same configuration options that those kernels
have. It will still work, but you will end up having to answer a lot of questions
about these missing options in a later step.
We’ve also placed a copy of our Raspberry Pi kernel configuration file here
into the GitHub repository for this book. You should be able to use it as a
starting point if nothing else works. To download it, simply clone our repos-
itory:
79
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
$ git clone https://github.com/spotrh/rpihacks
In the new rpihacks directory, you will see a file named kernel-
book.config. Copy this file into your top-level Raspberry Pi Linux kernel
source directory (as .config).
From here onward, you will need to specify the ARCH=arm CROSS_COMPILE=arm-rpi-
linux-gnueabi- options to all of the make invocations. This tells the Linux kernel
code that you are building for a non-native architecture (ARM) and with a specific
cross-compiler toolchain. The “-” at the end of the arm-rpi-linux-gnueabi- string
is important, because the Makefiles will append the necessary binary commands
(e.g., gcc, ar, ld) to the end.
Now you need to make sure that this base configuration file is brought up to date:
$ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- oldconfig
This command will ask you to provide answers to any values that are not defined in
the config file, and you’re likely to have more than a few blanks to fill in. For the vast
majority, you should simply hit Enter to accept the default, but there are a few that we
recommend you set if prompted:
Cross-compiler tool prefix (CROSS_COMPILE) [] (NEW)
Set this to arm-rpi-linux-gnueabi-. This is not entirely necessary, but it is better
to be safe than sorry here.
Local version - append to kernel release (LOCALVERSION) [] (NEW)
Set this to something unique. This will help you differentiate your custom kernel
from the prebuilt kernel images. We suggest using something that you will identify
easily as it relates to your project, or something containing the build date.
Those two settings will come early on (usually as the first two you see). After they’re
set, you just need to hit Enter several hundred times over the span of about 10 minutes.
Don’t worry too much about reading or changing these other options, as there is a
better way to find and make configuration changes in the next step. Just keep hitting
Enter until it says:
#
# configuration written to .config
#
80 RASPBERRY PI HACKS
Once that has happened, you should be back at a shell prompt. Now you can use the
better, more intuitive menuconfig option to make specific configuration changes:
$ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- menuconfig
This will present you with an ncurses-based Text User Interface (TUI) menu configu-
ration system, as shown in Figure 2-9.
Figure 2-9.
TUI menu configuration system
You can navigate through this system with the arrow keys and the Enter button.
Here you can make all sorts of configuration changes. Generally, if you’re doing this,
you’re enabling drivers or specific kernel features that you need for a hack. While we
can’t possibly list every option in the Linux kernel configuration universe (that would
be an entirely different book), we do point out options that need to be enabled in
several hacks in this book.
If you aren’t sure about an option, the TUI will let you see more information about any
specific configuration option by using the right arrow to move to Help (when an option
is highlighted) and then pressing Enter. The following screen presents a short sum-
mary of the option (usually in English, although sometimes in kernel-hacker dialect)
beneath the Kconfig syntax name for the option.
81
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
There are usually two ways to enable an option:
Compiled-in
If you opt to compile in a feature or driver, it will appear in the TUI with an asterisk.
You can select to compile in an item by hitting the spacebar when it is highlighted.
The upside to compiling things into the Linux kernel is that the feature/driver will
always be active. The downside is that the kernel becomes bigger and will use
more memory.
Modular
To enable a feature or driver as a module, just hit the M key when the item is
highlighted. Not everything can be built as a module, but most things can.
PinMux
One advantage to modularizing drivers is that it simplifies PinMux control on the
Raspberry Pi. PinMux is short for Pin-Multiplexing. The Broadcom BCM2835
system-on-chip used in the Raspberry Pi uses PinMux to select which signals will
be present on the pins of the chip. The multiplexing is necessary because the
number of available signals exceeds the number of available pins. Or, to put it
simply, some of the GPIO pins can be connected to different things within the
BCM2835 at different times. If your drivers which affect the GPIO pins or devices
are built as modules, you can switch the PinMux by simply loading/unloading the
module.
You should also be aware that some items, when enabled in the TUI, will expose ad-
ditional items (or even new submenus).
Quite a few of the hacks in our book connect to the Raspberry Pi across the I2C bus,
so you will definitely want to enable “I2C Support” (CONFIG_I2C). This option is under
the Device Drivers menu, and you will want to compile it into your kernel.
82 RASPBERRY PI HACKS
Additionally, you will need to go into the I2C Support submenu, and enable compiled-
in support for the “I2C device interface” (CONFIG_I2C_CHARDEV) and “Autoselect perti-
nent helper modules” (CONFIG_I2C_HELPER_AUTO). Figure 2-10 shows the menu with
these options properly enabled.
Figure 2-10.
I2C support options properly enabled
Then, in the “I2C Hardware Bus support” submenu, enable the BCM2708 BSC (CON
FIG_I2C_BCM2708) driver (again, as compiled-in, not as a module). This is the hardware
driver for the Raspberry Pi’s I2C bus controller. The BCM2708 I2C baud rate defaults
to 100000, and that is fine. It should look like Figure 2-11.
83
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Figure 2-11.
BCM2708 BSC driver enabled to be compiled-in to the kernel
It is almost never risky to enable something as a module (“M”), unless it is marked as
EXPERIMENTAL or DANGEROUS. However, it is rather risky to disable something that
is enabled in the default configuration. Unless you know what you are doing, you are
probably better off leaving all of the default settings alone.
That said, do not be overwhelmed by the sheer volume of configuration choices. Feel
free to explore by navigating through menus and reading the help entries. You just
might find something interesting.
When you’re done configuring your kernel, return to the top-level menu and select
Exit. The TUI will prompt you to save your new configuration. It will exit and leave you
at a shell prompt, at which point you’re ready to build the kernel image.
Build the Kernel Image
To speed up the build, you can parallelize the compilation by passing the -j flag to
make. You’ll need to know how many CPU cores are present on your build system to
determine the ideal value.
Hack #21 provides a longer explanation of this concept, but the basic formula we rec-
ommend trying is the number of CPU cores you have multiplied by 1.5. For example,
84 RASPBERRY PI HACKS
on an eight-core laptop, it would be 12. Using that example with this flag, the command
to kickoff the build is:
$ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- -j12
If you do not want to run a parallel compilation, simply omit the -j## flag from the
command (note, however, that this will cause the build to take significantly longer).
At this point, your laptop is cross-compiling the core Linux kernel image. Depending
on the options you have selected, this might take a while, but if all goes well, it will
finish compiling without errors. Next, you’ll need to build the matching kernel mod-
ules.
To keep the size of the core Linux kernel image small, many of the drivers for devices,
filesystems, and optional functionality are normally configured to be built as Linux
kernel modules. These make up a large tree of files, where each file is an individually
loadable device driver.
Most Linux distributions (including Pidora and Raspbian) contain support for auto-
loading appropriate kernel modules as they are needed, but you might find some sit-
uations in which you’ll want to load a kernel module manually. This model also helps
with memory management and boot object size. The default configuration we provide
with this book modularizes as much as possible.
To start the Linux kernel modules build, run:
$ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- modules -j12
This will also take some time, but it should finish without errors. If a module fails to
build, you might need to disable it in the kernel configuration file and restart the whole
process, but this is unlikely. Now, you just need to install your new kernel.
Install a New Kernel
The core Linux kernel image for the Raspberry Pi is a specially formatted copy of the
zImage binary, compiled as an ARM boot executable. This image contains the primary
functions of the Linux kernel, and it contains all the necessary code for booting into
the Linux operating system.
This is the file that is booted by the Raspberry Pi GPU firmware. It is not usually a large
file (slightly less than 3 MB). If you’ve built a custom Linux kernel from source as
described in the previous sections, you can find a copy of the core Linux kernel image
at arch/arm/boot/Image within that kernel source tree.
To install a new kernel, you will need to copy files onto the SD card containing your
Raspberry Pi Linux distribution. If you have not already mounted your SD card on your
Linux laptop, go ahead and do so by following the directions in Hack #02. Make sure
85
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
that both the root and boot partitions are mounted, because you will need to copy
files to both partitions.
Go ahead and copy the new core Linux kernel image into the mounted boot partition
on the SD card:
$ su -c 'cp -a arch/arm/boot/Image /mnt/raspi-boot/new-kernel.img'
By default, the Raspberry Pi GPU firmware attempts to boot kernel.img from the boot
partition. Since you are installing a new kernel, you probably want to override this
behavior.
If you want it to boot a different filename, you can specify that by adding a line to
config.txt (also found on the boot partition). If for some reason config.txt is not
present on the boot partition (it is not necessary for the Raspberry Pi to boot Linux),
simply create a new file with that filename.
To boot a specific file, edit /mnt/raspi-boot/config.txt and add a line like this:
kernel=new-kernel.img
In this example, the Raspberry Pi GPU will now look for new-kernel.img on the boot
partition of the SD card and try to execute it at boot time. Conveniently, this is the
name we used when we copied over the new kernel image. We used a new name here
to avoid conflicts with the stock Linux kernel image file kernel.img that came with your
Raspberry Pi Linux distribution. From here on, we will assume that the Raspberry Pi
Linux distribution is configured to boot your new kernel image file (as specified by
kernel=).
The second set of files that you need to copy over are the prebuilt Linux kernel modules
that match the new kernel image file. If you built a new Linux kernel from source, you’ll
need to install your new modules into a temporary directory. To do this, simply run
these commands from the top level of your kernel source code tree:
$ mkdir ~/modules
$ make ARCH=arm CROSS_COMPILE=arm-rpi-linux-gnueabi- \
INSTALL_MOD_PATH=~/modules modules_install
Unlike the core Linux kernel image (which has to be on the boot partition), the kernel
modules live in the root partition—specifically, in the /lib/modules directory. All you
need to do to install them is to copy the whole versioned directory (or directories)
into /lib/modules on the mounted root SD card partition. For your custom-built kernel,
these commands will copy over the proper modules:
$ cd ~/modules
$ su -c 'cp -a lib/modules/* /mnt/raspi-root/lib/modules/'
86 RASPBERRY PI HACKS
Post-Installation Tasks
When the last of these modules finishes copying onto the root partition, make sure
you have config.txt on the mounted boot SD card partition configured to boot the
new kernel image (or unconfigured, so that kernel.img is booted). Then run the sync
command a few times to ensure the data has all arrived onto the SD card:
$ sync;sync;sync
Now it should be safe to unmount the SD card partition(s) and eject the SD card. You
can unmount these partitions either from the GUI interface of your Linux laptop, or
you can manually unmount them from the terminal by running these commands:
$ cd ~
$ su -c 'umount /mnt/raspi-boot'
$ su -c 'umount /mnt/raspi-root'
Make sure to change into a directory that is not in either of the mounted partitions
before attempting to run the umount command, or that command will not succeed.
Next, put your SD card into your Raspberry Pi and plug it in. You should see it boot
into the Linux kernel successfully. Once you’ve logged in, you can now run:
$ uname -a
Linux myrpi 3.6.11+ #24 PREEMPT Sun Aug 19 21:28:36 BST 2013 armv6l GNU/
Linux
This will print out a list of system information, but the most important one is the ver-
sion of the running Linux kernel. It should match the version of the modules directory
(or directories) that you just copied over. You can also confirm that the build date
printed out for the running kernel matches the date that you built your new kernel.
HACK 23 Update to the Latest Prebuilt Kernel
Want the latest Linux kernel features for your Raspberry Pi? Of course
you do, and there is a way to get them without having to build it from
source.
The nice folks at the Raspberry Pi Foundation are regularly hard at work adding new
features to their Linux kernel source tree. They also go one step beyond and regularly
update a copy of a prebuilt Linux kernel image. This kernel is configured with a set of
options and modules intended specifically for the Raspberry Pi. Using this kernel
means that you can be sure that all of the hardware built into the Raspberry Pi will be
properly enabled, along with any Raspberry-Pi-specific functionality.
87
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Distribution specific features
Some Linux distributions may assume the presence of features which are not en-
abled or supported in the Raspberry Pi Foundation prebuilt kernel images. Exam-
ples include SELinux, some extended filesystem attributes, and some typos of
cryptography. This is one of the reasons we recommend that you keep a backup
copy of the distribution provided kernel image around, just in case.
The Raspberry Pi Foundation offers prebuilt binary kernel images in the same Git
repository that they use for firmware. To get a copy of this Git tree, see the instructions
in Hack #04.
Remember that this Git tree has two branches: master, which is targeted for the Rasp-
berry Pi Linux kernel 3.2-based source tree, and next, which is targeted for the Rasp-
berry Pi Linux kernel 3.6-based source tree. You need to make sure that your kernel
and firmware revision versions match; otherwise, your kernel might not boot (or fea-
tures might not work the way that you expect). The file locations for the prebuilt kernel
files are identical for both branches of the Git repository.
The Raspberry Pi Foundation’s prebuilt Linux kernel is handy, having been designed
for use with the Pi, and it contains a wide range of common device driver modules.
However, it is missing some modules that you might need when connecting periph-
erals. If this is the case, you will want to build a custom Linux kernel from source, as
covered in Hack #22.
Get the Prebuilt Linux Kernel
The prebuilt Linux kernel images come in two parts:
The core Linux kernel image (firmware/boot/kernel.img)
The prebuilt Linux kernel modules that correspond to that image (firmware/
modules)
You can view the history of builds for the core Linux kernel image via the GitHub web-
site. If you want to see the history for the next branch, just change the branch via the
drop-down on the website, or replace master with next in the URL.
Alternative Prebuilt Kernel Variants
The Raspberry Pi foundation also provides two alternative variants of this
prebuilt kernel:
88 RASPBERRY PI HACKS
kernel_cutdown.img
This is the smallest possible Linux kernel that can be booted on the
Raspberry Pi. It contains minimal peripheral support outside of what is
absolutely needed to use the embedded devices on the Raspberry Pi.
It comes with a much smaller set of kernel modules than the standard
kernel image.
kernel_emergency.img
This is a Linux kernel image that contains a wide range of support com-
piled directly into the Linux kernel. Because so much support is com-
piled directly into this kernel, it can be treated as a “safe mode” kernel,
and it should boot properly even if the Raspberry Pi Linux userspace
has problems. The downside to this kernel image is that it is large in
comparison (9.2 M) and thus will have a performance impact. Also, it
does not come with any kernel modules, as all of the device drivers are
compiled into the kernel image!
Both of these alternative kernel images are built from the same source tree
as the normal kernel image and are present in the Git checkout (firmware/
boot). You can copy these to the boot partition using the same methods
described for the usual image. Simply change directory into the mounted
boot partition, rename any existing copies of these files to serve as backups,
and then copy the new files from the Git checkout into the mounted boot
partition.
Remember, if you want to boot into one of these kernels (or one of your
backup kernel images), just add an appropriate kernel= line to config.txt.
You might want to add multiple lines to correspond to different kernel im-
ages, but be sure to comment out any entries that you are not using by
prepending a \# character to the beginning of the line.
Now you can safely copy the new core Linux kernel image from your Git checkout onto
the boot partition (as root). You’ll want to rename this file from kernel.img when you
do this (or rename the existing kernel.img in the SD card boot partition).
Install the Prebuilt Kernel Modules
Next, it is time to install the matching prebuilt kernel modules. You can find these
modules under the firmware/modules directory from your Git checkout. There will be
at least two directories here, and each will contain a version that corresponds to the
version of the Linux kernel used to build these images (and modules). At the time of
this writing, this version was 3.6.10, which shows as:
89
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
$ ls -l
total 8
drwxrwxr-x 3 spot spot 4096 Dec 12 21:57 3.6.10+
drwxrwxr-x 3 spot spot 4096 Dec 12 21:57 3.6.10-cutdown+
What’s Up with That +?
You might have noticed that the versioned directories here have a \+ ap-
pended to them. This is a custom identifier that the Raspberry Pi Founda-
tion uses for their kernel builds, mostly to prevent conflicts with custom
kernel builds (which by default, do not contain a custom identifier).
The prebuilt core Linux kernel images will be looking for their modules in
these exact directory names (including the +), so do not rename them. If
there is an existing directory with the same name, it is reasonably safe to
overwrite it (assuming that you have also copied the matching kernel image
file from the same firmware checkout), but you can always rename the di-
rectory to act as a backup.
Just be aware that even if you boot the older kernel image via kernel= in
config.txt, it will not know how to look in the renamed modules directory
and will try to load its modules from the original versioned directory.
The 3.6.10+ directory contains the modules that are built for kernel.img, while the
33.6.10-cutdown+ directory contains the modules that are built for kernel_cut
down.img. Makes sense, right? If you have copied kernel_cutdown.img into the boot
partition of your SD card, you will want the corresponding modules, but if you have
copied only kernel.img, you can leave them alone. It will not hurt anything to also copy
the cutdown kernel modules, but it will eat up about 15 MB more on your SD card.
For the prebuilt kernel, this will copy the proper modules:
$ cd ~/raspi/firmware/modules
$ su -c 'cp -a 3.6.10+ /mnt/raspi-root/lib/modules/'
From here on out, you will need to complete the same post-installation tasks that you
would do for a kernel installed from source, as described in “Post-Installation Tasks”
on page 87.
Merging Raspberry Pi Changes into Upstream
Linux Kernel Source
At some point, ideally, the Raspberry Pi Foundation will be able to merge all
of its Raspberry Pi (and BCM2835 system-on-chip) changes into the up-
stream Linux kernel source. This will mean that it is no longer necessary to
90 RASPBERRY PI HACKS
have a separate Raspberry-Pi-specific Linux kernel source tree, and it is
possible that the Raspberry Pi Foundation will stop providing new prebuilt
kernel images as a result.
This is just speculation, though, because while the Raspberry Pi Foundation
has indicated a desire for merging its patches into the upstream Linux ker-
nel tree, and there are various kernel hackers working toward this goal, it
has not yet happened. To date, the Foundation has not given any indication
that it will stop making prebuilt kernel images. This should not be too big of
a problem if it does happen, because the Linux distributions will easily be
able to produce prebuilt Raspberry-Pi-specific Linux kernel images that
they maintain from the upstream “Linus” source tree.
We point this out only so that if you are reading this book at a future time
when this has indeed occurred and you are not seeing recently updated
prebuilt kernel images in their GitHub firmware repository, you might have
an idea why.
HACK 24 Split Memory Between the GPU and
Linux Userspace
The performance that you get from your Raspberry Pi is tightly coupled
to the amount of memory that you allocate to its core components. Be-
cause this isn’t a system you can just drop more RAM into, you should
consider the needs of your project and the best way to split the available
memory.
In the embedded hardware universe, memory is almost always a precious and scant
commodity. The performance of the system is usually tightly coupled to the amount
of present (and accessible) memory. Additionally, most embedded systems do not
have any user-serviceable method to increase the amount of physical memory, and
the Raspberry Pi is no different.
When the Raspberry Pi Model B was first released, it came with 256 MiB of memory
(either Hynix MobileDDR2 or Samsung Mobile DRAM, depending on when it was pro-
duced). The memory rests physically on top of the Broadcom media processor in the
BCM2835 system-on-chip. This is known as package on package (PoP). PoP allows
for an embedded system to combine multiple ball grid array (BGA) packages in a
vertical stack.
The Raspberry Pi system-on-chip uses a mixed logic-memory stack, which is useful
to save space and allows the hardware vendor to choose from a wide range of com-
patible options (and helps them to keep costs down). This design decision allowed
91
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
them to easily upgrade the amount of on-board memory on the Model B from 256
MiB to 512 MiB (all Model B units sold after October 15, 2012 have the larger amount).
How to Tell Which Pi You Have
If you have a Pi that’s been sitting around for a while, and you’re not sure
which one it is, you can use cat /proc/cpuinfo to find out. The results look
like this:
Processor : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS : 795.44
Features : swp half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xb76
CPU revision : 7
Hardware : BCM2708
Revision : 000e
Serial : 0000000011185abc
The part after Revision tells you which board you have. Refer to this table:
Revision code Model Rev number RAM (MB)
0002 B 1.0 256
0003 B 1 256
0004 B 2 256
0005 B 2 256
0006 B 2 256
0007 A 2 256
0008 A 2 256
0009 A 2 256
000d B 2 512
000e B 2 512
000f B 2 512
This significantly improved the performance of the Raspberry Pi. Unfortunately, mak-
ing a change to the amount of memory is a decision that can really be made only at
92 RASPBERRY PI HACKS
fabrication time, and it’s not one that a user can easily hack. Stacking these tiny BGA
units is best done by robots, not clumsy human hands.
Even with the newer 512 MiB of memory, it’s a precious resource. Because of how the
BCM2835 system-on-chip works, some of this memory must go to the GPU. You might
have seen this sort of behavior on lower-end GPU cards for x86 computers, which do
not include dedicated on-GPU memory and dedicate some system memory for GPU
usage. The Raspberry Pi firmware allows for you to customize the amount of memory
that is allocated to the GPU.
Before the 512 MiB Raspberry Pi Model B units existed, customizing memory alloca-
tion was accomplished by choosing a start.elf file corresponding to the splits shown
in Table 2-1.
Table 2-1. Memory allocation on 256 MiB Raspberry Pi Model B
ARM CPU VIDEOCORE GPU FILENAME
128 MiB 128 MiB arm128_start.elf
192 MiB 64 MiB arm192_start.elf
224 MiB 32 MiB arm224_start.elf
240 MiB 16 MiB arm240_start.elf
This worked well when the Raspberry Pi Model B firmware had only one possible
memory size (256 MiB) to support, but when they started producing the 512 MiB
Model B units, this approach no longer made sense. Among other reasons this didn’t
work, the most obvious is that twice as many splits are possible on the 512 MiB units
(even if some of them are pretty ludicrous). They also wanted the firmware to be able
to support both units, and the split-out start.elf model was very much hardcoded to
the 256 MiB size.
Allocate Memory with config.txt
The current firmware (necessary for the 512 MiB units) abandons the separate
start.elf file approach and adds support for start.elf to read in a variable (gpu_mem)
from config.txt that specifies exactly the amount the user wants to allocate to the
GPU in chunks of 16 MiB, with 16 MiB as the minimum and 448 MiB as the maximum.
To set this, open config.txt (on the boot partition of the SD card containing the Rasp-
berry Pi Linux image) in the editor of your choice and use the following syntax (where
value is an integer representing the total MiB to dedicate to the GPU, in chunks of 16
MiB, 16 to 128 MiB):
gpu_mem=(value)
93
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
The Raspberry Pi firmware sets gpu_mem=64 as the default. But just how much memory
should you allocate to the GPU? The answer depends on what your Raspberry Pi will
be used for.
If you’re using it in a headless mode (see Hack #11), you can set gpu_mem to the minimum
value of 16. If you do this, you will need to be sure that start_cd.elf and fix
up_cd.elf are present, because they will be used instead. Be careful with this, because
video will not work at all at this minimal setting, but on the upside, it will leave 496 MiB
for the ARM CPU (this gets used by Linux userspace).
For an only slightly video-friendly option, at gpu_mem=32, the Linux kernel can drive the
framebuffer at 1080p, but 3D and video processing will not work properly. At
gpu_mem=128, you will get excellent 3D and video decoding performance, but you will
leave the Linux userspace with only 384 MiB.
In the middle of the road with a 256 MiB/256 MiB split, you will give the GPU enough
memory to handle big textures, but the Linux userspace will really struggle. It is pos-
sible to increase this value up to 448 MiB, but we don’t recommend exceeding 128
MiB unless you have an exceptionally GPU-intensive use case.
While the core Linux kernel is capable of running in memory-starved environments,
most userspace applications (especially graphical ones) rely on the availability of tens
of MiB of memory to run properly. The Raspberry Pi contains less memory than most
popular smartphones (for example, the Galaxy Nexus and iPhone 5 have 1 GiB, and
the Nexus 4 has 2 GiB).
Also keep in mind that Linux aggressively pre-caches available memory that is not
currently being used by applications to improve system performance. This means that
the more memory you can allocate to the ARM CPU, the better performance you’ll get
from Linux.
Make a config.txt Compatible with 256 or 512 MiB
Models
It is possible to make a config.txt that works on both 256 MiB and 512 MiB
Raspberry Pi Model B units. To set the GPU memory to be compatible with
both units, you need to use the gpu_mem_256 and gpu_mem_512 parameters.
The gpu_mem_256 parameter is used on the 256 MiB Raspberry Pi Model B,
overrides any value set in gpu_mem=, and is ignored entirely on the 512 MiB
Raspberry Pi Model B.
The same is true of the gpu_mem_512 setting, except that it is used on the 512
MiB unit and ignored on the 256 MiB unit. gpu_mem_256 has a max value of
192, and gpu_mem_512 has a max value of 448.
94 RASPBERRY PI HACKS
On Raspbian, it is also possible to configure an explicit memory split by using the
raspi-config utility. Launch raspi-config as root, and select the Memory Split option.
For most of the hacks and projects in this book, gpu_mem=128 should be a good place
to start. It’s the setting that has given us the best possible overall performance in most
of our tinkering. Feel free to experiment, though, as the only real damage you can do
is to the Raspberry Pi’s performance, and you can always change it back.
Automatically Share Memory
While you might be able to guess how much memory you want to split between the
CPU (OS) and the GPU (graphics), there are a lot of situations where you probably will
not know for sure. In cases like this, you really want to be able to configure your Rasp-
berry Pi to split the memory on the fly, allocating it between the CPU and the GPU as
needed.
As of the post-November 2012 firmware and 3.6 Linux kernel updates, there is a better
way to manage the GPU/CPU memory split. Called the Contiguous Memory Allocator
(CMA), it enables a dynamically managed memory split between the GPU and the
ARM CPU by setting low- and high-water marks for the GPU.
The config.txt parameter for the GPU low-water mark is cma_lwm, and cma_hwm is the
parameter for the GPU high-water mark. In order to use these parameters, you also
must pass some options to the Linux kernel at boot time. You can do this by adding
these options to cmdline.txt (on the boot partition of the SD card):
coherent_pool=6M smsc95xx.turbo_mode=N
This change to cmdline.txt also has the side-effect of disabling the turbo mode
for the built-in ethernet controller on the Raspberry Pi, but you might not mind too
much unless you have a network-intensive use case. Disabling turbo mode also
sometimes improves wireless network performance (and eliminates a lot of DE-
BUG noise in the system logs in some cases).
In this configuration, you will also need to set the following values in config.txt:
gpu_mem_256=112
gpu_mem_512=368
cma_lwm=16
cma_hwm=32
cma_offline_start=16
Once you have rebooted the Raspberry Pi with these settings in place, it will result in
466 MiB memory free (212 MiB on the 256 MiB Model B unit) for the Linux userspace
by default, with more allocated to the GPU as needed (within the watermarks).
95
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
While this CMA support is comparatively new, we highly recommend trying it instead
of hardcoding the split for most common use cases. It will improve things like web
browser performance while still allowing for high GPU memory utilization cases on-
demand.
HACK 25 Update the Firmware and Prebuilt Binary
Kernel the Easy Way
Everything’s easier when there’s a tool for it, and fortunately, Liam
McLoughlin (a.k.a. “Hexxeh”) has created one for updating your Rasp-
berry Pi firmware and kernel.
rpi-update is a shell script that automates the process of updating the firmware, pre-
built binary kernel, and prebuilt VideoCore SDK files on an SD card containing a Rasp-
berry Pi Linux distribution image.
First, make sure that you have the readelf and git binaries installed in your chosen
Raspberry Pi Linux distribution. You will need these commands for successful use of
the rpi-update script. On most Linux distributions, readelf is in the binutils package
and git is in the git package.
To install it, run the following (as root) on Pidora:
$ su -c 'yum install binutils git'
or Raspbian:
$ su -c 'apt-get install binutils git-core'
To use this script, download it from within your running Raspberry Pi Linux Distribution
image with the following command:
$ wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update
You will need to put it in your $PATH and set it executable. The simplest way to do this
is to run the following commands (as root):
$ su -c 'cp rpi-update /usr/bin/'
$ su -c 'chmod +x /usr/bin/rpi-update'
Then, to update the firmware, prebuilt binary kernel, and VideoCore SDK libraries all
at once, simply run (as root):
$ su -c 'rpi-update'
There are, however, a few caveats to using this shortcut tool:
96 RASPBERRY PI HACKS
It does require you to run the script from within the running Linux environment.
Make sure that the time is set properly within the environment, or you might get
script failures relating to clock drift.
The script does not let you perform fine-grained update operations (e.g., just
update the firmware). It is an all-or-nothing experience.
The script assumes that the VideoCore files are located under /opt/vc. Some
Raspberry Pi Linux distributions (such as Pidora) place the VideoCore files in a
different location or include them in the system library directories, so this script
will not work well for them.
The rpi-update script does not use the official GitHub repository for prebuilt files be-
cause of the size of that repository. Instead, Hexxeh keeps a copy of those files in a
separate GitHub repository with a different filesystem layout.
While this separate repository seems to be manually synced with the official reposi-
tory on a regular basis, keep in mind that it is possible that you will not be getting the
absolute latest available revisions of these files. Sometimes, that’s how it goes when
you try to take shortcuts.
HACK 26 Emulate the Pi
Whether you’re travelling without your Pi, need to test something in a
hurry, or your kids have taken over the Pi while you weren’t looking, it can
sometimes be convenient to emulate it on another machine. QEMU can
help.
QEMU (short for Quick EMUlator) is an open source, hosted hypervisor. That means
that you can use it to run a Linux distro that was made for your Raspberry Pi (which
uses ARM hardware) on your usual computer (an x86 laptop, for example).
It has two modes. The first is user-mode emulation, which lets you run single programs
that weren’t compiled for your machine. But this hack focuses on QEMU’s full-system
emulation, which lets you emulate an entire computer—in this case, a Raspberry Pi.
First install QEMU, by running this command on Fedora:
$ su -c 'yum install qemu'
Or, you can run this on Debian/Ubuntu:
$ su -c 'apt-get qemu-system-arm'
Download kernel-qemu from http://xecdesign.com/downloads/linux-qemu/kernel-
qemu. You can also compile your own kernel.
97
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Why Is This Kernel Special?
You might have noticed that we have not pointed you to the hack in this book (Hack
#22) that covers building a custom kernel for booting on the Raspberry Pi. This is
intentional, because that kernel will not work on qemu_. Qemu emulates a wide range
of hardware environments, but the exact hardware found in the Raspberry Pi is not
yet one of them.
The kernel-qemu file uses the closest match available in qemu and provides the
same level of ARM optimization and runtime support. This allows you to use almost
everything in your Raspberry Pi Linux distribution userspace as is. The most no-
table exception is the videocore libraries (and any applications which use them).
Because qemu has no BCM2835 system-on-chip hardware emulation, these ap-
plications will fail to operate properly in qemu emulation.
Create a directory to work in, and put a copy of your distro’s image and kernel-qemu
in it. The rest of this example will use the Pidora 18 image (pidora-18-r1c.img) and
qemu as that directory, though you can replicate these instructions for other distros
and of course name your directories whatever you like.
Run file on the image:
$ file pidora-18-r1c.img
pidora-18-r1c.img: x86 boot sector; partition 1: ID=0xc, active, starthead
32, startsector 2048, 102400 sectors; partition 2: ID=0x83, starthead 32,
startsector 104448, 3389858 sectors, code offset 0xb8
Take the startsector number from partition 2 (bold in the previous output) and mul-
tiply it by 512 to use as the offset number when you mount the image:
$ sudo mount qemu/pidora-18-r1c.img -o offset=53477376 /mnt/pidora
Now open /mnt/pidora/etc/ld.so.preload in a text editor and comment out the one
line you find there by adding a # in front of it and saving the file. You can now unmount:
$ sudo umount /mnt/pidora
And you’re ready to start Pidora in QEMU:
$ qemu-system-arm -kernel kernel-qemu -cpu arm1176 -m 256 -M versatilepb -
serial stdio -append "root=/dev/sda2 panic=1" -hda pidora-18-r1c.img
These are the options you’re setting:
-kernel
You’re telling it to use the kernel-qemu kernel file you downloaded. If you created
your own, specify its name+/path+ here instead.
98 RASPBERRY PI HACKS
-cpu
The Raspberry Pi contains an ARM1176 core, which you specify here. To see the
complete list of options QEMU offers, use the command qemu-system-arm -cpu
help.
If you have an older QEMU installation or acquire it from a package that hasn’t been
updated, you might encounter a problem with the -cpu option, because older ver-
sions didn’t support ARM1176. You might be able to make this work by substituting
arm1136-r2, but it would be better to update your version of QEMU.
-m
This sets the virtual RAM in megabytes. It is unlikely to work with more than 256.
-M
This sets the emulated machine type. (We’re specifying the Versatile PB platform
here.)
-serial
This redirects the virtual serial port. The default is vc in graphical mode and stdio
in non-graphical mode.
-append
This option gives the kernel command-line arguments.
-hda
This is the location of the image of the distro you’re emulating.
You can read further documentation of QEMU’s options at http://qemu.org.
This will take you to the first boot screen, and you can go through that process just
like you would on an actual Pi. It will reboot at the end, but QEMU will close, and you’ll
have to start it again. Just press the up arrow once to get to the previous qemu-system-
arm command and run it again.
This time you’ll boot through to the login screen and can use it as if you were on an
actual Raspberry Pi.
HACK 27 Try Occidentalis: The Raspberry Pi Distro
for (Advanced) Education
If you’re interested in using the Pi for hardware-hacking education (or
learning!), Adafruit’s Raspberry Pi Educational Linux Distro (a.k.a. Occi-
dentalis), is a great place to start.
99
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
Raspbian was one of the first Linux distributions designed specifically for the Raspb-
ery Pi, and it was based on Debian 7.0, nicknamed “Wheezy.” Thus the Raspberry Pi
version was named with the portmanteau “Raspbian Wheezy.” But online electronics
shop Adafruit found that Raspbian Wheezy didn’t have some of the features it most
wanted for hacking through the Raspberry Pi’s breakout pins, so it decided to create
its own. It’s called Occidentalis and is based on Raspbian Wheezy with hardware SPI,
I2C, and WiFi support built in, among other things.
Occidentalis is recommended for those with Linux experience who are interested
in taking full advantage of the hardware. Despite the “for education” aspect, it’s
not meant for beginners. That doesn’t mean it’s useless for kids; rather, it means
that this is a do-it-together sort of project.
Occidentalis is worth mentioning in this book, because it is intended for use with elec-
tronics. This means that it comes preconfigured in kernel and userspace to access
and control some commonly available sensors and components. This is especially
true if they come from Adafruit. Using Occidentalis will save you some time if you’re
attempting Hack #37.
As of this writing, the current version of Occidentalis is v0.2, based on Raspbian
Wheezy from August 16, 2012. Version 0.1 includes:
Firmware updating: Liam McLoughlin (“Hexxeh”) created a tool called rpi-
updater to update the Raspberry Pi’s firmware. We talk about it in more detail in
Hack #25.
I2C and hardware SPI supported and initialized at boot.
Ready-to-go sshd at first boot: At boot, the ssh keys are generated with a user-
name and password of pi/raspberry on raspberrypi.local.
Support for WiFi through the Realtek RTL8188CUS USB module, a tiny 802.11b/
g/n WLAN controller, which you can purchase from Adafruit and other vendors
for about $12.
One-wire support on GPIO 4. See this GitHub page.
Version 0.2 includes those features as well as:
Removed persistent wlan0 entry
RTC, lm-sensors
Kernel modules DS1307, AD626 I2C digipots, HMC6352, BMP085, and ADS1015,
which support common sensors, like weather sensors
Custom PWM/Servo kernel module
100 RASPBERRY PI HACKS
Occidentalis and Hynix
If your CPU says “Hynix” in a handwriting-style font on it, that indicates that you
have Hynix RAM. It will not work with Occidentalis as of version 0.2. The next ver-
sion is expected to be compatible.
Download the most recent version of Occidentalis at http://learn.adafruit.com/. It is
only a 99 MB download, which decompresses to a 2.6 GB image, so you only need a
4 GB card, unless you want extra room for storage. As of v0.2, you should see the
raspi-config tool at boot. If not, or if you’d like to return to it later, enter:
$ sudo raspi-config
What’s with the Crazy Name?
For starters, it’s a lot quicker to type “Occidentalis” than “Adafruit Raspberry Pi
Educational Linux Distro.” But if you go to http://learn.adafruit.com, you’ll notice
that the Occidentalis logo looks a lot like the Raspberry Pi logo, but a bit darker.
Rubus occidentalis is a particular species in the rose family more commonly known
as “black raspberry,” hence the name and the logo.
Your options in raspi-config should look familiar if you’ve used Raspbian, upon which
Occidentalis is based. Here are the ones you’ll most likely want to use or change up
front:
expand_rootfs
Clicking this will give you no further options; it will simply expand the root partition
to fill the available space on the SD card, which will be available after the next
reboot.
change_pass
Since the pi user’s password is publicly known, it’s a good idea to change it at first
boot.
boot_behaviour
Tell it whether you want to boot to the command line or to the GUI desktop.
update
Update to the latest packages.
Of course, for update, you’re going to need to be online, which is easy if you plugged
into a wired connection. But if you’re using a WiFi dongle, you’ll have to set up the
101
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
wireless connection first. Though Raspbian offers a GUI tool on the desktop to do so,
Occidentalis does not. Open the network interfaces file in a text editor:
$ sudo vi /etc/network/interfaces
Edit the last two lines for your network configuration:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid "Change this to your network SSID"
wpa-psk "Change this to your network password"
Remember to leave the quotation marks intact. Reboot, and your wireless connection
should be working.
It’s also worth noting, particularly if you’re using the Raspberry Pi with your kids, that
Occidentalis (and generally anything on the Pi) is not going to be up to the speed they
expect. In fact, it’s almost certain that at some point you’re going to assume that
something’s not working when really it’s just taking much, much longer than you ex-
pect—even “simple” things, like opening a Midori browser window or going to a web
page. Patience is the key with the Pi.
HACK 28 Monitor the Pi’s IP Address
Sure, you can ifconfig every time you need to know your Pi’s IP address.
Or you could see it at a glance any time.
This hack is all about knowing the IP address on your Pi. Unless you keep your Pi
connected to a monitor and a keyboard all of the time, or have its IP statically assigned,
you might not be able to easily determine its IP address. With a little bit of hardware
and a little bit of software, you’ll be able to answer that question whenever you want
to, simply by taking a look at your Pi, as shown in Figure 2-12.
102 RASPBERRY PI HACKS
Figure 2-12.
Raspberry Pi showing the eth0 IP
How do we perform this magical feat? Well, the trick is in another Adafruit project kit:
the LCD Pi Plate. The lovely and talented folks over at Adafruit have designed a simple
way to stack an 16 x 2 LCD and a simple keypad right on top of a Raspberry Pi. It comes
as an unassembled kit, but putting it together is simple.
Build the LCD Pi Plate
To assemble the LCD Pi Plate, you will need:
A soldering iron (and solder)
A LCD Pi Plate Kit (it includes a 16x2 Blue LCD, but Adafruit sells other colors)
Fine wire cutters
A narrow-tipped Phillips screwdriver
Tall stacking header (optional)
There are many different ways to connect an LCD to a Raspberry Pi, but the LCD Pi
Plate has some notable advantages for this hack. The LCDs that Adafruit uses require
a lot of digital pinouts (six to nine, depending on the functionality of the LCD device).
If you attached this device directly to your Raspberry Pi, you’d take up a lot of GPIO
pins simply to add an LCD.
But the LCD Pi Plate provides a stackable way to add an LCD (think Arduino shield)
that uses only two pins, the I2C pins. Also, because of how the I2C bus works, you can
attach additional devices to those pins and they will appear on the I2C bus (as long
as they do not have conflicting addresses). On top of that, you get five push buttons
that you can use to interact with the LCD.
Adafruit has a fantastic tutorial that walks you through the process of assembling the
LCD Pi plate. But if you’re unable to view it for some reason, the kit is very straight-
forward.
Basically, you solder in the two 220 ohm resistors (labeled Red, Red, Brown, Gold) in
the slots labeled RED and BLUE, and the 1 remaining resistor (330 ohm, labeled Or-
ange, Orange, Brown, Gold) goes in the slot labeled GREEN. Trim the excess leads
103
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
away after soldering. Then, insert all of the push buttons in the marked button slots
(all the way flush with the board) and solder them in.
Next, solder in the potentiometer (it has three “legs”) in the slot marked Contrast,
and the MCP23017 i2c port expander chip gets soldered into the slot marked
(MCP23017). Just make sure you align the notch in the chip with the notch in the
silkscreened outline, or it will not work.
At this point, we recommend deviating from the Adafruit kit a bit. It comes with a
normal height header connector (looks like a black plastic rectangle with holes and
pins on the other side), which will work fine, but if you want to be able to connect other
devices through the LCD Pi Plate (specifically, the Pi Cobbler), you should buy one of
the extra-tall stacking headers. Either way, put the header in the underside of the
board so that the pins stick up through the top. The header is where it will connect to
the Raspberry Pi GPIO pins. Solder it in (on the top).
Then, stick the rubber bumper to the underside of the board, right above where you
soldered in the buttons, sitting flat, as close as you can get it to the buttons and the
left edge without overlapping or going off the board.
Break off a 16 pin length of the header pins (or 18, if you bought a different LCD that
requires more), and insert it into the top of the LCD Pi Plate with the long pins sticking
up. Put the LCD into position, setting into to the long header pins. Solder each of the
header pins on the underside of the board and on the top of the LCD.
At this point, it should be completely assembled (and sturdy). You can push it onto
your Raspberry Pi, inserting the GPIO pins into the connector so that it lines up neatly
on top of the Raspberry Pi.
Again, if any of these steps are unclear, the Adafruit online tutorial is excellent, so you
should refer to it if you get confused along the way.
Install Software to Control the LCD Pi Plate
Adafruit is also worthy of respect because it writes open source software to drive the
hardware that it sells. The LCD Pi Plate has a Python library written for it that you can
use to access and program the LCD and buttons. You can get a copy from their GitHub
repository, but we have also included a copy in the GitHub repository for this book
(along with some additional code that we wrote to monitor the IP address on the Pi).
Go ahead and clone our GitHub repository on your Raspberry Pi (if you haven’t done
it already):
$ git clone https://github.com/spotrh/rpihacks
In order for any of this software to work, you need to enable the I2C support in the
Linux kernel. If you’re using a custom kernel (on any Linux flavor), configured as de-
104 RASPBERRY PI HACKS
scribed in Hack #22, you don’t need to do anything here. If you’re running Pidora or
Occidentalis without a custom kernel, you also have everything you need need pre-
configured.
But if you’re running a Raspbian instance running your kernel, you will need some
additional configuration to enable I2C support. Specifically, you need to run the fol-
lowing command:
$ su -c 'modprobe i2c-bcm2708'
To make that persistent, you will also want to edit /etc/modules and add these lines to
the end of the file:
i2c-bcm2708
i2c-dev
On any distro, you’ll need to install some software to add a Python module for System
Management Bus (SMBus) support (you can think of SMBus as a stricter version of
I2C), the python-rpi, the I2C utilities, and the python-netifaces module (this is how
you will get the IP address information).
Pidora doesn’t have a packaged version of python-smbus in release 18 (the current
release as of this writing), so we’ve included a RPM package for you in the book’s
GitHub repository.
On Pidora, run:
$ su -c 'yum install i2c-tools python-rpi.gpio python-netifaces -y'
$ su -c 'yum install rpihacks/i2c-tools-python-3.1.0-5.fc18.armv6hl.rpm --
nogpgcheck'
On Raspbian/Occidentalis, run:
$ su -c 'apt-get install python-dev python-rpi.gpio python-smbus i2c-tools
python-netifaces'
Run the Code
With this software installed, you can scan the I2C bus (bus 1) for the LCD Pi Plate:
$ su -c 'i2cdetect -y 1'
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: 20 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
105
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
Sure enough, you can see the Adafruit LCD Pi Plate on the I2C bus, as device number
20.
Now, go ahead and change into the Adafruit_CharLCDPlate/ directory within your
checkout of our GitHub repository:
$ cd rpihacks/Adafruit_CharLCDPlate
In that directory, you will see a few Python files. Most of these provide the library of
functions necessary to access the LCD Pi Plate. If you just want to test proper oper-
ation of your wiring and soldering work, you can run the Adafruit test script:
$ su -c 'python ./LCDtest.py'
This will cycle through the background colors and print text strings to the LCD when
you press the buttons on the Pi Plate. If you are using the Blue 16x2 LCD that normally
comes with this kit, it does not support different background colors, so this program
will seem to dim the background depending on which button you press. Don’t get
scared if this happens.
If no visible text appears, but you can see the LCD blinking, you probably just need to
adjust the contrast. Use your fine-tipped Phillips screwdriver to turn the potentiom-
eter (it’s the round knob next to the buttons with a Phillips-shaped slot in it) until text
appears.
When you’re satisfied with the test script, it’s time to get to the good stuff. We’ve
written a different Python script that, when executed, will run a simple program that
displays the IP addresses for eth0 and wlan0. It also has a crude menu structure, so
that you can push the Up and Down button on the LCD Pi Plate to switch between
displaying the IP address for eth0 and wlan0, respectively. The other buttons will re-
turn you to the menu screen.
To run that program, simply run:
$ su -c 'python ./LCD-pi-plate-demo.py'
If you want that program to run in the background, just add a & after ./LCD-pi-plate-
demo.py (but within the '' marks for the su -c invocation).
You should see this on the LCD panel:
Pi IP Addrs
UP:eth0 DN:wlan0
If you press the Up button on the LCD Pi Plate, it will try to display the address for eth0
(if any).
106 RASPBERRY PI HACKS
If you press the Down button on the LCD Pi Plate, it will try to display the address for
wlan0 (if any).
While we know that the Raspberry Pi does not have built-in wireless networking sup-
port, it is common for people to add that support by connecting a USB wireless device.
While eth0 and wlan0 devices are hardcoded in our script, you can easily change them
if you’d prefer to display other networking devices. This code is simple: if you have a
basic understanding of Python, you should be able to figure out how it works. Feel free
to take what we’ve made and improve upon it!
HACK 29 Run Android on the Raspberry Pi
Read through this chapter and got tired of all the Linux? Or maybe you
just love Android. Either way, it’s not impossible to run Android rather
than a Linux distribution on your Raspberry Pi, but this is a project for
the dedicated hackers.
The good news is that there is a community based around running Android on the
Raspberry Pi, which means if you’ve decided to give it a shot, there are people to whom
you can turn. They gather information on a wiki at http://androidpi.wikia.com/wiki/
Android_Pi_Wiki. For a quick status check, log into their IRC channel, #razdroid, on
Freenode.
The bad news is that this isn’t one of the faster moving communities you’ll find. This
isn’t a reflection on the community at all. Rather, the Raspberry Pi was simply not
designed for Android. In July 2012, Eben Moglen posted on the Raspberry Pi blog
about the progress on a port of Android 4.0 (Ice Cream Sandwich) for the Pi. Unfortu-
nately, that was well over a year ago as of this writing, and it is also the last update on
the subject. The Razdroid wiki now states “Very doubtful that any Android that will be
usable will ever be released.
But even a nonfunctional system is an opportunity for learning, and learning is what
the Raspberry Pi was designed for. So if Android and Raspberry Pi both interest you,
there’s no harm in giving it a shot. The worst outcome is that you say, “Well, that didn’t
work,” which you expected from the beginning anyway. The best outcome is that you
learn something about the Android, the Pi, or both in the process.
Since that official Android built by Broadcom hasn’t appeared yet, the working builds
are based on CyanogenMod, a popular replacement firmware for Android-based
107
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
phones and tablets. CyanogenMod isn’t the only such replacement, but it is one of
the most popular ones.
Another Odd Name
“Cyanogen” was the screen name of developer Steve Kondik, whose re-
placement firmware for the HTC Dream was built on one by a developer who
stopped work on his popular mod and directed its users to Cyanogen’s.
The short way to go about this is to download one of the images that others have built
and install it to your SD card. CyanogenMod 9 (based on Android 4.0)is so useless as
to be considered unusable. Thus the available images are built on CyanogenMod 7.2
(based on Android 2.3).
If you’re an Android phone or tablet user who enjoys CyanogenMod, you recognize
that the current version is well past either of these.
The wiki describes this version as “Boots, very slow, barely usable.” However, there
are more than a few blog posts from people who enjoy it for some purpose or another,
so don’t let that deter you.
The bottom of the main page of the Android Pi wiki includes several download links.
The first has notes that state it may or may not work only on Model A Raspberry Pis.
We used cm7_img_24-7-2012.tar.gz, the image for CyanogenMod 7.2.
Download the ZIP file and extract the image using dd, replacing /dev/mmcblk0 with the
location of your SD card and the img filename with the correct one if you’re using a
different image:
$ dd bs=4M if=cm7_img_24-7-2012.img of=/dev/mmcblk0
Then put your SD card in the Pi, power it on, and you’ve got Android on Pi, as shown
in Figure 2-13.
If you have never built Android (or Cyanogenmod, or perhaps anything else) before,
you will need to install quite a few packages. You should also follow the steps in Hack
#21 before proceeding.
108 RASPBERRY PI HACKS
Figure 2-13.
Android running on the Raspberry Pi
The Android Pi wiki offers a set of instructions for compiling CyanogenMod to run on
your Raspberry Pi. We have run them several times on multiple systems with varied
results—mostly of the negative sort. It’s a learning exercise if this is unfamiliar territory
for you, and that is always a worthwhile venture. We offer this information largely as
fair warning to those who might get excited about the possibility but disappointed with
the result.
Note that if you do want to compile CyanogenMod yourself for the Raspberry Pi on
Fedora, you’ll need a slightly different set of packages installed from the instructions
on the wiki:
$ su -c 'yum install make curl gnupg git bison unzip zip flex gperf gcc-c++
libstdc++-devel glibc-devel.i686 zlib-devel.i686 ncurses-devel.i686 libX11-
devel.i686 mesa-libGL-devel.i686 readline-devel.i686'
Other than that, the build instructions are the same. Ideally you will end up with usable
files you can flash to your SD card. Don’t be too frustrated if it doesn’t successfully
finish—you’re certainly not alone, and this is a complicated problem. Take what you’ve
learned from the experience, and then if you still want to try Android on the Pi, simply
use the image offered on the wiki.
109
CHAPTER 2: HACKING LINUX FOR THE RASPBERRY PI
3
Raspberry Pi Around the
House
Your Raspberry Pi has one handy feature when it comes to household projects: its
size. You can easily hide it in a wall or behind a piece of furniture or put it inside larger
build projects like robots and costumes.
This chapter will give you ideas for using your Raspberry Pi for assorted projects
around the house, from the practical (like Hack #31, printing from all your computers
to one printer) to the simply fun (like Hack #35 , using your Pi in your next Halloween
costume).
HACK 30 Share Files with Samba
We accept that there’s a possibility not all of the computers in your house
run Linux. Some might even use Windows (like that one used for PlayOn
in Hack #54). In that case, this hack should help your systems communi-
cate.
Samba is an open source suite of tools for SMB/CIFS clients. In plainspeak, it lets a
Linux computer (like your Raspberry Pi) talk to a Windows machine as if it were a
Windows file or print server.
SMB (Server Message Block) is a protocol for sharing files, printers, and assorted
communications. CIFS (Common Internet File System) is the modern form of SMB.
SMB was designed to run on the NetBIOS API and runs by default on versions of
Windows since Windows 2000. Samba started as a project to reverse engineer SMB
to allow users on Microsoft systems to access files on Sun systems.
Samba works by creating a network share for directories and subdirectories you
choose on your Raspberry Pi. From your Windows machine, you can mount the share
with smbmount, and they will look like networked Windows folders. There is also an
smbclient utility that will feel like using an FTP program, if you’re more comfortable
with that method.
111
Samba requires two daemons, smbd for the sharing services and nmbd for the NetBIOS
name requests, which are controlled by the smb service. (You can use a third daemon,
winbindd, to help the Linux machine understand the Windows user and group infor-
mation on Windows NT 2000 and Windows Server 2003 systems.)
Let’s Samba!
Samba is also a Brazilian dance style popularized by Carmen Miranda, or
as you may know her, “the person who inspired the Bugs Bunny cartoons
in which he wears a hat made of fruit.” Despite thorough experimentation
on the authors’ part, there is no evidence that dancing the samba with your
Raspberry Pi will do anything but make you look silly.
The name was borrowed for the software we’re discussing here by grepping
a UNIX system’s dictionary for words that had the letters S, M, and B. You
can try this yourself by running grep -i ^s.*m.*b /usr/share/dict/words,
although as of a 1998 message about the history of Samba, creator Andrew
Trigdell notes, “Strangely enough, when I repeat that now I notice that Sam-
ba isn’t in /usr/dict/words on my system anymore!” We’re just glad he
didn’t go with “Sulphmethemoglobin.
We’ll assume you’re using a USB external hard drive with your Raspberry Pi for this
project (and it’s likely you’ll want to if you’re bothering with Samba). If you’re starting
from scratch, consider formatting it as either FAT32 or NTFS (if you’re borrowing it
from a Windows machine, it probably already is). It’s not really necessary, but it will
be handy later if you decide to no longer use it with the Raspberry Pi and want to use
that drive with the Windows machine.
Locate said drive (or USB flash drive or just the SD card—whatever you’re intending
to share):
$ fdisk -l
The output will look something like this:
Disk /dev/mmcblk0: 7822 MB, 7822376960 bytes
4 heads, 16 sectors/track, 238720 cylinders, total 15278080 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000d4f0f
Device Boot Start End Blocks Id System
/dev/mmcblk0p1 4096 147455 71680 c W95 FAT32 (LBA)
/dev/mmcblk0p2 151552 15278079 7563264 83 Linux
112 RASPBERRY PI HACKS
Disk /dev/sda: 1037 MB, 1037041664 bytes
2 heads, 63 sectors/track, 16075 cylinders, total 2025472 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0101bc87
Device Boot Start End Blocks Id System
/dev/sda1 * 32 2025471 1012720 6 FAT16
The first disk, /dev/mmcblk0, is the SD card in the Raspberry Pi. The second, /dev/
sda/, is a USB flash drive we put in one of the Pi’s USB connections to use as the
example shared storage. Create a mount directory for the drive:
$ mkdir /mnt/PiShare
To see whether you were successful, run ls /mnt, and you should see PiSamba listed.
Open /etc/fstab in your favorite text editor, so you can tell it to connect to PiSamba
at boot:
$ sudo vi /etc/fstab
The contents of the file will look something like this:
#
# /etc/fstab
# Created by anaconda
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
LABEL="rootfs" / ext4 defaults,noa
time 1 1
LABEL="boot" /boot vfat noauto,com
ment=systemd.automount 1 2
/swap0 swap swap
Add the following line at the bottom:
/dev/sda1 /mnt/PiShare vfat defaults 0 0
For the first part, use the device name you saw listed when you ran fdisk (in this
example, /dev/sda/). Be sure to change PiSamba if you used a different name for your
mount, and make ntfs-3g whatever type of hard drive format you used. Save the file,
exit, and mount the share:
$ mount -a
113
CHAPTER 3: RASPBERRY PI AROUND THE HOUSE
If you run ls /mnt/, you should see your files. If you don’t, check your disk type in the
line you added in /etc/fstab.
Samba is included with many Linux distributions and is set to start automatically. It
is not, however, necessarily included with your Raspberry Pi Linux distribution. But
that’s easy to fix.
To install Samba on Pidora, run the following command:
$ sudo yum install samba
For Raspbian, run this one:
$ sudo apt-get install samba samba-common-bin
Once it’s installed, the service will start automatically. The Samba configuration file
lives in /etc/samba/smb.conf. Open it in your editor to get it set up for your particular
needs.
If you’re nervous about editing config files, create a backup first by running
cp /etc/samba/smb.conf /etc/samba/smb.conf.backup.
It’s also a well-commented file, so feel free to read it all to get a better feel for what
you’re doing:
$ sudo vi /etc/samba/smb.conf
At the bottom of the first large chunk of comments, you’ll see this:
[global]
workgroup = WORKGROUP
#usershare allow guests = yes
#security=share
security=user
follow symlinks = yes
wide links = no
unix extensions = no
lock directory = /var/cache/samba
[pi]
browsable = yes
read only = no
#guest ok = yes
valid users = pi
path = /home/pi
#force user = pi (no longer needed)
114 RASPBERRY PI HACKS
[devices]
browsable = yes
read only = no
#guest ok = yes
valid users = pi
path = /media
force user = root
Add this to the bottom of the file:
[PiShare]
browsable = yes
read only = no
path = /mnt/PiShare
create mask = 0660
directory mask = 0771
Save the file, exit, and restart Samba. On Pidora, reboot the Samba service with:
$ su -c '/sbin/service smb restart'
On Raspbian, use:
$ su -c '/etc/init.d/samba restart'
Configure Samba Without the Command Line
If you’re using Pidora, a package available for the GUI Samba Server Configuration
Tool can modify the /etc/samba/ files for you. To install this tool, run:
$ su -c 'yum install system-config-samba'
You can start it from the command line by typing system-config-samba.
Now connect to your share from another machine. From Fedora, for example, use the
Connect to Server dialog (similar dialogs exist in any Linux distribution or on OS X or
Windows). The share address is smb:// followed by the IP address, a slash, and the
name of your share, as shown in Figure 3-1.
115
CHAPTER 3: RASPBERRY PI AROUND THE HOUSE
Figure 3-1.
Fedora Connect to Server dialog
Finally, you’ll be asked to log in. Use the information you set in /etc/samba/smb.conf,
as shown in Figure 3-2.
Figure 3-2.
Log into shared drive
Your drive is now shared and accessible from beyond your Pi.
116 RASPBERRY PI HACKS
HACK 31 Use Your Raspberry Pi as a Remote Print
Server
You’re never on the computer with the bulky, unsightly printer when you
want to print something. The Raspberry Pi is small enough that you can
hide your printer just about anywhere and let the Pi do the work of being
a print server.
You might think it would be nice to hide the bulky printer out of sight, but you’ll need
to connect to it to actually print something. If you connect the printer to a discreet Pi
running as a print server, you can connect to it from your primary computer remotely.
You might even be able to find ways to mount the Pi on the back of the printer, or just
tuck it away nearby. Either way, physically connect the printer cable to your Raspberry
Pi, and let’s get started!
The easiest and most logical way to turn your Raspberry Pi into a print server is to set
up CUPS (the Common UNIX Printing System). It’s another one of those things that’s
often included in a Linux distribution, but probably not with your Raspberry Pi distri-
bution. That’s what packages are for.
Install it on Pidora with the following command:
$ su -c 'yum install cups'
Or install it on Raspbian:
$ su -c 'apt-get install cups'
When you install CUPS, it creates a group called lpadmin whose members CUPS will
authenticate:
$ su -c 'usermod -aG lpadmin user'
Replace user with the username that will be responsible for the printers. (Create one
first if you prefer.)
Then you need to make a few changes to the CUPS configuration file in /etc/cups/
cupsd.conf. It nev