John Wiley & Sons Ltd., e Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom
For details of our global editorial oces, for customer services and for information about how to apply for permission to
reuse the copyright material in this book please see our website at www.wiley.com.
e right of the authors to be identied as the authors of this work has been asserted in accordance with the Copyright,
Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form
or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright,
Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in
electronic books.
Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. e publisher is not associated with any product or vendor mentioned in this book. is publication is designed to
provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that
the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required,
the services of a competent professional should be sought.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its
aliates in the United States and/or other countries, and may not be used without written permission. Raspberry Pi and
the Raspberry Pi logo are registered trademarks of the Raspberry Pi Foundation. All other trademarks are the property of
their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.
Google Drive™ is a registered trademark of Google™.
A catalogue record for this book is available from the British Library.
ISBN 978-1-118-79548-4 (Pbk); ISBN 978-1-118-79546-0 (ePDF); ISBN 978-1-118-79547-7 (ePub)
Set in 10 pt. Chaparral Pro by Indianapolis Composition Services
Printed simultaneously in Great Britain and the United States
Publisher’s Acknowledgements
Some of the people who helped bring this book to market include the following:
Editorial and Production
VP Consumer and Technology
Publishing Director
Michelle Leete
Associate Director–Book Content
Management
Martin Tribe
Associate Publisher
Chris Webb
Executive Commissioning Editor
Craig Smith
Senior Project Editor
Sara Shlaer
Copy Editor
Kathryn Duggan, Grace Fairley
Technical Editors
Omer Kilic
Mike Cook
Russell Davis
Marketing
Associate Marketing Director
Louise Breinholt
Marketing Manager
Lorna Mein
Marketing Assistant
Polly omas
Composition Services
Compositor
Erin Zeltner
Proofreader
Wordsmith Editorial
Indexer:
Potomac Indexing, LLC
Editorial Manager
Jodi Jensen
Editorial Assistant
Annie Sullivan
For Liz, who made it all possible.
—Eben
For my father, the enthusiastic past,
and my daughter, the exciting future.
—Gareth
About the Authors
Eben Upton is a founder and trustee of the Raspberry Pi Foundation, and serves as its
Executive Director. He is responsible for the overall software and hardware architecture of
the Raspberry Pi, and for the Foundation’s relationships with its key suppliers and customers. In an earlier life, he founded two successful mobile games and middleware companies,
Ideaworks 3d Ltd. and Podfun Ltd., and held the post of Director of Studies for Computer
Science at St John’s College, Cambridge. He holds a BA, a PhD and an MBA from the
University of Cambridge.
In his day job, Eben works for Broadcom as an ASIC architect and general troublemaker.
Gareth Halfacree is a freelance technology journalist and the co-author of the Raspberry Pi
User Guide alongside project co-founder Eben Upton. Formerly a system administrator working
in the education sector, Gareth’s passion for open source projects has followed him from one
career to another, and he can often be seen reviewing, documenting or even contributing to
projects including GNU/Linux, LibreOce, Fritzing and Arduino. He is also the creator of
the Sleepduino and Burnduino open hardware projects, which extend the capabilities of the
Arduino electronics prototyping system. A summary of his current work can be found at
“CHILDREN TODAY ARE digital natives”, said a man I got talking to at a reworks party
last year. “I don’t understand why you’re making this thing. My kids know more about setting up our PC than I do.”
I asked him if they could program, to which he replied: “Why would they want to? e computers do all the stu they need for them already, don’t they? Isn’t that the point?”
As it happens, plenty of kids today aren’t digital natives. We have yet to meet any of these
imagined wild digital children, swinging from ropes of twisted-pair cable and chanting war
songs in nicely parsed Python. In the Raspberry Pi Foundation’s educational outreach work, we
do meet a lot of kids whose entire interaction with technology is limited to closed platforms
with graphical user interfaces (GUIs) that they use to play movies, do a spot of word-processed
homework and play games. ey can browse the web, upload pictures and video, and even
design web pages. (ey’re often better at setting the satellite TV box than Mum or Dad, too.)
It’s a useful toolset, but it’s shockingly incomplete, and in a country where 20 percent of households still don’t have a computer in the home, even this toolset is not available to all children.
Despite the most fervent wishes of my new acquaintance at the reworks party, computers
don’t program themselves. We need an industry full of skilled engineers to keep technology
moving forward, and we need young people to be taking those jobs to ll the pipeline as older
engineers retire and leave the industry. But there’s much more to teaching a skill like programmatic thinking than breeding a new generation of coders and hardware hackers. Being
able to structure your creative thoughts and tasks in complex, non-linear ways is a learned
talent, and one that has huge benets for everyone who acquires it, from historians to
designers, lawyers and chemists.
Programming Is Fun!
It’s enormous, rewarding, creative fun. You can create gorgeous intricacies, as well as (much
more gorgeous, in my opinion) clever, devastatingly quick and deceptively simple-looking
routes through, under and over obstacles. You can make stu that’ll have other people looking
on jealously, and that’ll make you feel wonderfully smug all afternoon. In my day job, where I
design the sort of silicon chips that we use in the Raspberry Pi as a processor and work on the
low-level software that runs on them, I basically get paid to sit around all day playing. What
could be better than equipping people to be able to spend a lifetime doing that?
2
RASPBERRY PI USER GUIDE, SECOND EDITION
It’s not even as if we’re coming from a position where children don’t want to get involved in
the computer industry. A big kick up the backside came a few years ago, when we were moving quite slowly on the Raspberry Pi project. All the development work on Raspberry Pi was
done in the spare evenings and weekends of the Foundation’s trustees and volunteers—
we’re a charity, so the trustees aren’t paid by the Foundation, and we all have full-time jobs
to pay the bills. is meant that occasionally, motivation was hard to come by when all I
wanted to do in the evening was slump in front of the Arrested Development boxed set with a
glass of wine. One evening, when not slumping, I was talking to a neighbour’s nephew about
the subjects he was taking for his General Certicate of Secondary Education (GCSE, the
British system of public examinations taken in various subjects from the age of about 16),
and I asked him what he wanted to do for a living later on.
“I want to write computer games”, he said.
“Awesome. What sort of computer do you have at home? I’ve got some programming books
you might be interested in.”
“A Wii and an Xbox.”
On talking with him a bit more, it became clear that this perfectly smart kid had never done
any real programming at all; that there wasn’t any machine that he could program in the
house; and that his information and communication technology (ICT) classes—where he
shared a computer and was taught about web page design, using spreadsheets and word processing—hadn’t really equipped him to use a computer even in the barest sense. But computer games were a passion for him (and there’s nothing peculiar about wanting to work on
something you’re passionate about). So that was what he was hoping the GCSE subjects he’d
chosen would enable him to do. He certainly had the artistic skills that the games industry
looks for, and his maths and science marks weren’t bad. But his schooling had skirted around
any programming—there were no Computing options on his syllabus, just more of the same
ICT classes, with its emphasis on end users rather than programming. And his home interactions with computing meant that he stood a vanishingly small chance of acquiring the skills
he needed in order to do what he really wanted to do with his life.
is is the sort of situation I want to see the back of, where potential and enthusiasm is
squandered to no purpose. Now, obviously, I’m not monomaniacal enough to imagine that
simply making the Raspberry Pi is enough to eect all the changes that are needed. But I do
believe that it can act as a catalyst. We’re already seeing big changes in the UK schools’ curriculum, where Computing is arriving on the syllabus and ICT is being reshaped, and we’ve
seen a massive change in awareness of a gap in our educational and cultural provision for
kids just in the short time since the Raspberry Pi was launched.
INTRODUCTION
Too many of the computing devices a child will interact with daily are so locked down that they
can’t be used creatively as a tool—even though computing is a creative subject. Try using your
iPhone to act as the brains of a robot, or getting your PS3 to play a game you’ve written. Sure,
you can program the home PC, but there are signicant barriers in doing that which a lot of
children don’t overcome: the need to download special software, and having the sort of parents
who aren’t worried about you breaking something that they don’t know how to x. And plenty
of kids aren’t even aware that doing such a thing as programming the home PC is possible. ey
think of the PC as a machine with nice clicky icons that give you an easy way to do the things
you need to do so you don’t need to think much. It comes in a sealed box, which Mum and Dad
use to do the banking and which will cost lots of money to replace if something goes wrong!
e Raspberry Pi is cheap enough to buy with a few weeks’ pocket money, and you probably
have all the equipment you need to make it work: a TV, an SD card that can come from an old
camera, a mobile phone charger, a keyboard and a mouse. It’s not shared with the family; it
belongs to the kid; and it’s small enough to put in a pocket and take to a friend’s house. If
something goes wrong, it’s no big deal—you just swap out a new SD card and your Raspberry
Pi is factory-new again. And all the tools, environments and learning materials that you need
to get started on the long, smooth curve to learning how to program your Raspberry Pi are
right there, waiting for you as soon as you turn it on.
3
A Bit of History
I started work on a tiny, aordable, bare-bones computer about seven years ago, when I was
a Director of Studies in Computer Science at Cambridge University. I’d received a degree at
the University Computer Lab as well as studying for a PhD while teaching there, and over
that period, I’d noticed a distinct decline in the skillset of the young people who were applying to read Computer Science at the Lab. From a position in the mid-1990s, when 17-yearolds wanting to read Computer Science had come to the University with a grounding in
several computer languages, knew a bit about hardware hacking, and often even worked in
assembly language, we gradually found ourselves in a position where, by 2005, those kids
were arriving having done some HTML—with a bit of PHP and Cascading Style Sheets if you
were lucky. ey were still fearsomely clever kids with lots of potential, but their experience
with computers was entirely dierent from what we’d been seeing before.
e Computer Science course at Cambridge includes about 60 weeks of lecture and seminar
time over three years. If you’re using the whole rst year to bring students up to speed, it’s
harder to get them to a position where they can start a PhD or go into industry over the next
two years. e best undergraduates—the ones who performed the best at the end of their
three-year course—were the ones who weren’t just programming when they’d been told to
for their weekly assignment or for a class project. ey were the ones who were programming
4
RASPBERRY PI USER GUIDE, SECOND EDITION
in their spare time. So the initial idea behind the Raspberry Pi was a very parochial one with
a very tight (and pretty unambitious) focus: I wanted to make a tool to get the small number
of applicants to this small university course a kick start. My colleagues and I imagined we’d
hand out these devices to schoolkids at open days, and if they came to Cambridge for an
interview a few months later, we’d ask what they’d done with the free computer we’d given
them. ose who had done something interesting would be the ones that we’d be interested
in having in the program. We thought maybe we’d make a few hundred of these devices, or
best case, a lifetime production run of a few thousand.
Of course, once work was seriously underway on the project, it became obvious that there was
a lot more we could address with a cheap little computer like this. What we started with is a
long way indeed from the Raspberry Pi you see today. I began by soldering up the longest piece
of breadboard you can buy at Maplin with an Atmel chip at our kitchen table, and the rst
crude prototypes used cheap microcontroller chips to drive a standard-denition TV set
directly. With only 512 K of RAM, and a few MIPS of processing power, these prototypes were
very similar in performance to the original 8-bit microcomputers. It was hard to imagine these
machines capturing the imaginations of kids used to modern games consoles and iPads.
ere had been discussions at the University Computer Lab about the general state of computer education, and when I left the Lab for a non-academic job in the industry, I noticed
that I was seeing the same issues in young job applicants as I’d been seeing at the University.
So I got together with my colleagues Dr Rob Mullins and Professor Alan Mycroft (two colleagues from the Computer Lab), Jack Lang (who lectures in entrepreneurship at the
University), Pete Lomas (a hardware guru) and David Braben (a Cambridge games industry
leading light with an invaluable address book), and over beers (and, in Jack’s case, cheese and
wine), we set up the Raspberry Pi Foundation—a little charity with big ideas.
Why “Raspberry Pi”?
We get asked a lot where the name “Raspberry Pi” came from. Bits of the name came from
different trustees. It’s one of the very few successful bits of design by committee I’ve seen, and
to be honest, I hated it at rst. (I have since come to love the name, because it works really
well—but it took a bit of getting used to since I’d been calling the project the “ABC Micro” in my
head for years.) It’s “Raspberry” because there’s a long tradition of fruit names in computer
companies (besides the obvious, there are the old Tangerine and Apricot computers—and we
like to think of the Acorn as a fruit as well). “Pi” is a mangling of “Python”, which we thought
early on in development would be the only programming language available on a much less
powerful platform than the Raspberry Pi we ended up with. As it happens, we still recommend
Python as our favourite language for learning and development, but there is a world of other
language options you can explore on the Raspberry Pi too.
INTRODUCTION
In my new role as a chip architect at Broadcom, a big semiconductor company, I had access to
inexpensive but high-performing hardware produced by the company with the intention of
being used in very high-end mobile phones—the sort with the HD video and the 14-megapixel cameras. I was amazed by the dierence between the chips you could buy for $10 as a
small developer, and what you could buy as a cell-phone manufacturer for roughly the same
amount of money: general purpose processing, 3D graphics, video and memory bundled into
a single BGA package the size of a ngernail. ese microchips consume very little power,
and have big capabilities. ey are especially good at multimedia, and were already being
used by set-top box companies to play high-denition video. A chip like this seemed the
obvious next step for the shape the Raspberry Pi was taking, so I worked on taping out a lowcost variant that had an ARM microprocessor on board and could handle the processing
grunt we needed.
We felt it was important to have a way to get kids enthusiastic about using a Raspberry Pi
even if they didn’t feel very enthusiastic about programming. In the 1980s, if you wanted to
play a computer game, you had to boot up a box that went “bing” and fed you a command
prompt. It required typing a little bit of code just to get started, and most users didn’t ever go
beyond that—but some did, and got beguiled into learning how to program by that little bit
of interaction. We realised that the Raspberry Pi could work as a very capable, very tiny, very
cheap modern media centre, so we emphasised that capability to suck in the unwary—with
the hope that they’d pick up some programming while they’re at it.
5
After about ve years’ hard grind, we had created a very cute prototype board, about the size
of a thumb drive. We included a permanent camera module on top of the board to demonstrate the sort of peripherals that can easily be added (there was no camera when we launched
because it brought the price up too much, but we’ve now made a separate, cheap camera
module available for photography projects), and brought it along to a number of meetings
with the BBC’s R&D department. ose of us who grew up in the UK in the 1980s had
learned a lot about 8-bit computing from the BBC Microcomputer and the ecosystem that
had grown up around it—with BBC-produced books, magazines and TV programmes—so I’d
hoped that they might be interested in developing the Raspberry Pi further. But as it turned
out, something has changed since we were kids: various competition laws in the UK and the
EU meant that “the Beeb” couldn’t become involved in the way we’d hoped. In a last-ditch
attempt to get something organised with them, we ditched the R&D department idea and
David (he of the giant address book) organised a meeting with Rory Cellan-Jones, a senior
tech journalist, in May 2011. Rory didn’t hold out much hope for partnership with the BBC,
but he did ask if he could take a video of the little prototype board with his phone, to put on
his blog.
6
RASPBERRY PI USER GUIDE, SECOND EDITION
e next morning, Rory’s video had gone viral, and I realised that we had accidentally promised the world that we’d make everybody a $25 computer.
While Rory went o to write another blog post on exactly what it is that makes a video go
viral, we went o to put our thinking caps on. at original, thumb-drive-sized prototype
didn’t t the bill: with the camera included as standard, it was way too expensive to meet the
cost model we’d suggested (the $25 gure came from my statement to the BBC that the
Raspberry Pi should cost around the same as a text book, and is a splendid demonstration of
the fact that I had no idea how much text books cost these days), and the tiny prototype
model didn’t have enough room around its periphery for all the ports we needed to make it
as useable as we wanted it to be. So we spent a year working on engineering the board to
lower cost as much as possible while retaining all the features we wanted (engineering cost
down is a harder job than you might think), and to get the Raspberry Pi as useable as possible
for people who might not be able to aord much in the way of peripherals.
We knew we wanted the Raspberry Pi to be used with TVs at home, just like the ZX Spectrum
in the 1980s, saving the user the cost of a monitor. But not everybody has access to an
HDMI television, so we added a composite port to make the Raspberry Pi work with an old
cathode-ray television instead since SD cards are cheap and easy to nd. We decided against
microSD as the storage medium, because the little ngernail-sized cards are so imsy in the
hands of children and so easy to lose. And we went through several iterations of power supply, ending up with a micro USB cable. Recently, micro USB became the standard charger
cable for mobile telephones across the EU (and it’s becoming the standard everywhere),
which means the cables are becoming more and more ubiquitous, and in many cases, people
already have them at home.
By the end of 2011, with a projected February release date, it was becoming obvious to us
that things were moving faster, and demand was higher, than we were ever going to be able
to cope with. e initial launch was always aimed at developers, with the educational launch
planned for later in 2012. We had a small number of very dedicated volunteers, but we
needed the wider Linux community to help us prepare a software stack and iron out any
early-life niggles with the board before releasing into the educational market. We had enough
capital in the Foundation to buy the parts for and build 10,000 Raspberry Pis over a period
of a month or so, and we thought that the people in the community who would be interested
in an early board would come to around that number. Fortunately and unfortunately, we’d
been really successful in building a big online community around the device, and interest
wasn’t limited to the UK, or to the educational market. Ten thousand was looking less and
less realistic.
INTRODUCTION
Our Community
The Raspberry Pi community is one of the things we’re proudest of. We started with a very
bare-bones blog at www.raspberrypi.org just after Rory’s May 2011 video, and put up a
forum on the same website shortly after that. That forum now has more than 60,000 members—between them they’ve contributed nearly 400,000 posts of wit and wisdom about
the Raspberry Pi. If there’s any question, no matter how abstruse, that you want to ask
about the Raspberry Pi or about programming in general, someone there will have the
answer (if it’s not in this book, you’ll nd it in the forums).
Part of my job at Raspberry Pi involves giving talks to hacker groups, computing conferences, teachers, programming collectives and the like, and there’s always someone in the
audience who has talked to me or to my wife Liz (who runs the community) on the Raspberry
Pi website—and some of these people have become good friends of ours. The Raspberry
Pi website gets more than one request every single second of the day.
7
There are now hundreds of fan sites out there. There’s also a fan magazine called The
MagPi (a free download from www.themagpi.com), which is produced monthly by com-
munity members, with type-in listings, lots of articles, project guides, tutorials and more.
Type-in games in magazines and books provided an easy route into programming for me—
my earliest programming experience with the BBC Micro was of modifying a type-in helicopter game to add enemies and pick-ups.
We blog something interesting about the device at www.raspberrypi.org at least once
every day. Come and join in the conversation!
ere were 100,000 people on our mailing list wanting a Raspberry Pi—and they all put an
order in on day one! Not surprisingly, this brought up a few issues.
First o, there are the inevitable paper cuts you’re going to get boxing up 100,000 little computers and mailing them out—and the fact was that we had absolutely no money to hire
people to do this for us. We didn’t have a warehouse—we had Jack’s garage. ere was no
way we could raise the money to build 100,000 units at once—we’d envisaged making them
in batches of 2,000 every couple of weeks, which, with this level of interest, was going to take
so long that the thing would be obsolete before we managed to full all the orders. Clearly,
manufacturing and distribution were something we were going to have to give up on and
8
RASPBERRY PI USER GUIDE, SECOND EDITION
hand over to somebody else who already had the infrastructure and capital to do that, so we
got in touch with element14 and RS Components, both UK microelectronics suppliers with
worldwide businesses, and contracted with them to do the actual manufacture and distribution side of things worldwide so we could concentrate on development and the Raspberry Pi
Foundation’s charitable goals.
Demand on the rst day was still so large that RS and element14’s websites both crashed for
most of the day—at one point in the day, element14 were getting seven orders a second, and
for a couple of hours on February 29, Google showed more searches were made worldwide
for “Raspberry Pi” than were made for “Lady Gaga”. We made and sold more than a million
Raspberry Pis in the rst year of business, making Raspberry Pi the fastest-growing computer company in the world, ever. ings aren’t slowing down: we sell more than 100,000 Pis
every month. If we’d stuck with our original plans, we’d have made 100 or so of these devices
for University open days, and that would have been it.
NOTE
The rst production Pis were made in Chinese factories, but in the last year we have managed
to repatriate all of the production to the UK. Your Raspberry Pi is now made in South Wales,
in an area of the country with a proud manufacturing heritage, but few remaining factories.
Amazingly, it costs us the same to manufacture in Wales as it did in China, and we’re able to
do that manufacture without a language or cultural barrier, and with the ability to jump in the
car and be on the factory oor in a few hours if necessary.
ere is nothing that aects the blood pressure quite like accidentally ending up running a
large computer company!
So What Can You Do with the Raspberry Pi?
is book explores a number of things you can do with your Raspberry Pi, from controlling
hardware with Python, to using it as a media centre, setting up camera projects, or building
games in Scratch. e beauty of the Raspberry Pi is that it’s just a very tiny general-purpose
computer (which may be a little slower than you’re used to for some desktop applications,
but much better at some other stu than a regular PC), so you can do anything you could do
on a regular computer with it. In addition, the Raspberry Pi has powerful multimedia and 3D
graphics capabilities, so it has the potential to be used as a games platform, and we very
much hope to see more people starting to write games for it.
INTRODUCTION
We think physical computing—building systems using sensors, motors, lights and microcontrollers—is something that gets overlooked in favour of pure software projects in a lot of
instances, and it’s a shame, because physical computing is massivefun. To the extent that
there was any children’s computing movement when we began this project, it was a physical
computing movement. e LOGO turtles that represented physical computing when we
were kids are now ghting robots, quadcopters or parent-sensing bedroom doors, and we
love it. However, the lack of General Purpose Input/Output (GPIO) on home PCs is a real
handicap for many people getting started with robotics projects. e Raspberry Pi exposes
GPIO so you can get to work straight away.
I keep being surprised by ideas the community comes up with which wouldn’t have crossed
my mind in a thousand years: the Australian school meteor-tracking project; the Boreatton
Scouts in the UK and their robot, which is controlled via an electroencephalography headset
(the world’s rst robot controlled by Scouting brain waves); the family who are building a
robot vacuum cleaner; Manuel, the talking Christmas moose. And I’m a real space cadet, so
reading about the people sending Raspberry Pis into near-earth orbit on rockets and balloons
gives me goosebumps.
9
In the rst edition of this book, I said that success for us would be another 1,000 people
every year taking up Computer Science at the university level in the UK. at would not only
be benecial for the country, the software and hardware industries, and the economy; but it
would be even more benecial for every one of those 1,000 people, who, I hope, discover that
there’s a whole world of possibilities and a great deal of fun to be had out there. We’ve gotten
greedy now: I’d like to see that sort of statistic replicated in many more countries across the
developed world, and to see something similar starting to happen in the developing world.
We’ve been immensely proud to see Raspberry Pi labs spring up in the most unlikely places,
like a village lab in a part of Cameroon with no electricity network where the Pis run o solar
power, generators and batteries, or a school high in the mountains in Bhutan.
Building a robot when you’re a kid can take you to places you never imagined—I know
because it happened to me!
—Eben Upton
10
RASPBERRY PI USER GUIDE, SECOND EDITION
Part I
Connecting the
Board
Chapter 1 Meet the Raspberry Pi
Chapter 2 Getting Started with Raspberry Pi
Chapter 3 Linux System Administration
Chapter 4 Troubleshooting
Chapter 5 Network Conguration
Chapter 6 e Raspberry Pi Software Conguration Tool
Chapter 7 Advanced Raspberry Pi Conguration
Chapter 1
Meet the Raspberry Pi
14
PAR T I CONNECTING THE BOARD
YOUR RASPBERRY PI board is a miniature marvel, packing considerable computing power
into a footprint no larger than a credit card. It’s capable of some amazing feats, but there are
a few things you need to know before you plunge head-rst into the bramble patch.
TIP
Figure 1-1:
e Raspberry Pi
board
If you’re eager to get started, skip to the next chapter to nd out how to connect your
Raspberry Pi to a display, keyboard and mouse, install an operating system, and jump straight
in to using the Pi.
A Trip Around the Board
e Raspberry Pi is currently available as two dierent models, known as the Model A and
the Model B. While there are dierences, with the Model A sacricing some functionality in
order to reduce its cost and power requirements, both share plenty of similarities that you’ll
learn about in this chapter. Figure 1-1 shows a Raspberry Pi Model B.
CHAPTER 1 MEET THE RA SPBERRY PI
In the centre of all Raspberry Pi boards is a square semiconductor, more commonly known as
an integrated circuit or chip. is is the Broadcom BCM2835 system-on-chip (SoC) module,
which provides the Pi with its general-purpose processing, graphics rendering and input/
output capabilities. Stacked on top of that chip is another semiconductor, which provides
the Pi with memory for temporary storage of data while it’s running programs. is type of
memory is known as random access memory (RAM), as the computer can read from or write to
any part of the memory at any time. RAM is volatile, meaning that anything stored in the
memory is lost when the Pi loses power or is switched o.
Above and below the SoC are the Pi’s video outputs. e silver (bottom) connector is a High Denition Multimedia Interface (HDMI) port, the same type of connector found on media players
and many satellite and cable set-top boxes. When connected to a modern TV or monitor, the
HDMI port provides high-resolution video and digital audio. e yellow (top) connector is a com-posite video port, which is designed for connection to older TVs that don’t have an HDMI socket.
e video quality is lower than is available via HDMI, and there’s no audio; instead, audio is provided as an analogue signal on the 3.5mm audio jack to the right of the composite video socket.
15
e pins to the top-left of the Pi compose the general-purpose input-output (GPIO) header,
which can be used to connect the Pi to other hardware. e most common use for this port is
to connect an add-on board. A selection of these is described in Chapter 16, “Add-on Boards”.
e GPIO port is extremely powerful, but it’s fragile; when handling the Pi, always take care
to avoid touching these pins, and never connect anything to them while the Pi is switched
on.
e plastic and metal connector below the GPIO port is the Display Serial Interface (DSI) port,
for connecting digitally driven at-panel display systems. ese are rarely used except by
professional embedded developers, as the HDMI port is more exible. A second plastic and
metal connector, found to the right of the HDMI port, is the Camera Serial Interface (CSI)
port, which provides a high-speed connection to the Raspberry Pi Camera Module or other
Pi-compatible CSI-connected camera system. For more details on the CSI port, see Chapter
15, “e Raspberry Pi Camera Module”.
To the very bottom-left of the board is the Pi’s power socket. is is a micro-USB socket, the
same type found on most modern smartphones and tablets. Connecting a micro-USB cable
to a suitable power adapter, detailed in Chapter 2, “Getting Started with the Raspberry Pi”,
switches the Raspberry Pi on; unlike a desktop or laptop computer, the Pi doesn’t have a
power switch and will start immediately when power is connected.
On the underside of the Raspberry Pi board on the left-hand side is an SD card slot. A Secure
Digital (SD) memory card provides storage for the operating system, programs, data and other
les, and is non-volatile; unlike the volatile RAM, it will retain its information even when power
16
PAR T I CONNECTING THE BOARD
is lost. In Chapter 2, “Getting Started with the Raspberry Pi”, you’ll learn how to prepare an SD
card for use with the Pi, including installing an operating system in a process known as ashing.
e right-hand edge of the Pi will have dierent connectors depending on which model of
Raspberry Pi you have, the Model A or the Model B. Above these is a series of Light Emitting Diodes (LEDs), the top two of which—marked ACT and PWR and providing an activity notication and power notication respectively—are present on all boards.
Model A
e least expensive of the Raspberry Pis, the Model A shown in Figure 1-2 is designed to be
aordable yet exible. As well as its lower cost compared to the Model B, the Model A draws
less power and is a good choice for projects that use solar, wind or battery power. Although the
Model A’s BCM2835 SoC is just as powerful as the one found on the Model B, it comes with
half the memory at 256MB. is is an important consideration when deciding which model to
buy, as it can make more complex applications run slowly—in particular, those applications
that turn the Pi into a server, as described in Chapter 10, “e Pi as a Web Server”.
Figure 1-2:
A Raspberry Pi
Model A
CHAPTER 1 MEET THE RA SPBERRY PI
e Model A has only a single port on its right-hand edge, a Universal Serial Bus (USB) port.
is is the same type of port found on desktop and laptop computers, and allows the Pi to be
connected to almost any USB-compatible peripheral. Most commonly, the USB port is used
to connect a keyboard for interacting with the Pi. If you also want to use a mouse at the same
time, you’ll need to buy a USB hub to add more ports to the Model A, or alternatively, a keyboard with built-in mouse functionality.
Model B
e Raspberry Pi Model B shown in Figure 1-3 is more expensive than the Model A, but
comes with considerable advantages. Internally, it includes twice the memory at 512MB,
while externally there are additional ports not available on the lower-cost model. For many
users, the Model B is a worthwhile investment; only those with particular requirements of
weight, space or power draw should consider the Model A for general-purpose use.
17
Figure 1-3:
A Raspberry Pi
Model B
18
PAR T I CONNECTING THE BOARD
e Model B has two USB ports on the right-hand edge of the board, providing connectivity
for a keyboard and mouse, and still leaving two spare ports for additional accessories such as
external storage devices or hardware interfaces. Additionally, it includes an Ethernet port for
connecting the Pi to a wired network; this allows the Pi to access the Internet, and allows
other devices on the network to access the Pi—providing, that is, they know the username
and password or the Pi has been set up as a server as described in Chapter 10, “e Pi as a
Web Server”.
A History of Model B PCB Revisions
Although the Raspberry Pi Model B currently has 512MB of memory and two USB ports, this
wasn’t always the case. e Model B available today is known as Revision 2, as it is the second
board to be made with the Model B designation. If you have bought a Raspberry Pi Model B
second-hand, or purchased it some time ago, you may have a Revision 1 board, which has a
few dierences.
Revision 1
e original Raspberry Pi Model B, the Revision 1 board has just 256MB of RAM. It also has
a slightly dierent GPIO header, which looks identical to those of later revisions but has
certain features assigned to dierent pins, as explained in Chapter 14, “e GPIO Port”. is
is the most important dierence: all other Raspberry Pi revisions and models share the same
GPIO layout, so if you have an original Model B Revision 1 you may need to adjust instructions and programs before they can be used successfully.
Revision 2
Introduced shortly before the launch of the Model A, the Raspberry Pi Revision 2 includes
double the memory of the original at 512MB. It also introduces the new, standardised GPIO
header shared with the Model A. An extra header, which is also present on Model A boards,
marked P5 and located just below the GPIO header, is a sure sign that a Model B is the newer
Revision 2.
A Bit of Background
Before heading into Chapter 2, “Getting Started with the Raspberry Pi”, it’s a good idea to familiarise yourself with some background details of the Pi and its creation. While the Pi is usable as
a general-purpose computer, capable of performing the same tasks as any desktop, laptop or
server—albeit more slowly—it is designed as a single-board computer aimed at hobbyists and
educational use, and as such diers from a “normal” computer in a couple of important ways.
CHAPTER 1 MEET THE RA SPBERRY PI
ARM versus x86
e processor at the heart of the Raspberry Pi system is the Broadcom BCM2835 SoC multimedia processor. is means that the vast majority of the system’s components, including
its central and graphics processing units along with the audio and communications hardware, are built onto that single component hidden beneath the memory chip at the centre of
the board.
It’s not just this SoC design that makes the BCM2835 dierent to the processor found in
your desktop or laptop, however. It also uses a dierent instruction set architecture (ISA),
known as ARM.
Developed by Acorn Computers back in the late 1980s, the ARM architecture is a relatively
uncommon sight in the desktop world. Where it excels, however, is in mobile devices: the
phone in your pocket almost certainly has at least one ARM-based processing core hidden
away inside. Its combination of a simple reduced instruction set computing (RISC) architecture
and low power draw make it the perfect choice over desktop chips with high power demands
and complex instruction set computing (CISC) architectures.
19
e ARM-based BCM2835 is the secret of how the Raspberry Pi is able to operate on just the
5V 1A power supply provided via the onboard micro-USB port. It’s also the reason why you
won’t nd any metal heat sinks on the device: the chip’s low power draw directly translates
into very little waste heat, even during complicated processing tasks.
It does mean, however, that the Raspberry Pi isn’t compatible with traditional PC software.
e majority of software for desktops and laptops is built with the x86 instruction set architecture in mind, as found in processors from the likes of AMD, Intel and VIA. As a result, it
won’t run on the ARM-based Raspberry Pi.
e BCM2835 uses a generation of ARM’s processor design known as ARM11, which in turn
is designed around a version of the instruction set architecture known as ARMv6. is is
worth remembering: ARMv6 is a lightweight and powerful architecture, but has a rival in the
more advanced ARMv7 architecture used by the ARM Cortex family of processors. Software
developed for ARMv7, like software developed for x86, is sadly not compatible with the
Raspberry Pi’s BCM2835—although developers can usually convert the software to make it
suitable, a process known as porting.
at’s not to say you’re going to be restricted in your choices. As you’ll discover later in the
book, there is plenty of software available for the ARMv6 instruction set and, as the Raspberry
Pi’s popularity continues to grow, that will only increase. In this book, you’ll also learn how to
create your own software for the Pi even if you have no experience with programming.
20
PAR T I CONNECTING THE BOARD
Windows versus Linux
Another important dierence between the Raspberry Pi and your desktop or laptop, other
than the size and price, is the operating system—the software that allows you to control the
computer.
e majority of desktop and laptop computers available today run one of two operating systems:
Microsoft Windows or Apple OS X. Both platforms are closed source, created in a secretive
environment using proprietary techniques.
ese operating systems are known as closed source because of the nature of their source code,
the computer-language recipe that tells the system what to do. In closed-source software, this
recipe is kept a closely guarded secret. Users are able to obtain the nished software, but never
to see how it’s made.
e Raspberry Pi, by contrast, is designed to run an operating system called GNU/Linux—
hereafter referred to simply as Linux. Unlike Windows or OS X, Linux is open source: it’s possible to download the source code for the entire operating system and make whatever
changes you desire. Nothing is hidden, and all changes are made in full view of the public.
is open source development ethos has allowed Linux to be altered quickly to run on the
Raspberry Pi. At the time of this writing, several versions of Linux—known as distributions—
have been ported to the Raspberry Pi’s BCM2835 chip, including Raspbian, Pidora and Arch
Linux.
e dierent distributions cater to dierent needs, but they all have something in common:
they’re all open source. ey’re also all, by and large, compatible with each other: software
written on a Debian system will usually operate perfectly well on Arch Linux, and vice versa.
Linux isn’t exclusive to the Raspberry Pi. Hundreds of dierent distributions are available for
desktops, laptops and even mobile devices; even Google’s popular Android platform is developed on top of a Linux core. If you nd that you enjoy the experience of using Linux on the
Raspberry Pi, you could consider adding it to other computing devices you use as well. It will
happily coexist with your current operating system, allowing you to enjoy the benets of
both while giving you a familiar environment when your Pi is unavailable.
As with the dierence between ARM and x86, there’s a key point to make about the practical
dierence between Windows and OS X and Linux: software written specically for Windows
or OS X won’t run on Linux. ankfully, there are plenty of compatible alternatives for the
overwhelming majority of common software products—better still, the majority are free to
use and as open source as the operating system itself, and can even be installed on both
Windows and OS X to provide a familiar experience across all three platforms.
Chapter 2
Getting Started with
the Raspberry Pi
22
PAR T I CONNECTING THE BOARD
NOW THAT YOU
computing devices, it’s time to get started. If you’ve just received your Pi, take it out of its
protective anti-static bag and place it on a at, non-conductive surface before continuing
with this chapter.
To use your Pi, you’ll need some extra peripherals. A display will allow you to see what you’re
doing, while a keyboard and mouse will be your input devices. In this chapter, you’ll learn
how to connect these to the Pi, along with a network connection in the case of the Model B.
You’ll also learn how to download and install an operating system for the Pi.
have a basic understanding of how the Raspberry Pi diers from other
Your Mileage May Vary
The information and instructions in this book give you all you need to get your Raspberry Pi
up and running and to make the most of its capabilities. Be aware that some of the software
for the Raspberry Pi is evolving so quickly that what you see on your screen may differ
slightly from some of the images in the book, as new features and options become
available.
Connecting a Display
Before you can start using your Raspberry Pi, you’re going to need to connect a display. e
Pi supports three dierent video outputs: composite video, HDMI video and DSI video.
Composite video and HDMI video are readily accessible to the end user, as described in this
section, while DSI video requires some specialised hardware.
Composite Video
Composite video, available via the yellow-and-silver port at the top of the Pi known as an
RCA phonoconnector (see Figure 2-1), is designed for connecting the Raspberry Pi to older
display devices. As the name suggests, the connector creates a composite of the colours
found within an image—red, green and blue—and sends it down a single wire to the display
device, typically an old cathode-ray tube (CRT) TV.
When no other display device is available, a composite video connection will get you started
with the Pi. e quality isn’t great, however. Composite video connections are signicantly
more prone to interference, lack clarity and run at a limited resolution, meaning that you can
t fewer icons and lines of text on the screen at once.
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
23
Figure 2-1:
e yellow RCA
phono
connector, for
composite video
output
HDMI Video
A better quality picture can be obtained using the High Denition Multimedia Interface (HDMI)
connector, the only port found on the bottom of the Pi (see Figure 2-2). Unlike the analogue
composite connection, the HDMI port provides a high-speed digital connection for pixelperfect pictures on both computer monitors and high-denition TV sets. Using the HDMI
port, a Pi can display images at the Full HD 1920x1080 resolution of most modern HDTV
sets. At this resolution, signicantly more detail is available on the screen.
If you’re hoping to use the Pi with an existing computer monitor, you may nd that your
display doesn’t have an HDMI input. at’s not a disaster: the digital signals present on the
HDMI cable map to a common computer monitor standard called Digital Video Interconnect (DVI). By purchasing an HDMI-to-DVI cable, you’ll be able to connect the Pi’s HDMI port to
a monitor with DVI-D connectivity.
If your monitor has a VGA input—a D-shaped connector with 15 pins, typically coloured
silver and blue—the Raspberry Pi can’t connect to it directly. To use this type of monitor,
you will need to purchase what is known as an adapter dongle; look for models that convert
HDMI to VGA and specically mention Raspberry Pi compatibility when making a purchase,
and simply connect the HDMI end to the Pi and your VGA monitor cable to the other end of
the dongle.
24
PAR T I CONNECTING THE BOARD
Figure 2-2:
e silver HDMI
connector, for
high-denition
video output
DSI Video
e nal video output on the Pi can be found above the SD card slot on the top of the printed
circuit board—it’s a small ribbon connector protected by a layer of plastic. is is for a video
standard known as Display Serial Interface (DSI), which is used in the at-panel displays of
tablets and smartphones. Displays with a DSI connector are rarely available for retail purchase, and are typically reserved for engineers looking to create a compact, self-contained
system. A DSI display can be connected by inserting a ribbon cable into the matched connector on the Pi, but for beginners, the use of a composite or HDMI display is recommended.
Connecting Audio
If you’re using the Raspberry Pi’s HDMI port, audio is simple: when properly congured, the
HDMI port carries both the video signal and a digital audio signal. is means that you can
connect a single cable to your display device to enjoy both sound and pictures.
Assuming you’re connecting the Pi to a standard HDMI display, there’s very little to do at
this point. For now, it’s enough simply to connect the cable.
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
25
If you’re using the Pi with a DVI-D monitor via an adapter or cable, audio will not be included.
is highlights the main dierence between HDMI and DVI: while HDMI can carry audio
signals, DVI cannot and is instead used exclusively for video signals.
For those with DVI-D monitors, or those using the composite video output, a black 3.5 mm audio jack located on the top edge of the Pi next to the yellow phono connector provides analogue audio (see Figure 2-1). is is the same connector used for headphones and microphones on consumer audio equipment, and it’s wired in exactly the same way. If you want,
you can simply connect a pair of headphones to this port for quick access to audio.
TIP
While headphones can be connected directly to the Raspberry Pi, you may nd the volume a little
lacking. If possible, connect a pair of powered speakers instead. The amplier inside will help boost
the signal to a more audible level, while many will also provide a physical volume control.
If you’re looking for something more permanent, you can either use standard PC speakers
that have a 3.5 mm connector or buy some adapter cables. For composite video users, a 3.5 mm to RCA phono cable is useful. is provides the two white-and-red RCA phono connections that sit alongside the video connection, each carrying a channel of the stereo audio
signal to the TV.
For those connecting the Pi to an amplier or stereo system, you’ll either need a 3.5 mm to
RCA phono cable or a 3.5 mm to 3.5 mm cable, depending on what spare connections you
have on your system. Both cable types are readily and cheaply available at consumer electronics shops, or can be purchased even cheaper from online retailers such as Amazon.
Connecting a Keyboard and Mouse
Now that you’ve got your Raspberry Pi’s output devices sorted, it’s time to think about input.
At a bare minimum, you’re going to need a keyboard, and for the majority of users, a mouse
or trackball is a necessity too.
First, some bad news: if you’ve got a keyboard and mouse with a PS/2 connector—a round
plug with a horseshoe-shaped array of pins—then you’re going to have to go out and buy a
replacement. e old PS/2 connection has been superseded, and the Pi expects your peripherals to be connected over the Universal Serial Bus (USB) port. An alternative is to buy a USB to PS/2 adapter, although be aware that some particularly old keyboards may not operate
correctly through such an adapter.
Depending on whether you purchased the Model A or Model B, you’ll have either one or two
USB ports available on the right side of the Pi (see Figure 2-3). If you’re using a Model B, you
26
PAR T I CONNECTING THE BOARD
can connect the keyboard and mouse directly to these ports. If you’re using a Model A, you’ll
need to purchase an external USB hub in order to connect two USB devices simultaneously.
Figure 2-3:
e Raspberry Pi
Model B’s two
USB ports
TIP
A USB hub is a good investment for any Pi user: even if you’ve got a Model B, you’ll use up
both your available ports just connecting your keyboard and mouse, leaving nothing free for
additional devices such as an external optical drive, storage device or joystick. Make sure you
buy a powered USB hub: passive models are cheaper and smaller, but lack the ability to run
current-hungry devices like CD drives and external hard drives.
If you want to reduce the number of power sockets in use, connect the Raspberry Pi’s USB
power lead to your powered USB hub. This way, the Pi can draw its power directly from the hub,
rather than needing its own dedicated power socket and mains adapter. This will only work on
hubs with a power supply capable of providing 700mA to the Pi’s USB port—more than will be
available on cheaper hub models—along with whatever power is required by other peripherals.
Connecting the keyboard and mouse is as simple as plugging them into the USB ports, either
directly in the case of a Model B or via a USB hub in the case of a Model A.
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
A Note on Storage
As you’ve probably noticed, the Raspberry Pi doesn’t have a traditional hard drive. Instead, it
uses a Secure Digital (SD) memory card, a solid-state storage system typically used in digital
cameras. Almost any SD card will work with the Raspberry Pi, but because it holds the entire
operating system, you need a card with at least 4 GB in capacity to store all the required les.
SD cards with the operating system preloaded are available from the ofcial Raspberry Pi
Store as well as with numerous other sites on the Internet. If you’ve purchased one of
these, or received it in a bundle with your Pi, you can simply plug it into the SD card slot on
the bottom side of the left-hand edge.
Some SD cards work better than others, with some models refusing to work at all with the
Raspberry Pi. For an up-to-date list of SD card models known to work with the Pi, visit the
eLinux Wiki page at http://www.elinux.org/RPi_SD_cards.
27
Installing NOOBS on an SD Card
e Raspberry Pi Foundation supplies a software tool for the Pi known as New Out-Of-Box
Software, or NOOBS. is tool, is intended to make it as easy as possible to get started with
using the Pi, and is available pre-installed on SD cards bundled with Raspberry Pi boards as
well as separately and as a free download. It provides a selection of dierent operating systems for installation on the Pi, along with tools for changing its conguration.
If you have purchased an SD card with NOOBS already installed on it, you need do nothing
at this stage. If not, download the latest version of the NOOBS software from the Raspberry
Pi Foundation at www.raspberrypi.org/downloads. Note that this is a large le, and
can take some considerable time to download; if you are on a capped Internet connection of
around 1 GB a month, you will be unable to download the le. In this case, invest in an SD
card with NOOBS preloaded from any Raspberry Pi-carrying retailer.
To use NOOBS, you’ll need an SD card of at least 4 GB capacity, and preferably at least 8 GB to
give you room to install additional software as you use the Pi. You’ll also need an existing computer with an SD card reader, either built-in as with some models of laptop or an add-on device.
To begin, insert the SD card into the card reader. If you have previously used your SD card with
another device, such as a digital camera or games console, follow the link on the Raspberry Pi
Downloads page to the SD Card Association’s formatting tool and use this to format the SD
card, preparing it for the installation. If the card is new, you can safely skip this step.
e NOOBS software is provided as a Zip archive. is is a le format where the data is compressed,
so that it takes up less space and is quicker to download. Double-clicking on the le should be
28
PAR T I CONNECTING THE BOARD
enough to open it on most operating systems; if not, download an archive utility like 7Zip
(www.7-zip.org) and try again.
When you have opened the le, use your archive software’s extract or copy function to transfer
the les from within the archive to your SD card (see Figure 2-4). is can take some time to
complete, thanks to the number and size of the les involved. Be patient, and when the extraction has nished and the activity light—if applicable—has gone o, use your operating system’s Eject option to remove the SD card, and then insert the card into the Pi’s SD card slot.
Figure 2-4:
Extracting
NOOBS to the
SD card
Connecting External Storage
While the Raspberry Pi uses an SD card for its main storage device—known as a boot
device—you may nd that you run into space limitations quite quickly. Although large SD
cards holding 32 GB, 64 GB or more are available, they are often prohibitively expensive.
ankfully, there are devices that provide an additional hard drive capacity to any computer when
connected via a USB cable. Known as USB Mass Storage (UMS) devices, these can be physical hard
drives, solid-state drives (SSDs) or even portable pocket-sized ash drives (see Figure 2-5).
e majority of USB Mass Storage devices can be read by the Pi, whether or not they have
existing content. In order for the Pi to be able to access these devices, their drives must be
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
mounted—a process you will learn in Chapter 3, “Linux System Administration”. For now,
it’s enough to connect the drives to the Pi in readiness.
29
Figure 2-5:
Two USB Mass
Storage devices:
a pen drive and
an external hard
drive
Connecting the Network
While the majority of these setup instructions are equally applicable to both the Raspberry Pi
Model A and the Model B, networking is a special exception. To keep the component count—
and therefore the cost—as low as possible, the Model A doesn’t feature any onboard networking. ankfully, that doesn’t mean you can’t network the Model A, only that you’ll need
some additional equipment to do so.
Networking the Model A
To give the Model A the same networking capabilities as its more expensive Model B counterpart, you’ll need a USB-connected Ethernet adapter. This connects to a free USB port on
the Raspberry Pi or a connected hub, and provides a wired Ethernet connection with an
RJ45 connector, the same as is available on the Model B.
A 10/100 USB Ethernet adapter—with the numbers referring to its two-speed mode, 10 Mb/s and
100 Mb/s—can be purchased from online retailers for very little money. When buying an Ethernet
adapter, be sure to check that Linux is listed as a supported operating system. There are a few
models that only work with Microsoft Windows and are incompatible with the Raspberry Pi.
Don’t be tempted to go for a gigabit-class adapter, which may be referred to as a 10/100/1000
USB Ethernet adapter. Standard USB ports, as used on the Raspberry Pi, can’t cope with the
speed of a gigabit Ethernet connection, and you’ll see no benet from the more expensive
adapter.
30
PAR T I CONNECTING THE BOARD
Wired Networking
To get your Raspberry Pi on the network, you’ll need to connect an RJ45 Ethernet patch cable
between the Pi and a switch, router or hub. If you don’t have a router or hub, you can get
your desktop or laptop talking to the Pi by connecting the two directly together with a patch
cable.
Usually, connecting two network clients together in this way requires a special cable, known
as a crossover cable. In a crossover cable, the receive and transmit pairs are swapped so that
the two devices are prevented from talking over each other—a task usually handled by a
network switch or hub.
e Raspberry Pi is cleverer than that, however. e RJ45 port on the side of the Pi (see
Figure 2-6) includes a feature known as auto-MDI, which allows it to recongure itself automatically. As a result, you can use any RJ45 cable—crossover or not—to connect the Pi to
the network, and it will adjust its conguration accordingly.
Figure 2-6:
e Raspberry Pi
Model B’s
Ethernet port
TIP
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
31
If you do connect the Pi directly to a PC or laptop, you won’t be able to connect out onto the
Internet by default. To do so, you’ll need to congure your PC to bridge the wired Ethernet
port and another (typically wireless) connection. Doing so is outside the scope of this book,
but if you are completely unable to connect the Pi to the Internet in any other way, you can
try searching your operating system’s help le for “bridge network” to nd more guidance.
With a cable connected, the Pi will automatically receive the details it needs to access the
Internet when it loads its operating system through the Dynamic Host Conguration Protocol (DHCP). is assigns the Pi an Internet Protocol (IP) address on your network, and tells it the
gateway it needs to use to access the Internet (typically the IP address of your router or
modem).
For some networks, there is no DHCP server to provide the Pi with an IP address. When connected to such a network, the Pi will need manual conguration. You’ll learn more about this
in Chapter 5, “Network Conguration”.
Wireless Networking
Current Raspberry Pi models don’t feature any form of wireless network capability onboard,
but—as with adding wired Ethernet to the Model A—it’s possible to add Wi-Fi support to
any Pi using a USB wireless adapter (see Figure 2-7).
Figure 2-7:
Two USB
wireless
adapters,
suitable for use
with the
Raspberry Pi
32
PAR T I CONNECTING THE BOARD
Using such a device, the Pi can connect to a wide range of wireless networks, including those
running on the latest 802.11n high-speed standard. Before purchasing a USB wireless
adapter, check the following:
❍ Ensure that Linux is listed as a supported operating system. Some wireless adapters
are provided with drivers for Windows and OS X only, making them incompatible with
the Raspberry Pi. A list of Wi-Fi adapters known to work with the Raspberry Pi can be
found on the following website: http://elinux.org/RPi_USB_Wi-Fi_
Adapters
❍ Ensure that your Wi-Fi network type is supported by the USB wireless adapter. e
network type will be listed in the specications as a number followed by a letter. If your
network type is 802.11a, for example, an 802.11g wireless adapter won’t work.
❍ Check the frequencies supported by the card. Some wireless network standards, like
802.11a, support more than one frequency. If a USB wireless adapter is designed to
work on a 2.4GHz network, it won’t connect to a 5GHz network.
.
❍ Check the encryption type used by your wireless network. Most modern USB wireless
adapters support all forms of encryption, but if you’re buying a second-hand or older
model, you may nd it won’t connect to your network. Common encryption types
include the outdated WEP and more modern WPA and WPA2.
Conguration of the wireless connection is done within Linux, so for now it’s enough simply
to connect the adapter to the Pi (ideally through a powered USB hub). You’ll learn how to
congure the connection in Chapter 5, “Network Conguration”.
Connecting Power
e Raspberry Pi is powered by the small micro-USBconnector found on the lower left side of
the circuit board. is connector is the same as is found on the majority of smartphones and
many tablet devices.
Many chargers designed for smartphones will work with the Raspberry Pi, but not all. e Pi
is more power-hungry than most micro-USB devices, and requires up to 700 mA of current
in order to operate. Some chargers can only supply up to 500 mA, causing intermittent problems in the Pi’s operation (see Chapter 4, “Troubleshooting”).
Connecting the Pi to the USB port on a desktop or laptop computer is possible, but not recommended. As with smaller chargers, the USB ports on a computer can’t provide the power
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
required for the Pi to work properly. Connect the micro-USB power supply only when you are
ready to start using the Pi. With no power button on the device, it will start working the
instant power is connected.
To safely turn the Raspberry Pi o, issue a shutdown command at the console or terminal by
typing:
sudo shutdown -h now
For more information on using the terminal, see Chapter 3, “Linux System Administration”.
If you have prepared or purchased your SD card with the NOOBS tool, as described earlier in this
chapter, the Pi will load this tool and wait for your instructions; if not, powering the Pi on with a
blank SD card will result in a blank screen or a coloured test pattern. In this case, switch o the
power and remove the SD card before following the manual installation instructions from the
following section, “Installing the Operating System”.
33
Installing the Operating System
If you purchased your Raspberry Pi with a bundled SD card featuring a preloaded operating
system, or followed the instructions for installing NOOBS earlier in this chapter, you can
simply insert the card into the SD card slot on the underside of the Pi. If you bought the Pi by
itself, you will need to install an operating system on the SD card before the Pi is ready
to use.
Installing Using NOOBS
If you have installed NOOBS on your SD card, or purchased an SD card with NOOBS preinstalled, powering on the Raspberry Pi will display a menu (see Figure 2-8). is menu provides a list of operating systems suitable for the Pi, any one (or more) of which can be
installed. You can also choose to change the interface language by clicking the arrow next to
Language at the bottom of the screen, or choose a dierent keyboard layout using the arrow
next to Keyboard.
If this is your rst time running NOOBS on that SD card, there will be a delay while the SD
card’s partition is resized to make room for your chosen operating system; do not unplug the
Pi’s power while this is in progress, as you will risk damaging your SD card.
34
PAR T I CONNECTING THE BOARD
Figure 2-8:
e NOOBS
operating
system menu
TIP
If you see only a blank screen, but the Pi’s ACT and PWR lights are on, you may need to choose a
different display mode. Press 1 on the keyboard for standard HDMI mode, 2 for a ‘safe’ mode with
a lower resolution, 3 if you are using the composite port in a PAL region or 4 if you are using the
composite port in an NTSC region. If you’re not sure which is suitable, try all the options until you
nd one that works for you. The chosen display mode will also be passed to the installed operating
system automatically.
Using the keyboard or mouse, browse through the list of operating systems and click on the
box by its name to mark it for installation. Note that you can install multiple operating systems if your SD card is large enough: simply tick two or more operating systems from the list.
For beginners, we recommend the Raspbian operating system. e remainder of this book
will be written with Raspbian in mind, but much of what you’ll learn is applicable to almost
any Linux-based operating system both on the Pi and on other devices.
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
To begin the installation process, click the Install icon at the top-left of the menu and, when
asked, conrm that the SD card can be overwritten when asked. As with installing NOOBS
itself, this process can take a long time to complete; be patient, watch the progress bar and
slideshow (see Figure 2-9) and don’t remove the power cable or SD card from the Pi until it is
nished. When the operating system is installed, click the OK button to reboot and load your
chosen operating system.
35
Figure 2-9:
Installing an
operating
system via
NOOBS
If you have installed more than one operating system, NOOBS will bring up a menu asking
which one to boot: if you don’t make a choice, the last operating system chosen—or the rst
in the list, if you haven’t booted into an OS before—will automatically boot after 10 seconds.
For more information on using NOOBS after the operating system is installed, to either
install a dierent operating system or to change the Pi’s various settings, see Chapter 7,
“Advanced Raspberry Pi Conguration”.
Installing Manually
Installing an operating system manually is a more complicated procedure than using the
NOOBS tool, but is sometimes preferable. By installing the software manually—a process
known as ashing—you can choose to install operating systems that aren’t available through
NOOBS or newer versions that the tool doesn’t yet have available.
To prepare a blank SD card for use with the Raspberry Pi, you’ll need to ash an operating
system onto the card, using your desktop or laptop computer. While this is slightly more
complicated than simply dragging and dropping les onto the card, it shouldn’t take more
than a few minutes to complete.
36
PAR T I CONNECTING THE BOARD
First, you’ll need to decide which Linux distribution you would like to use with your Raspberry
Pi. Each has its advantages and disadvantages. Don’t worry if you change your mind later
and want to try a dierent version of Linux: an SD card can be ashed again with a new operating system at any point, and if you choose you can have multiple cards each with a dierent operating system installed.
e most up-to-date list of Linux releases compatible with the Pi is available from the
Raspberry Pi website at http://www.raspberrypi.org/downloads.
e Foundation provides BitTorrent links for each distribution. ese are small les that can
be used with BitTorrent software to download the les from other users. Using these links is
an ecient and fast way to distribute large les, and keeps the Foundation’s download servers from becoming overloaded.
To use a BitTorrent link, you’ll need to have a compatible client installed. If you don’t already have
a BitTorrent client installed, download one and install it before trying to download the Raspberry
Pi Linux distribution. One client for Windows, OS X and Linux is µTorrent, available from
http://www.utorrent.com/downloads.
WARNING
Which distribution you choose to download is up to you. Instructions in the rest of the book will
be based on the Raspbian Raspberry Pi distribution, a good choice for beginners. Where possible,
we’ll give you instructions for other distributions as well.
Linux distributions for the Raspberry Pi are provided as a single image le, compressed to make it
faster to download. Once you’ve downloaded the Zip archive (a compressed le, which takes less
time to download than the uncompressed les would) for your chosen distribution, you’ll need to
decompress it somewhere on your system. In most operating systems, you can simply doubleclick the le to open it, and then choose Extract or Unzip to retrieve the contents.
After you’ve decompressed the archive, you’ll end up with two separate les. e le ending in
sha1 is a hash, which can be used to verify that the download hasn’t been corrupted in transit.
e le ending in img contains an exact copy of an SD card set up by the distribution’s creators in
a way that the Raspberry Pi understands. is is the le that needs to be ashed to the SD card.
In the following instructions, you’ll be using a software utility called dd. Used incorrectly, dd
will happily write the image to your main hard drive, erasing your operating system and all
your stored data. Make sure you read the instructions in each section thoroughly and note the
device address of your SD card carefully. Read twice, write once!
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
Flashing from Linux
If your current PC is running a variant of Linux already, you can use the dd command to write the
contents of the image le out to the SD card. is is a text-interface program operated from the
command prompt, known as a terminal in Linux parlance. Follow these steps to ash the SD card:
1. Open a terminal from your distribution’s applications menu.
2. Plug your blank SD card into a card reader connected to the PC.
3. Type sudo fdisk -l to see a list of disks. Find the SD card by its size, and note the
device address: /dev/sdX, where X is a letter identifying the storage device. Some
systems with integrated SD card readers may use the alternative format /dev/
mmcblkX—if this is the case, remember to change the target in the following instruc-
tions accordingly.
4. Use cd to change to the directory with the .img le you extracted from the Zip archive.
5. Type sudo dd if=imagefilename.img of=/dev/sdX bs=2M to write the le
imagefilename.img to the SD card connected to the device address from step 3.
Replace imagefilename.img with the actual name of the le extracted from the Zip
archive. is step takes a while, so be patient! During ashing, nothing will be shown
on the screen until the process is fully complete (see Figure 2-10).
37
Figure 2-10:
Flashing the SD
card using the
dd command
in Linux
38
PAR T I CONNECTING THE BOARD
Flashing from OS X
If your current computer is a Mac running Apple OS X, you’ll be pleased to hear that things are
just as simple as with Linux. anks to a similar ancestry, OS X and Linux both contain the dd
utility, which you can use to ash the system image to your blank SD card as follows:
1. Select Utilities from the Application menu, and then click on the Terminal application.
2. Plug your blank SD card into a card reader connected to the Mac.
3. Type diskutil list to see a list of disks. Find the SD card by its size, and note the
device address (/dev/diskX, where X is a letter identifying the storage device).
4. If the SD card has been automatically mounted and is displayed on the desktop, type
diskutil unmountdisk /dev/diskX to unmount it before proceeding.
5. Use cd to change to the directory with the .img le you extracted from the Zip archive.
6. Type dd if=imagefilename.img of=/dev/diskX bs=2m to write the le
imagefilename.img to the SD card connected to the device address from step 3.
Replace imagefilename.img with the actual name of the le extracted from the Zip
archive. is step takes a while, so be patient!
Flashing from Windows
If your current PC is running Windows, things are slightly trickier than with Linux or OS X.
Windows does not have a utility like dd, so some third-party software is required to get the image
le ashed onto the SD card. Although it’s possible to install a Windows-compatible version of
dd, there is an easier way: the Image Writer for Windows. Designed specically for creating USB
or SD card images of Linux distributions, this features a simple graphical user interface that
makes the creation of a Raspberry Pi SD card straightforward.
e latest version of Image Writer for Windows can be found at the ocial website:
https://sourceforge.net/projects/win32diskimager/. Follow these steps to
download, install and use the Image Writer for Windows software to prepare the SD card for
the Pi:
1. Click the green Download button to download the Image Writer for Windows Zip le,
and extract it to a folder on your computer.
2. Plug your blank SD card into a card reader connected to the PC.
3. Double-click the Win32DiskImager.exe le to open the program, and click the blue
folder icon to open a le browse dialogue box.
CHAPTER 2 GETTING STARTED WITH THE RASPBERRY PI
39
4. Browse to the imagefilename.img le you extracted from the distribution archive,
replacing imagefilename.img with the actual name of the le extracted from the Zip
archive, and then click the Open button.
5. Select the drive letter corresponding to the SD card from the Device drop-down dialogue
box. If you’re unsure which drive letter to choose, open My Computer or Windows Explorer
to check.
6. Click the Write button to ash the image le to the SD card. is process takes a while,
so be patient!
WARNING
No matter which operating system you’re writing from, it’s important to ensure you leave the
SD card connected until the image has been completely written. If you don’t, you may nd
that Pi doesn’t boot when the SD card is connected. If this happens, start the process again.
When the image has been ashed onto the SD card, remove it from the computer and insert it
into the Raspberry Pi’s SD card slot, located underneath the circuit board. The SD card should
be inserted with the label facing away from the board and pushed fully home to ensure a good
connection.
Chapter 3
Linux System Administration
42
PAR T I CONNECTING THE BOARD
THE MAJORITY OF
interface (GUI) that provides an easy way to perform common tasks. It is, however, quite different to both Windows and OS X, so if you’re going to get the most out of your Raspberry Pi,
you’ll need a quick primer in using the operating system.
modern Linux distributions are user-friendly, with a graphical user
Linux: An Overview
As briey explained in Chapter 1, “Meet the Raspberry Pi”, Linux is an open source project
that was originally founded to produce a kernel that would be free for anyone to use. e
kernel is the heart of an operating system, and handles the communication between the user
and the hardware.
Although only the kernel itself is rightly called Linux, the term is often used to refer to a collection of dierent open source projects from a variety of companies. ese collections come
together to form dierent avours of Linux, known as distributions.
e original version of Linux was combined with a collection of tools created by a group
called GNU. e resulting system, known as GNU/Linux, was basic but powerful. Unlike
many mainstream operating systems of the era, it oered facilities like multiple user accounts
where several users can share a single computer. at’s something rival closed-source operating systems have taken on board, with both Windows and OS X now supporting multiple
user accounts on the same system. It’s also still present in Linux, and provides security and
protection for the operating system.
In Linux, you’ll spend most of your time running a restricted user account. is doesn’t mean
you’re being limited in what you can do; instead, it prevents you from accidentally doing
something that will break the software on your Raspberry Pi. It also prevents viruses and
other malware from infecting the system by locking down access to critical system les and
directories.
Before you can get started, it’s worth becoming familiar with some of the terms and concepts
used in the world of Linux, as dened in Table 3-1. Even if you’re experienced with other
operating systems, it’s a good idea to review this table before booting up your Pi for the rst
time.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
Table 3-1 The Quick Linux Glossary
Term/ConceptDenition
Bashe most popular shell choice, used in the majority of Linux distributions.
BootloaderSoftware responsible for loading the Linux kernel. e most common is GRUB.
ConsoleA version of the terminal that is always available, and the rst thing you see on
the Pi.
Desktop
environment
Directorye Linux term for what Windows calls folders, where les are stored.
DistributionA particular version of Linux. Pidora, Arch and Raspbian are distributions.
ExecutableA le that can be run as a program. Linux les must be marked executable in
EXT2/3/4e EXTended le system, the most common le system used in Linux.
File systeme way a hard drive or other storage device is formatted so it’s ready for le
GNOMEOne of the most common Linux desktop environments.
GNUA free software project, which provides many of the tools used in Linux distri-
GRUBe GRand Unied Bootloader, created by GNU and used to load the Linux
GUIA graphical user interface, in which the user operates the computer via a
KDEAnother extremely popular Linux desktop environment.
LinuxProperly, the kernel used by GNU/Linux. Popularly, an open source operating
Live CDA Linux distribution provided as a CD or DVD, which doesn’t require installation.
PackageA collection of les required to run an application, typically handled by the
Package managerA tool for keeping track of, and installing new, software.
PartitionA section of a hard drive that is ready to have a le system applied to it for
Roote main user account in Linux, equivalent to the Windows administrator
ShellA text-based command prompt, loaded in a terminal.
sudoA program that allows restricted users to run a command as the root user.
SuperuserSee Root.
TerminalA text-based command prompt in which the user interacts with a shell program.
X11e X Window system, a package that provides a graphical user interface (GUI).
Software to make the GUI look pretty. GNOME and KDE are popular desktop
environments.
order to run.
storage.
butions.
kernel.
mouse or touch.
system.
package manager.
storage.
account. Also called the superuser.
43
44
PAR T I CONNECTING THE BOARD
The Terminal and the GUI
As in OS X and Windows, there are typically two main ways to achieve a given goal in Linux:
through the graphical user interface (GUI) and through the command line (known in Linux
parlance as the console or the terminal).
The appearance of various Linux distributions can be quite different, depending on the desktop environment in use. In this book, the recommended Raspbian distribution is used, but
most of the commands you will be learning are entered at the terminal and are typically the
same across all distributions.
Where other distributions differ, you will be given alternative methods of achieving the
same goals.
Linux Basics
Although there are hundreds of dierent Linux distributions available, they all share a common set of tools known as commands. ese tools, which are operated via the terminal, are
analogous to similar tools on Windows and OS X. To get started, you’ll need to learn the following commands:
❍ ls—Short for listing, ls provides a list of the contents of the current directory.
Alternatively, it can be called with the directory to be listed as an argument. As an
example, typing ls /home will provide a list of the contents of /home, regardless of
your current directory. e Windows equivalent is dir.
❍ cd—An initialism of change directory, cd allows you to navigate your way through the
le system. Typing cd on its own puts you back in your home directory. Typing the
command along with the name of the directory you wish to move to, by contrast,
switches to that directory. Note that directories can be absolute or relative: cd boot
will move you to the directory called boot under your current directory, but cd /
boot will move you straight to the /boot directory wherever you are.
❍ mv—e move command has two purposes in Linux: it allows a le to be moved from
one directory to another, and it also allows les to be renamed. at latter feature may
seem out of place, but in Linux terms, the le is being moved from one name to
another. e command is called as mv oldfile newfile.
❍ rm—Short for remove, rm deletes les. Any le—or list of les—provided after the
command name will be deleted. e Windows equivalent is del, and the two share a
common requirement that care should be taken to ensure the right le is deleted.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
45
❍ rmdir—By itself, rm cannot usually remove directories. As a result, rmdir is provided
to delete directories once they have been emptied of les by rm.
❍ mkdir—e opposite of rmdir, the mkdir command creates new directories. For
example, typing mkdir myfolder at the terminal will create a new directory called
myfolder under the current working directory. As with cd, directories provided to
the command can be relative or absolute.
Introducing Raspbian
Raspbian is the name given to a customised variant of the popular Debian Linux distribution. Debian is one of the longest-running Linux distributions, and concentrates on high
compatibility and excellent performance even on modest hardware—making it a great partner for the Raspberry Pi. Raspbian takes Debian as its base, or parent distribution, and adds
custom tools and software to make using the Raspberry Pi as easy as possible.
To keep the download size to a minimum, the Raspberry Pi image for Raspbian includes only
a subset of the software you’d nd on a regular desktop version. is includes tools for
browsing the web, programming in Python and using the Pi with a GUI. Additional software
can be quickly installed through the use of the distribution’s package manager, apt, or purchased through the Raspberry Pi Store link on the desktop. Raspbian includes a desktop
environment known as the Lightweight X11 Desktop Environment (LXDE). Designed to oer
an attractive user interface using the X Window System software, LXDE provides a familiar
point-and-click interface that will be immediately accessible to anyone who has used
Windows, OS X or other GUI-based operating systems in the past.
TIP
The GUI doesn’t load by default in most Raspberry Pi distributions, and Raspbian is no
exception. To quickly load it and leave the text-based console behind, log in, type startx
and then press the Enter key. To return to the console, while leaving the GUI running in the
background, hold down Ctrl + Alt and press F1 before releasing all three keys.
If you’re using the recommended Raspbian distribution, you’ll nd that you have plenty of
preinstalled software to get started. While hardly an exhaustive example of the software
available for the Pi, which numbers in the thousands of packages, it’s a good introduction to
precisely what the system can do.
e software provided with the Raspbian distribution is split into themed categories. To view
these categories, left-click the menu icon, the arrow located on the bottom-left of the screen
in LXDE (see Figure 3-1).
46
PAR T I CONNECTING THE BOARD
F -:
e LXDE
desktop, as
loaded on the
Raspbian
distribution on a
Raspberry Pi
e following lists describe the software packages, grouped by category. ere is also a category not covered here, dubbed “Other”, into which numerous system tools are grouped. If
you have installed a program and can’t nd it anywhere else, try the Other menu.
Accessories
❍
DebianReference—A built-in reference guide, this provides a detailed explanation of
the Debian Linux distribution and how programmers can contribute to its development.
❍ File Manager—e PCManFM le manager provides a graphical browser for les
stored on the Pi or any connected storage device.
❍ Galculator—An open source scientic calculator, oering a variety of functions for
both quick and complex sums.
❍ Image Viewer—e GPicView lets you view images, such as those from a digital cam-
era or on a connected storage device.
❍ Leafpad—is is a simple text editor, which is useful for making quick notes or writ-
ing simple programs.
❍ LXTerminal—is LXDE terminal package allows you to use the Linux command line
in a window without leaving the graphical user interface.
❍ Root Terminal—Similar to LXTerminal, the Root Terminal automatically logs you in
as the root superuser account in order to carry out system maintenance tasks unavailable to a regular user account.
❍ Xarchiver—If you need to create or extract compressed les, such as Zip archives, this
is the tool for the job.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
Education
❍
Scratch—A graphical programming language aimed at young children. You’ll learn
more about Scratch and its capabilities in Chapter 11, “An Introduction to Scratch”.
❍ Squeak—e platform on which Scratch runs. You will rarely need to use this menu
entry, and should instead use the Scratch entry above.
Internet
❍
Dillo—One of the fastest web browsers available for the Pi, but somewhat basic compared to Midori.
❍ Midori—A fast yet lightweight web browser, Midori is equivalent to Internet Explorer
in Windows or Safari on OS X.
❍ Midori Private Browsing—Clicking on this menu entry loads the Midori web browser
in private mode, meaning that sites you visit aren’t saved into the browser’s history.
47
❍ NetSurf Web Browser—An alternative to Midori, NetSurf can perform better on cer-
tain types of web page. Trying both will allow you to experiment and nd the one that
works best for you.
❍ wps_gui—A graphical user interface for conguring a Raspberry Pi with optional USB
Wireless Adapter to connect to a Wireless Protected System (WPS) encrypted network.
Programming
❍
IDLE—An integrated development environment (IDE) written specically for Python.
You’ll learn more about using IDLE to write your own Python programs in Chapter 12,
“An Introduction to Python”.
❍ IDLE 3—Clicking this entry loads IDLE congured to use the newer Python 3 pro-
gramming language, rather than the default Python 2.7 language. Both are largely
compatible with each other, but some programs may require features of Python 3.
❍ Scratch—is shortcut opens the Scratch educational language, and is the same as the
Scratch entry found in the Education category. Either can be used to start the program.
❍ Squeak—As with Scratch, this is a duplicate of the shortcut found in the Education cate-
gory. You will rarely want to click this directly, and should instead use the Scratch shortcut.
System Tools
Task Manager—A tool for checking the amount of free memory available on the Pi
❍
and the current workload of the processor, and for closing programs that have crashed
or are otherwise unresponsive.
48
PAR T I CONNECTING THE BOARD
Preferences
❍
Customise Look and Feel—A toolkit for adjusting the appearance of the GUI, including the style and colour of windows.
❍ Desktop Session Settings—A tool for changing how the system works when the
user is logged in, including what programs are automatically loaded and which
window manager—the software that draws the borders and title bars of windows—
is used.
❍ Keyboard and Mouse—A tool for adjusting input devices. If your keyboard is typing
the wrong characters for certain keys, or your mouse is too sensitive, the settings can
be altered here.
❍ Monitor Settings—e resolution that the monitor or TV connected to the Pi runs at
can be altered here, although advanced changes require modication of conguration
les. You’ll learn about this in Chapter 7, “Advanced Raspberry Pi Conguration”.
❍ Openbox Conguration Manager—e LXDE GUI uses a desktop environment
called Openbox, which can be adjusted here. Using this tool, you can apply new themes
to change the GUI’s appearance, or alter how certain aspects of the interface operate.
❍ Preferred Applications—A tool for changing which applications are opened for par-
ticular le types. If you choose to use an alternative web browser, the system default
can be changed here.
Finding Help
Linux is designed to be as user-friendly as possible to new users, even at the terminal command prompt. Although you’ll learn the most common ways to use each command in this
chapter, not every option will be covered—to do so would require a much larger book.
If you nd yourself stuck, or if you want to learn more about any of the tools that are discussed in the following pages, there’s a command you should learn: man.
Each Linux application comes with a help le known as a man page—short for “manual
page”. It provides background on the software as well as details on what its options do and
how to use them.
To access the man page for a given tool, just type man followed by the command name. To
see the man page for ls, a tool for listing the contents of directories, just type man ls.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
About Raspbian’s Parent, Debian
Raspbian is based on one of the original Linux distributions, Debian. Named after its creator and
his girlfriend—Ian and Deb—Debian is a popular distribution in its own right. It is common in
the world of open source software, however, for projects to start up based on rening, customising or tweaking existing projects in a process known as forking. Raspbian is a fork of Debian, but
it isn’t alone: Ubuntu Linux from Canonical is also based on Debian, while Linux Mint, one of
the most popular distributions for desktops and laptops, is based in turn on Ubuntu.
is process of forking and forking again is something unique to open source software. With
a closed-source package, like Microsoft Windows, it’s not possible to customise it to your
individual requirements. is is one of the biggest strengths of open source software, and is
brilliantly demonstrated by the ease with which Raspbian was tailored to the requirements
of the Raspberry Pi.
Alternatives to Raspbian
49
While Raspbian is the recommended Linux distribution for the Raspberry Pi, there are alternatives. e most popular are available from the Raspberry Pi Foundation’s Downloads page
at http://www.raspberrypi.org/downloads, and most can be installed easily using
NOOBS, as described in Chapter 2, “Getting Started with the Raspberry Pi”.
Next to Raspbian, the most common distributions installed are RaspBMC and OpenELEC,
which both turn the Pi into a dedicated home theatre system, as demonstrated in Chapter 8,
“e Pi as a Home eatre PC”. e next most popular is Pidora, a distribution based on the
Fedora Linux project, which, in turn, has Red Hat as its parent distribution. Finally, Arch
Linux is designed for those already familiar with Linux; unlike the others in the list, it doesn’t
include a graphical user interface by default.
One entry in the NOOBS list is not a variant of Linux at all: RiscOS. Originally produced by
Acorn Computers in the late 1980s for its Archimedes range of personal computers—which,
like the Raspberry Pi, were based on an ARM processor—RiscOS is a fast, easy-to-use operating system with a clean appearance to its graphical user interface. While the breakup of
Acorn in 1998 saw the popularity of RiscOS decline, the platform still has its fans, who were
quick to add support for the Raspberry Pi.
Running RiscOS on the Raspberry Pi results in an environment that is signicantly more
responsive than any of the other operating systems on oer, thanks to its origins as a platform designed specically for the ARM instruction set architecture. Sadly, that speed comes
at a cost: RiscOS can only run applications written specically for RiscOS, of which there are
far fewer than those written for Linux.
50
PAR T I CONNECTING THE BOARD
Using External Storage Devices
e Pi’s SD card, which stores all the various Pi les and directories, isn’t very big. e largest
available SD card at the time of writing is 256 GB, which is tiny compared to the 4,000 GB (4
TB) available from the largest full-size desktop hard drives.
If you’re using your Pi to play back video les (see Chapter 8, “e Pi as a Home eatre PC”)
you’ll likely need more storage than you can get from an SD card. As you learned in Chapter 1,
“Meet the Raspberry Pi”, it’s possible to connect USB Mass Storage (UMS) devices to the Pi
in order to gain access to more storage space.
Before these external devices are accessible, however, the operating system needs to know
about them. In Linux, this process is known as mounting. If you’re running a version of Linux
with a desktop environment loaded—like the recommended Raspbian distribution’s LXDE,
loaded from the console with the startx command—this process is automatic. Simply connect the device to a free USB port on the Pi or a USB hub, and the device and its contents will
immediately be accessible (see Figure 3-2).
F -:
LXDE
automatically
mounting a USB
mass storage
device
TIP
From the console, things are only slightly more dicult. To make a device accessible to Linux
when the desktop environment isn’t loaded, follow these steps:
Where you see a ↵ symbol, this means the command has been split over multiple lines due to
the size of the book’s pages. Enter the command as a single line, continuing to type for each
line that ends in a ↵ and only pressing Enter at the very end of the command.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
51
1. Connect the USB storage device to the Pi, either directly or through a connected
USB hub.
2. Type sudo fdisk -l to get a list of drives connected to the Pi, and nd the USB
storage device by size. Note the device name: /dev/sdXN, where X is the drive letter and N
is the partition number. If it is the only device connected to the Pi, this will be /dev/sda1.
3. Before the USB storage device is accessible, Linux needs a mount point for it. Create
this by typing sudo mkdir /media/externaldrive.
4. Currently, the device is only accessible to the root user. To make it accessible to all
5. Type the following command to mount the USB storage device to gain access to the
device and its contents:
sudo mount /dev/sdXN /media/externaldrive -o=rw
Creating a New User Account
Unlike many desktop operating systems, which were originally designed for use by a single
individual, Linux is at heart a social operating system designed to accommodate numerous
users. By default, Raspbian is congured with two user accounts: pi, which is the normal user
account, and root, which is a superuser account with additional permissions.
TIP
Don’t be tempted to log in as root all the time. Using a nonprivileged user account, you’re
protected against accidentally wrecking your operating system and from the ravages of viruses
and other malware downloaded from the Internet.
While it’s certainly possible for you to use the pi account, it’s better if you create your own
dedicated user account. Further accounts can also be created, for any friends or family members who might want to use the Pi.
Creating a new account on the Pi is straightforward, and is roughly the same on all distributions, except for the username and password used to log in to the Pi initially. Just follow
these steps:
1. Log in to the Pi using the existing user account (user name pi and password rasp-
berry if you’re using the recommended Raspbian distribution).
52
PAR T I CONNECTING THE BOARD
2. Type the following as a single line with no spaces after any of the commas:
3. To set a password on the new account, type sudo passwd username followed by
the new password when prompted.
To explain what just happened: the command sudo tells the operating system that the command you’re typing should be run as if you were logged in as the root account. e useradd
command says you want to create a new user account. e -m section—known as a ag or an
option—tells the useradd program to create a home directory where the new user can store
his or her les. e big list following the -G ag is the list of groups of which the user should
be a member.
Users and Groups
In Linux, each user has three main attributes: their User ID (UID), their Group ID (GID) and a
list of supplementary group memberships. A user can be a member of as many groups as
he or she pleases, although only one of these can be the user’s primary group. This is usually a self-named group matching the user name.
Group membership is important. While users can be granted direct access to les and
devices on the system, it’s more common for a user to receive access to these via group
membership. The group audio, for example, grants all members the ability to access the
Pi’s sound playback hardware. Without that membership, the user won’t be listening to any
music.
To see a user’s group memberships, type groups username at the terminal. If you use
this on the default user pi, you’ll see the list of groups any new member should join to make
use of the Pi. This is where the information used in step 2 of the preceding procedure was
found.
File System Layout
e content of the SD card is known as its le system and is split into multiple sections, each
with a particular purpose. Although it’s not necessary for you to understand what each section does in order to use the Raspberry Pi, it can be helpful background knowledge should
anything go wrong.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
Logical Layout
e way Linux deals with drives, les, folders and devices is somewhat dierent to other
operating systems. Instead of having multiple drives labelled with a letter, everything appears
as a branch beneath what is known as the root le system.
If you log in to the Pi and type ls / you’ll see various directories displayed (see Figure 3-3).
Some of these are areas of the SD card for storing les, while others are virtual directories for
accessing dierent portions of the operating system or hardware.
53
F -:
A directory
listing for the
Pi’s root le
system
e directories visible on the default Raspbian distribution are as follows:
❍ boot—is contains the Linux kernel and other packages needed to start the Pi.
❍ bin—Operating system-related binary les, like those required to run the GUI, are
stored here.
❍ dev—is is a virtual directory, which doesn’t actually exist on the SD card. All the
devices connected to the system—including storage devices, the sound card and the
HDMI port—can be accessed from here.
54
PAR T I CONNECTING THE BOARD
❍
etc—is stores miscellaneous conguration les, including the list of users and their
encrypted passwords.
❍ home—Each user gets a subdirectory beneath this directory to store all their personal
les.
❍ lib—is is a storage space for libraries, which are shared bits of code required by
numerous dierent applications.
❍ lost+found—is is a special directory where le fragments are stored if the system
crashes.
❍ media—is is a special directory for removable storage devices, like USB memory
sticks or external CD drives.
❍ mnt—is folder is used to manually mount storage devices, such as external hard drives.
❍ opt—is stores optional software that is not part of the operating system itself. If
you install new software to your Pi, it will usually go here.
❍ proc—is is another virtual directory, containing information about running pro-
grams, which are known in Linux as processes.
❍ selinux—Files related to Security Enhanced Linux, a suite of security utilities originally
developed by the US National Security Agency.
❍ sbin—is stores special binary les, primarily used by the root (superuser) account
for system maintenance.
❍ sys—is directory is where special operating system les are stored.
❍ tmp—Temporary les are stored here automatically.
❍ usr—is directory provides storage for user-accessible programs.
❍ var—is is a virtual directory that programs use to store changing values or variables.
Physical Layout
Although the preceding list is how the le system appears to the Linux operating system, it’s
not how it’s laid out on the SD card itself. For the default Raspbian distribution, the SD card is
organised into two main sections, known as partitions because they split the device into dierent areas in much the same way as the chapters of this book help to organise its contents.
e rst partition on the disk is a small (approximately 75 MB) partition formatted as VFAT,
the same partition format used by Microsoft Windows for removable drives. is is mounted,
or made accessible, by Linux in the /boot directory and contains all the les required to
congure the Raspberry Pi and to load Linux itself.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
e second partition is far larger and formatted as EXT4, a native Linux le system designed
for high-speed access and data safety. is partition contains the main chunk of the distribution. All the programs, the desktop, the users’ les and any software that you install yourself
are stored here. is takes up the bulk of the SD card.
Installing and Uninstalling Software
e default software installed with the Raspbian distribution is enough to get you started, but
chances are you’re going to want to customise your Pi according to your own requirements.
Obtaining Software from the Pi Store
Installing new software onto the Pi is simple, thanks to the inclusion of the Raspberry Pi
Store. is is a custom shopfront where Pi programmers can oer their software for quick
download and installation. To get started, double-click the Pi Store icon on the desktop. e
window that appears provides access to all software currently available through the Pi Store
(see Figure 3-4).
55
F -:
e Pi Store
main window
56
PAR T I CONNECTING THE BOARD
Software on the Pi Store is split into categories, ranging from games to tutorials and even
media like videos, books and magazines. Clicking on a category across the top will show the
software from that category in a grid, which can be scrolled using the keyboard or mouse.
Clicking on a piece of software will provide access to more information and a download link
to automatically install the software (see Figure 3-5).
F -:
Viewing
software in the
Pi Store
Before software can be installed, however, you will need to register for an account. e Pi Store
is run by digital distribution specialist IndieCity; if you already have an account on IndieCity’s
own website, you can use this by clicking the Log In option at the top right of the Pi Store window and entering your email address and password. If not, when you try to download any
software you will be asked to register: simply click the Register button and ll in your email
address, followed by typing a password for your account in the two boxes provided.
Some software on the Pi Store requires payment. If this is the case, attempting to install the
software will prompt you for your name, address and payment details. ese details are
transmitted across an encrypted connection, meaning that they cannot be seen during transit,
and used by the Pi Store’s operator IndieCity to take payment for the item. Once payment
has been made, the software can be downloaded as normal.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
All software you install through the Pi Store is placed in the My Library section (see Figure 3-6).
is provides an easy way to uninstall software, or to install software that you have previously
used but since removed. Downloads are tied to your account; if you log in to the Pi Store on a
dierent Raspberry Pi, you can use the My Library to quickly nd and install your favourite
software.
57
F -:
e Pi Store My
Library screen
As you learn to use the Raspberry Pi, and especially if you’re learning to program, you may
nd yourself writing software of your own. Whether it’s a game, a productivity application or
even a tutorial, you can quickly and easily list it for download on the Pi Store by clicking the
Upload option and lling in the form that appears.
If you have any trouble with the Pi Store, either for downloading software or publishing your
own, click the question mark icon at the top right of the window to access help.
Obtaining Software from Elsewhere
For a larger selection of packages, the Raspbian distribution includes a tool called apt, which
is a powerful package manager. Packages are what Linux calls a piece of software, or a collection of dierent pieces of software designed to work together.
58
PAR T I CONNECTING THE BOARD
Although apt is designed to be operated from the command line, it’s very user-friendly and
easy to learn. ere are GUIs for apt, such as the popular Synaptic Package Manager, but
they often struggle to run on the Pi due to the lack of memory. As a result, we recommend
that software be installed at the terminal.
Other Distributions
Raspbian, in common with most Debian-based distributions, uses a tool called apt as the
package manager. It’s not the only tool out there, and other distributions make different
choices. Pidora, for example, uses the pacman tool.
Pacman is no more difcult to use than apt, but its syntax (the way it expects you to phrase
instructions to install new software or remove existing software) is different. For instructions on how to use pacman instead of apt, type man pacman at the Pidora terminal.
TIP
Other distributions may use the yum package manager. If you’re trying a distribution that
uses yum, simply type man yum at the terminal for instructions.
A package manager’s job is to keep track of all the software installed on the system. It doesn’t
just install new software—it also keeps tabs on what is currently installed, allows old software to be removed and installs updates as they become available.
Package management is one of the areas where Linux diers greatly from operating systems
like Windows or OS X. Although it’s possible to manually download new software to install,
it’s far more common to use the built-in package management tools instead.
Before trying to install new software or upgrade existing software, you need to make sure
the aptcache is up to date. To do this, simply type the command sudo apt-get update.
Finding the Software You Want
e rst step to installing a new piece of software is to nd out what it’s called. e easiest
way to do this is to search the cache of available software packages. is cache is a list of all
the software available to install via apt, stored on Internet servers known as repositories.
e apt software includes a utility for managing this cache, called apt-cache. Using this
software, it’s possible to run a search on all the available software packages for a particular
word or phrase.
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
59
For example, to nd a game to play, you can type the following command:
apt-cache search game
at tells apt-cache to search its list of available software for anything that has the word
“game” in its title or description. For common search terms, you can end up with quite a list
(see Figure 3-7), so try to be as specic as you can.
F -:
e last few
results for an
apt-cache
“game” search
TIP
If your search term brings up too many different packages to see on a single screen display,
you can tell Linux that you want it to pause on each screenful by piping the output of apt-
cache through a tool called less. Simply change the command to apt-cache search
game | less and use the cursor keys to scroll through the list. Press the letter Q on the
keyboard to exit.
Installing Software
Once you know the name of the package you want to install, switch to the apt-get command in order to install it. Installing software is a privilege aorded only to the root user, as
60
PAR T I CONNECTING THE BOARD
it aects all users of the Raspberry Pi. As a result, the commands will need to be prefaced
with sudo to tell the operating system that it should be run as the root user.
For example, to install the package nethack-console (a console-based randomly generated
role-playing game), you would simply use the install command with apt-get as follows:
sudo apt-get install nethack-console
Some packages rely on other packages in order to operate. A programming language may
depend on a compiler, a game engine on graphics les, or an audio player on codecs for playing back dierent formats. ese are known in Linux terms as dependencies.
Dependencies are one of the biggest reasons for using a package manager like apt rather
than installing software manually. If a package depends on other packages, apt will automatically nd them (see Figure 3-8) and prepare them for installation. If this happens, you’ll
be shown a prompt asking whether you want to continue. If you do, type the letter Y and
press the Enter key.
F -:
Apt listing the
dependencies
for the
OpenOce.org
package
CHAPTER 3 LINUX SYSTEM ADMINISTRATION
Uninstalling Software
If you decide you no longer want a piece of software, apt-get also includes a remove command that cleanly uninstalls the package along with any dependencies that are no longer
required. When you’re using a smaller SD card with the Pi, the ability to try out software and
quickly remove it is extremely useful.
To remove nethack-console, simply open the terminal and type the following command:
sudo apt-get remove nethack-console
e remove command has a more powerful brother in the form of the purge command.
Like remove, the purge command gets rid of software you no longer require. Where
remove leaves the software’s conguration les intact, however, purge removes every-
thing. If you’ve got yourself into a mess customising a particular package and it no longer
works, purge is the command to use. For example, to purge nethack-console, you would
just type this:
61
sudo apt-get purge nethack-console
Upgrading Software
In addition to installing and uninstalling packages, apt can be used to keep them up to date.
Upgrading a package through apt ensures that you’ve received the latest updates, bug xes
and security patches.
Before trying to upgrade a package, make sure the apt cache is as fresh as possible by running an update:
sudo apt-get update
When upgrading software, you have two choices: you can upgrade everything on the system
at once or upgrade individual programs. If you just want to keep your distribution updated,
the former is achieved by typing the following:
sudo apt-get upgrade
To upgrade an individual package, simply tell apt to install it again. For example, to install a
nethack-console upgrade, you would type this:
sudo apt-get install nethack-console
62
PAR T I CONNECTING THE BOARD
If the package is already installed, apt will treat it as an in-place upgrade. If you’re already
running the latest version available, apt will simply tell you it cannot upgrade the software,
and will then exit.
TIP
For more information on package management with apt—in particular, how certain packages
can be “kept back” and excluded from upgrades—type man apt at the terminal.
Shutting the Pi Down Safely
Although the Pi doesn’t have a power switch like a traditional computer, that doesn’t mean that
you can simply pull the power cable out when you’re nished. Even when it doesn’t appear to
be doing anything, the Pi is often reading from or writing to the SD card, and if it loses power
while this is happening the contents of the card can become corrupt and unreadable.
To shut down using the terminal, type the following command:
sudo shutdown -h now
e Pi will close all open applications, prompting you to save any open les if you haven’t
done so already, and shut itself down, at which point the screen will go black and the ACT
light will switch o. Once the light has gone o, it’s safe to remove the micro-USB cable or
switch the Pi o at the wall.
When you want to switch the Pi back on, or if you accidentally shut the Pi down without
meaning to, simply reconnect the power and it will start to boot automatically.
Chapter 4
Troubleshooting
64
PAR T I CONNECTING THE BOARD
SOMETIMES, THINGS DON’T
more complex the problems that can occur—and the Pi is an extremely complex device
indeed.
ankfully, many of the most common problems are straightforward to diagnose and x. In
this chapter, we’ll look at some of the most common reasons for the Pi to misbehave and
how to x them.
go entirely smoothly. e more complex the device, the
Keyboard and Mouse Diagnostics
Perhaps the most common problem that users experience with the Raspberry Pi is when the
keyboard repeats certain characters. For example, if the command startx appears onscreen
as sttttttttttartxxxxxxxxxxxx, it will, understandably, fail to work when the Enter
key is pressed.
ere are typically two reasons why a USB keyboard fails to operate correctly when connected to the Raspberry Pi: it’s drawing too much power, or its internal chipset is conicting
with the USB circuitry on the Pi.
Check the documentation for your keyboard, or the label on its underside, to see if it has a
power rating given in milliamps (mA). is is how much power the keyboard attempts to draw
from the USB port when it’s in use.
e Pi’s USB ports have a component called a polyfuse connected to them, which protects the
Pi in the event that a device attempts to draw too much power. When this polyfuse is tripped,
it causes the USB port to shut o, at around 150 mA. If your keyboard draws anywhere
around that much power, it may operate strangely—or not at all. is can be a problem for
keyboards that have built-in LED lighting, which require far more power to operate than a
standard keyboard.
If you nd that your USB keyboard may be drawing too much power, try connecting it to a
powered USB hub instead of directly to the Pi. is will allow the keyboard to draw its power
from the hub’s power supply unit, instead of from the Pi itself. Alternatively, swap the keyboard out for a model with lower power demands. e repeating-letter problem may also be
traced to an inadequate power supply for the Pi itself, which is addressed in the next section,
“Power Diagnostics”.
CHAPTER 4 TROUBLESHOOTING
65
e issue of compatibility, sadly, is harder to diagnose. While the overwhelming majority of
keyboards work just ne with the Pi, a small number exhibit strange symptoms. ese range
from intermittent response, the repeating-letter syndrome or even crashes that prevent the
Pi from operating. Sometimes, these issues don’t appear until other USB devices are connected to the Pi. If your keyboard was working ne until another USB device, in particular a
USB wireless adapter, was connected, you may have an issue of incompatibility.
If possible, try swapping the keyboard out for another model. If the new keyboard works,
your old one may be incompatible with the Pi. For a list of known-compatible keyboards,
visit the eLinux wiki at http://elinux.org/RPi_USB_Keyboards.
e same advice on checking compatibility in advance applies to problems with the mouse:
the majority of USB mice and trackballs work ne, but some exhibit incompatibility with the
Pi’s own USB circuitry. is usually results in symptoms like a jerky or unresponsive mouse
pointer, but it can sometimes lead to the Pi failing to load or crashing at random intervals. If
you’re looking to buy a new mouse, an up-to-date list of models known to work with the Pi is
available at the eLinux wiki site at http://elinux.org/RPi_USB_Mouse_devices.
Power Diagnostics
Many problems with the Raspberry Pi can be traced to an inadequate power supply. e
Model A requires a 5 V supply capable of providing a 500 mA current, while the Model B’s
extra components bump up the current requirement to 700 mA. Not all USB power adapters
are designed to oer this much power, even if their labelling claims otherwise.
TIP
The formal USB standard states that devices should draw no more than 500 mA, with even
that level of power only available to the device following a process called negotiation. Because
the Pi doesn’t negotiate for power, it’s unlikely that it will work if you connect it to the USB
ports on a desktop or laptop computer.
If you’re having intermittent problems with your Pi—particularly if it works until you connect something to a USB port or start a processor-intensive operation like playing video—
the chances are that the power supply in use is inadequate. e Pi provides a relatively easy
way to check if this is the case in the form of two voltage test points.
66
PAR T I CONNECTING THE BOARD
To use the voltage test points, you’ll need a voltmeter or multimeter with direct current (DC)
voltage measuring capabilities. If your meter has multiple inputs for dierent voltages, use
an appropriate setting.
WARNING
F -:
e two voltage
test points,
labelled TP1 and
TP2, on a
Raspberry Pi
Model B
Revision 1
Avoid touching the test probes to anything not labelled as a test point. It’s possible to bridge
the 5 V supply that comes in to the Pi to the internal 3.3 V supply, creating a short circuit which
can damage the device. Be especially careful around exposed header pins.
e two test points are small, copper-clad holes known as vias, which are connected to the
Pi’s 5 V and ground circuits. Put the positive (red) meter probe on TP1, located to the left of
the board just above a small black component called a regulator labelled RG2. Connect the
black (negative) meter probe to TP2, located between the copper GPIO pins and the yellowand-silver RCA phono connector at the top-left of the board (see Figure 4-1).
CHAPTER 4 TROUBLESHOOTING
e reading on the voltmeter should be somewhere between 4.8 V and 5 V. If it’s lower than
4.8 V, this indicates that the Pi is not being provided with enough power. Try swapping the
USB adapter for a dierent model, and check that the label says it can supply 700 mA or
more. A model rated at 1A is recommended, but beware of cheap models—they sometimes
have inaccurate labelling, and fail to supply the promised current. Genuine branded mobile
phone chargers rarely have this problem, but cheap unbranded devices—often sold as
compatible adapters—should be avoided
If your voltmeter reads a negative number, don’t worry: this just means you’ve got the positive and negative probes in the wrong place. Either swap them around or just ignore the
negative sign when noting your reading.
Display Diagnostics
Although the Pi is designed to work with almost any HDMI, DVI or composite video display
device, it simply may not work as expected when you plug it in. For example, you may nd
that your picture is shifted to the side or not fully displayed, or is only visible as a postagestamp-sized cut-out in the middle of the screen or in black-and-white—or even missing
entirely.
67
First, check the type of device to which the Pi is connected. is is especially important when
you’re using the composite RCA connection to plug the Pi into a TV. Dierent countries use
dierent standards for TV video, meaning that a Pi congured for one country may not work
in another. is is the usual explanation for a Pi showing black-and-white video. You’ll learn
how to adjust this setting in Chapter 7, “Advanced Raspberry Pi Conguration”.
When you use the HDMI output, the display type is usually automatically detected. If you’re
using an HDMI to DVI adapter to plug the Pi into a computer monitor, this occasionally goes
awry. Common symptoms include snow-like static, missing picture portions or no display at
all. To x this, note the resolution and refresh rate of your connected display, and then jump
to Chapter 7, “Advanced Raspberry Pi Conguration”, to nd out how to set these manually.
Another issue is a too-large or too-small image, either missing portions at the edge of the
screen or sitting in the middle of a large black border. is is caused by a setting known as
overscan, which is used when the Pi is connected to TVs to avoid printing to portions of the
display which may be hidden under a bezel. As with other display-related settings, you will
learn how to adjust—or even completely disable—overscan in Chapter 7.
68
PAR T I CONNECTING THE BOARD
Boot Diagnostics
e most common cause for a Pi to fail to boot is a problem with the SD card. Unlike a desktop or laptop computer, the Pi relies on les stored on the SD card for everything. If Pi can’t
talk to the card, it won’t display anything on the screen or show any signs of life at all.
If your Pi’s power light glows when you connect the micro-USB power supply, but nothing
else happens and the OK light remains dark, you have an SD card problem. First, ensure that
the card works when you connect it to a PC, and that it shows the partitions and les
expected of a well-ashed card. (For more details, see Chapter 3, “Linux System
Administration”, particularly the section titled “File System Layout” in that chapter.)
If the card works on a PC but not in the Pi, it may be a compatibility problem. Some SD
cards—especially high-speed cards marked as Class 10 on their labelling—don’t operate correctly when connected to the Pi’s onboard SD card reader. A list of cards known to be compatible with the Pi can be found on the eLinux wiki at http://elinux.org/RPi_SD_cards.
Sadly, if you have an incompatible card, you will probably need to replace it with a dierent
card in order for the Pi to work. As the Pi’s software base is developed, however, work is
being carried out to ensure that a wider range of cards operate correctly with the Pi. Before
giving up on a high-speed card completely, check to see if an updated version of your chosen
Linux distribution is available. (See Chapter 1, “Meet the Raspberry Pi”, for more information about distributions.)
If you’ve been changing the speed of your Raspberry Pi by overclocking (see Chapter 6, “e
Raspberry Pi Software Conguration Tool”), this can also stop it from booting correctly. To
temporarily disable the overclock and run the Pi at its default speed, hold down the Shift key
as you turn the Pi on.
Network Diagnostics
e most useful tool for diagnosing network problems is ifconfig. If you’re using a wireless network connection, jump to Chapter 5, “Network Conguration”, for information on a
similar tool for those devices. Otherwise, read on.
Designed to provide information on connected network ports, ifconfig is a powerful tool
for controlling and conguring the Pi’s network ports. For its most basic usage, simply type
the tool’s name in the terminal:
ifconfig
CHAPTER 4 TROUBLESHOOTING
Called in this manner, ifconfig provides information on all the network ports it can nd
(see Figure 4-2). For the standard Raspberry Pi Model B, there are two ports: the physical
Ethernet port on the right side of the board, and a virtual loopback interface that allows programs on the Pi to talk to each other.
69
F -:
e output of
ifconfig on
a Raspberry Pi
Model B
e output of ifconfig is split into the following sections:
❍ Link encap—e type of encapsulation used by the network, which on the Model B will
either read Ethernet for the physical network port or Local Loopback for the virtual loopback adaptor.
❍ Hwaddr—e Media Access Control (MAC) address of the network interface, written in
hexadecimal. is is unique for every device on the network, and each Pi has its own
MAC address, which is set at the factory.
❍ inet addr—e internet protocol (IP) address of the network interface. is is how you
nd the Pi on the network if you’re using it to run a network-accessible service, such as
a web server or le server.
70
PAR T I CONNECTING THE BOARD
❍
Bcast—e broadcast address for the network to which the Pi is connected. Any trac
sent to this address will be received by every device on the network.
❍ Mask—e network mask, which controls the maximum size of the network to which
the Pi is connected. For most home users, this will read 255.255.255.0.
❍ MTU—e maximum transmission unit size, which is how big a single packet of data
can be before the system needs to split it into multiple packets.
❍ RX—is section provides feedback on the received network trac, including the
number of errors and dropped packets recorded. If you start to see errors appearing in
this section, there’s something wrong with the network.
❍ TX—is provides the same information as the RX section, but for transmitted pack-
ets. Again, any errors recorded here indicate a problem with the network.
❍ collisions—If two systems on the network try to talk at the same time, you get a colli-
sion which requires them to retransmit their packets. Small numbers of collisions
aren’t a problem, but a large number here indicates a network issue.
❍ txqueuelen—e length of the transmission queue, which will usually be set to 1000
and rarely needs changing.
❍ RX bytes, TX bytes—A summary of the amount of trac the network interface has
passed.
If you’re having problems with the network on the Pi, you should rst try to disable and then
re-enable the network interface. e easiest way to do this is with two tools called ifup and
ifdown.
If the network is up, but not working correctly—for example, if ifconfig doesn’t list anything in the inet addr section—start by disabling the network port. From the terminal,
type the following command:
sudo ifdown eth0
Once the network is disabled, make sure that the cable is inserted tightly at both ends, and
that whatever network device the Pi is connected to (hub, switch or router) is powered on
and working. en bring the interface back up again with the following command:
sudo ifup eth0
CHAPTER 4 TROUBLESHOOTING
You can test the networking by using the ping command, which sends data to a remote
computer and waits for a response. If everything’s working, you should see the same response
as shown in Figure 4-3. If not, you may need to manually congure your network settings,
which you’ll learn how to do in Chapter 5, “Network Conguration”.
71
F -:
e result of a
successful test
of the network,
using the ping
command
The Emergency Kernel
e Linux kernel is the heart of the operating system that drives the Pi. It’s responsible for
everything from making sure that you can access your les to allowing programs to talk to
other programs.
When switched on, your Pi will load the normal, default kernel. ere’s also a second kernel
included in most distributions, which sits unused. is is the emergency kernel, and as the
name suggests, it is typically used only when the normal kernel isn’t working.
72
PAR T I CONNECTING THE BOARD
It’s highly unlikely that you’ll ever need to boot a Pi using the emergency kernel, but it’s
worth learning how to do so just in case. is is especially important if you’re upgrading your
kernel or are using a new and potentially poorly tested distribution. Sometimes, newly
released software can have bugs which aren’t spotted before its release. When encountering
strange errors after upgrading, the emergency kernel can be used to narrow down the problem to the new kernel version.
e Linux kernel is a single le located in the /boot directory called kernel.img. When
the Pi is rst switched on and begins to load the operating system, it looks for this le, and if
the le is missing, the Pi won’t work. e emergency kernel is a second le, again in the /
boot directory, called kernel_emergency.img.
e emergency kernel is, in most cases, almost identical to the standard kernel. When
changes are made to the standard kernel, to boost performance or add new features for
example, the emergency kernel is left unaltered. is way, if the changes to the standard
kernel cause stability problems, a user can simply tell the Pi to load the emergency kernel
instead.
ere are two ways to boot into the emergency kernel, and both require the use of a PC and
an SD card reader if the Pi can’t boot. Otherwise, the following steps can be carried out on
the Pi itself.
e easiest way to boot the emergency kernel is to rename the existing kernel.img le to
kernel.img.bak, and then rename the kernel_emergency.img le to kernel.img.
When the Pi loads, it will now load the emergency kernel by default. To go back to the standard kernel, simply reverse the process: rename kernel.img to kernel_emergency.img
and kernel.img.bak to kernel.img.
An alternative method to load the emergency kernel is to edit the cmdline.xt le (located
in the /boot directory) by adding the following entry at the end of the existing command
line:
kernel=kernel_emergency.img
is tells the Pi that it should load the kernel named kernel_emergency.img instead of
the usual kernel.img. Reversing the process is as simple as opening cmdline.txt again
and removing the entry.
You’ll learn more about cmdline.txt and how it aects the operation of the Raspberry Pi
in Chapter 7, “Advanced Raspberry Pi Conguration”.
Chapter 5
Network Configuration
74
PAR T I CONNECTING THE BOARD
FOR MOST USERS,
into the Model B’s Ethernet port—or a USB Ethernet adapter, in the case of the Model A. For
others, however, the network requires manual conguration.
If you know that your network doesn’t have a Dynamic Host Conguration Protocol (DHCP)
server—a system that tells the Pi and other devices on the network how they should connect—or if you want to use a USB wireless adapter with the Pi, read on.
conguring the Raspberry Pi’s network is as easy as plugging a cable
Wired Networking
In some instances, in order for the Pi’s network to operate correctly you may need to congure it manually. Normally, the network in a home, school or oce has a DHCP server that
tells the Pi and other devices on the network how they should connect. Some networks don’t
have a DHCP server, however, and need to be set up manually.
e list of network interfaces, along with information about how they should be congured,
is stored in a le called interfaces located in the folder /etc/network. is is a le only
the root user can edit, because removing a network interface from this list will cause it to stop
working.
From the terminal, you can edit this le using a variety of dierent text editors. For simplicity, the nano text editor should be used for this process. Open the le for editing with the
following command:
sudo nano /etc/network/interfaces
is a powerful yet lightweight text editor, with a simple user interface (see Figure 5-1).
Nano
You can move your cursor around the document with the arrow keys, save the le by holding
down the CTRL key and pressing O, and quit by holding down the CTRL key and pressing X.
e line you need to edit for manual conguration starts with iface eth0 inet. Delete
dhcp from the end of this line and replace it with static, press Enter to start a new line,
and then ll in the remaining details in the following format with a tab at the start of each
line:
Make sure that you press the Tab key at the start of each line, and don’t actually type [Tab].
e x characters in the conguration lines represent network addresses you’ll need to enter.
For address, you should enter the static IP address that you want to assign to the Pi. For
netmask, you should enter the network mask—which controls the size of the connected
network—in what is known as dotted-quad format. If you’re using a home network, this is
typically 255.255.255.0. For gateway, you should enter the IP address of your router or
cable modem.
As an example, the settings for a common home network would look like this:
When you’ve nished editing the le, press CTRL + O to save it, and then press CTRL + X to
leave nano and return to the terminal. To use your new network settings, restart the net-working service by typing the following:
sudo /etc/init.d/networking restart
76
PAR T I CONNECTING THE BOARD
If you need to return to automatic settings via DHCP, you need to edit the interfaces le
again and delete the address, netmask and gateway settings. Replace static with dhcp
at the end of the iface line, and then restart the networking service again.
Setting a manual IP address isn’t quite enough to get your Pi connected to the outside world.
Computers on modern networks have both a numerical address identier—known as an IP
address—and a hostname or domain name. It’s this latter, friendly name that allows you
simply to type www.raspberrypi.org into your browser, instead of trying to remember
93.93.128.176.
A system called a Domain Name Service (DNS) server is responsible for looking up the friendly
names you supply and converting them into the numbers required to access the system. It
operates much like an automated telephone directory. Before you’ll be able to access Internetconnected systems via their domain names, you’ll need to tell the Pi which DNS servers to use.
e list of DNS servers, known as nameservers in Linux parlance, is stored in /etc/resolv.
conf. When the system gets its details through DHCP, this le is automatically lled in; but
when you set an address manually, you need to provide the addresses of the nameservers on
your network. Normally, this would be the address of your router as found in the gateway
line from the interfaces le (described earlier in this chapter).
To set the nameservers, open the le with nano by typing the following command at the
terminal:
sudo nano /etc/resolv.conf
Add each nameserver on a separate line, prefaced with nameserver and a space. As an
example, the resolv.conf conguration for a network that uses Google’s publicly accessible nameservers to resolve domain names would appear like this:
nameserver 8.8.8.8
nameserver 8.8.4.4
You’ll notice that the nameserver addresses need to be supplied as IP addresses, rather than
domain names. If you provided domain names instead, the Pi would enter an innite loop of
trying to nd a nameserver to ask how it can nd the nameservers.
Save the le by pressing CTRL + O, and then quit nano by pressing CTRL + X. Restart the
networking interface by typing the following:
sudo /etc/init.d/networking restart
CHAPTER 5 NETWORK CONFIGURATION
77
en test the settings by either opening a web browser or using the following ping command (see Figure 5-2):
ping -c 1 www.raspberrypi.org
F -:
A successful test
of networking
on the
Raspberry Pi
Model B
Wireless Networking
Although no current models of the Raspberry Pi include Wi-Fi networking hardware onboard,
it’s possible to add wireless connectivity with a simple USB Wi-Fi adapter. However, you will
need to congure the adapter before you can use it to get your Pi online.
TIP
USB Wi-Fi adapters are very power-hungry. If you connect one directly to the Pi’s USB port,
it may not work. Instead, connect a powered USB hub to the Pi, and then insert the Wi-Fi
adapter into that.
78
PAR T I CONNECTING THE BOARD
Before you start to set up the wireless interface, you’ll need to know the Service Set Identier
(SSID)—also known as the network name—of the wireless router to which you want to con-
nect, along with the type of encryption in use and the password required. You’ll also need to
know what type of wireless network it is. A USB adapter designed for 802.11a Wi-Fi may not
connect to an 802.11g network, and vice versa.
Installing Firmware
In order for the USB wireless adapter to be addressed by the system, a software bundle
known as a rmware is required. While some distributions include a selection of the most
common Wi-Fi rmware installed by default, others do not. Raspbian includes most common wireless rmware packages, and if this is the operating system you are using you can
skip ahead to the section on “Connecting to a Wireless Network via wpa_gui”; otherwise,
read on for instructions on installing rmware packages.
In order to download the rmware les, the Pi must be connected to the Internet. If you can
spare a wired port on your router or gateway for a few minutes, that’s not a problem. However,
if wireless is your only way of getting online, you’ll need to manually download the rmware
installation package on a dierent computer, and then transfer it across to the Pi by either
copying it to the Pi’s SD card or connecting an external storage device such as a USB ash drive.
To nd the correct rmware le to download, you’ll need to know what type of wireless
adapter you have. Although various companies sell branded USB wireless adapters, the number of companies that actually manufacture the components is a lot smaller. Several dierent manufacturers may use the same type of chip inside their USB wireless adapters, making
them all compatible with the same rmware. As a result, the labelling on a device or its packaging is not enough to know which rmware you should install. Instead, you’ll need to connect the device to the Pi and check the kernel ring buer for error messages. If you’ve already
connected the wireless adapter as instructed in Chapter 2, “Getting Started with the
Raspberry Pi”, you can continue. If not, connect the adapter now.
e kernel ring buer is a special portion of memory used by the Linux kernel to store its
human-readable output. It’s an important part of the Linux operating system: the text
ashes by too quickly to read while the Pi boots, so it’s critical that users are able to view the
messages at a later date to read errors and diagnose problems.
With the adapter connected but no wireless rmware packages installed, the kernel will print a
series of error messages to the ring buer. To read these messages, you can use the dmesg command to print the contents of the buer to the screen. At the terminal, or at the console if you
haven’t loaded the desktop environment, simply type the following command to view the buer:
dmesg
CHAPTER 5 NETWORK CONFIGURATION
is will print out the entire kernel ring buer, which will contain all messages output by the
kernel since the Pi was switched on. If the Pi has been running a while, that can be a lot of
text. To locate error messages particular to the wireless adapter, it can help to send the output of dmesg through a tool called grep. Using grep, you can search through the buer for
text relating to missing rmware. By piping the output of dmesg through grep with a search
term, things become signicantly clearer. Type the following at the terminal:
dmesg -t | grep ^usb
e | symbol is known as a pipe, and it tells Linux to send the output of one program—which
would normally go to a le or the screen—to the input of another. Multiple programs can be
chained this way. In this example, grep is being told to search through the output of
dmesg—the screens full of text from the earlier command—for any use of the term usb at
the start of the line (denoted by the ^ character).
79
e exact output of that search will depend on the manufacturer of your USB wireless
adapter. In Figure 5-3, the output is shown with a Zyxel NWD2015 Wireless USB Adapter
connected to the Pi.
F -:
Searching the
kernel ring
buer for usb
with a Zyxel
wireless adapter
connected
80
PAR T I CONNECTING THE BOARD
e important part of this output is the line that reads Manufacturer. In the case of the
example Zyxel NWD2105, this reads Ralink, which is the company that makes the actual
chip found inside Zyxel USB wireless adapter. It’s this company’s rmware that must be
installed for the wireless adapter to work.
TIP
If you couldn’t nd anything using usb as a search term, you can try the same command using
the search term firmware, wlan or wireless. If you still can’t see anything useful, type
lsusb for a list of all USB devices connected to the system.
Using the manufacturer name from dmesg, search for the rmware les using the
apt-cache search tool introduced earlier in this chapter. For the example Zyxel NWD2015
adapter, the apt-cache command would be:
apt-cache search ralink
If apt-cache fails to nd the rmware, you may need to make a guess based on the rmware packages in the following list. Don’t worry if you install the wrong one—any rmware
can be quickly uninstalled using apt-get remove, and having multiple rmware packages
does no harm. e following wireless rmware packages are available in the recommended
Raspbian distribution on the Raspberry Pi:
❍ atmel-rmware—for devices based on the Atmel AT76C50X chipset
❍ rmware-atheros—for devices based on Atheros chipsets
❍ rmware-brcm80211—for devices based on Broadcom chipsets
❍ rmware-intelwimax—for devices based on Intel’s WiMAX chipsets
❍ rmware-ipw2x00—for Intel Pro Wireless adapters (including 2100, 2200 and 2915)
❍ rmware-iwlwi—for other Intel wireless adapters (including 3945, 4965 and the
5000 series)
❍ rmware-ralink—for devices based on Ralink chipsets
❍ rmware-realtek—for devices based on Realtek chipsets
❍ zd1211-rmware—for devices based on the ZyDAS 1211 chipset
CHAPTER 5 NETWORK CONFIGURATION
e rmware for the example Zyxel wireless adapter is provided by the firmware-ralink
package in this list. is package can be installed using apt-get, but only while the Pi is
connected to the Internet through its wired Ethernet port or a USB Ethernet adapter.
When connected, install the rmware by typing the following:
sudo apt-get install firmwarepackage
Replace firmwarepackage in this command with the name of the package that you found
by using apt-cache. For the example Zyxel NWD2105, the full command would be sudo
apt-get install firmware-ralink.
Installing Wireless Firmware Ofine
If you can’t connect the Pi to the Internet using any method other than a wireless connection, you’ll need to download the rmware on a different computer. In a web browser, load
a search engine and type the name of the rmware package followed by the name of the
distribution you’re using and its version.
81
If you’re using the recommend Raspbian distribution, the rmware for the Ralink RT2x00
chipset from the example can be found by searching for firmware-ralink debian wheezy. The search will lead you to a package le to download. In the case of Debian and
Raspbian, this is a .deb le. For Pidora, the same rmware is provided as a .rpm le.
Download this le, and then copy it to the Pi’s SD card in the /home/pi directory, or onto
a USB ash drive or other external storage device. Load the Pi, and then when it is time to
install the rmware, replace the package name with the name of the le you downloaded.
For the example Zyxel NWD2105 card, the command would be the following:
sudo apt-get install firmware-ralink_0.35_all.deb
With the rmware installed, disconnect the USB wireless adapter and reconnect it to the Pi.
is will restart the kernel’s search for the rmware les, which it will now be able to nd.
ese les will remain in place, and load automatically when the USB wireless adapter is connected. You will only have to perform the installation process once.
82
PAR T I CONNECTING THE BOARD
Connecting to a Wireless Network via wpa_gui
e simplest way to connect to a wireless network from the Raspberry Pi is to use the
wpa_gui tool. is provides a graphical user interface for software that would otherwise
require the use of the terminal, and is accessed from the desktop by double-clicking on the
icon labelled WiFi Cong.
e main wpa_gui window has two drop-down lists, labelled Adapter and Network (see
Figure 5-4). e rst should be already lled with your wireless network dongle’s identier,
wlan0. If you have more than one dongle connected, you can click on the arrow to choose
which you are conguring; if nothing is listed, turn back a few pages and make sure the rmware for your dongle is correctly installed.
F -:
e wpa_gui
application
CHAPTER 5 NETWORK CONFIGURATION
Finding a wireless network is a process known as scanning, which in wpa_gui is activated by
clicking the Scan button at the bottom-right of the window. is will pop up a second window, showing the results of the scan (see Figure 5-5). Look through the list to nd the name
of your wireless network—which, hopefully, will also be the strongest in the list, as shown by
the signal column—and double-click on its entry.
83
F -:
Choosing a
wireless network
in wpa_gui
e window that appears when you double-click on a network asks for several dierent settings, which will depend on the type of network to which you are trying to connect (see
Figure 5-6). For an unencrypted network—which is a bad thing to be running as it allows
anybody within range to use your network—wpa_gui will require no additional settings;
just click the Add button at the bottom.
If your network uses encryption, you will need to choose the type of encryption, using the
Authentication and Encryption drop-down lists. In most cases, wpa_gui will have selected
these values automatically. If so, simply type in the password—known as a pre-shared key—
in the box labelled PSK and click Add . If the network encryption is Wired Equivalent Privacy
(WEP) rather than the more secure Wireless Protected Access (WPA) type, you will need to ll
in at least one key in the WEP keys section. If you use an authenticated enterprise network,
you can also add the details of your identity, password and encryption certicate, but most
home users will not need these elds.
84
PAR T I CONNECTING THE BOARD
F -:
Adding a
network to
wpa_gui
If your network includes a Wi-Fi Protected Setup (WPS) option, you can click the WPS button at the
bottom-left of the window to perform a one-click setup. Simply press the WPS button on your
router or access point, and then click the WPS button in wpa_gui to connect automatically.
When you have lled in the details of your network, click Add. is will close the window and
return you to the main wpa_gui window—but now the Network drop-down should have
an entry, named after your wireless access point. At this point, wpa_gui will automatically
connect you to the wireless network and an IP address should appear at the bottom of the
screen (see Figure 5-7).
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.