SlideShare a Scribd company logo
1 of 152
Download to read offline
Raspberry Pi® User Guide
Table of Contents
Introduction
Programming is fun!
A bit of history
So what can you do with the Raspberry Pi?
Part I: Connecting the Board
Chapter 1: Meet the Raspberry Pi
ARM vs. x86
Windows vs. Linux
Getting Started with the Raspberry Pi
Connecting a Display
Connecting Audio
Connecting a Keyboard and Mouse
Flashing the SD Card
Connecting External Storage
Connecting the Network
Connecting Power
Chapter 2: Linux System Administration
Linux: An Overview
Linux Basics
Introducing Debian
Using External Storage Devices
Creating a New User Account
File System Layout
Logical Layout
Physical Layout
Installing and Uninstalling Software
Finding Software
Installing Software
Uninstalling Software
Upgrading Software
Chapter 3: Troubleshooting
Keyboard and Mouse Diagnostics
Power Diagnostics
Display Diagnostics
Boot Diagnostics
Network Diagnostics
The Emergency Kernel
Chapter 4: Network Configuration
Wired Networking
Wireless Networking
Chapter 5: Partition Management
Creating a New Partition
Resizing Existing Partitions
Automatic Resizing
Manual Resizing
Moving to a Bigger SD Card
Imaging from Linux
Imaging from OS X
Imaging from Windows
Chapter 6: Configuring the Raspberry Pi
Hardware Settings—config.txt
Modifying the Display
Boot Options
Overclocking the Raspberry Pi
Disabling L2 Cache
Enabling Test Mode
Memory Partitioning—start.elf
Software Settings—cmdline.txt
Part II: Using the Pi as a Media Centre, Productivity Machine and Web Server
Chapter 7: The Pi as a Home Theatre PC
Playing Music at the Console
Dedicated HTPC with Rasbmc
Streaming Internet Media
Streaming Local Network Media
Configuring Rasbmc
Chapter 8: The Pi as a Productivity Machine
Using Cloud-Based Apps
Using OpenOffice.org
Image Editing with The Gimp
Chapter 9: The Pi as a Web Server
Installing a LAMP Stack
Installing WordPress
Part III: Programming and Hacking
Chapter 10: An Introduction to Scratch
Introducing Scratch
Example 1: Hello World
Example 2: Animation and Sound
Example 3: A Simple Game
Robotics and Sensors
Sensing with the PicoBoard
Robotics with LEGO
Further Reading
Chapter 11: An Introduction to Python
Introducing Python
Example 1: Hello World
Example 2: Comments, Inputs, Variables and Loops
Example 3: Gaming with pygame
Example 4: Python and Networking
Further Reading
Chapter 12: Hardware Hacking
Electronic Equipment
Reading Resistor Colour Codes
Sourcing Components
Online Sources
Offline Sources
Hobby Specialists
The GPIO Port
UART Serial Bus
I²C Bus
SPI Bus
Using the GPIO Port in Python
Installing the GPIO Python Library
GPIO Output: Flashing an LED
GPIO Input: Reading a Button
Moving Up From the Breadboard
A Brief Guide to Soldering
Chapter 13: Add-on Boards
Ciseco Slice of Pi
Adafruit Prototyping Pi Plate
Fen Logic Gertboard
Part IV: Appendixes
Appendix A: Python Recipes
Appendix B: HDMI Display Modes
Raspberry Pi® User Guide
Eben Upton and Gareth Halfacree
Raspberry Pi® User Guide
This edition first published 2012
© 2012 Eben Upton and Gareth Halfacree
Registered office
John Wiley & Sons Ltd., The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United
Kingdom
For details of our global editorial offices, 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.
The right of the authors to be identified 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. The publisher is not associated with any product or
vendor mentioned in this book. This 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 and
Sons, Ltd. and/or its affiliates 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-46446-5 (pbk); ISBN 978-1-118-46448-9 (ebk); ISBN 978-1-118-46447-2 (ebk); ISBN
978-1-118-46449-6 (ebk)
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
Assistant Editor
Ellie Scott
Project Editor
Kathryn Duggan
Copy Editor
Kathryn Duggan
Technical Editor
Omer Kilic
Editorial Manager
Jodi Jensen
Senior Project Editor
Sara Shlaer
Editorial Assistant
Leslie Saxman
Marketing
Associate Marketing Director
Louise Breinholt
Marketing Manager
Lorna Mein
Senior Marketing Executive
Kate Parrett
Composition Services
Compositor
Erin Zeltner
Proofreader
Wordsmith Editorial
Indexer
BIM Indexing & Proofreading Services
About the Authors
EbenUptonis a founder and trustee ofthe RaspberryPiFoundation, and serves as its Executive Director. He is responsible for
the overallsoftware and hardware architecture ofthe RaspberryPi, and for the Foundation's relationships withits keysuppliers
and customers. Inanearlier life, he founded two successfulmobile games and middleware companies, Ideaworks 3d Ltd. and
PodfunLtd., and held the post ofDirector ofStudies for Computer Science at St John's College, Cambridge. He holds a BA, a
PhDand anMBAfromthe UniversityofCambridge.
Inhis dayjob, Ebenworks for Broadcomas anASIC architect and generaltroublemaker.
GarethHalfacree is a freelance technologyjournalist and the co-author ofthe RaspberryPiUser Guide alongside project co-
founder EbenUpton. Formerlya systemadministrator workinginthe educationsector, Gareth’s passionfor opensource
projects has followed himfromone career to another, and he canoftenbe seenreviewing, documentingor evencontributingto
projects includingGNU/Linux, LibreOffice, Fritzingand Arduino. He is also the creator ofthe Sleepduino and Burnduino open
hardware projects, whichextend the capabilities ofthe Arduino electronics prototypingsystem. Asummaryofhis current work
canbe found at http://freelance.halfacree.co.uk.
For Liz, who made it all possible.
—Eben
For my father, the enthusiastic past, and my daughter, the exciting future.
—Gareth
Introduction
“Childrentoday are digitalnatives”, said a manI got talkingto at a fireworks partylast year. “I don’t understand whyyou’re
makingthis thing. Mykids knowmore about settingup our PC thanI do.”
I asked himiftheycould program, to whichhe replied:“Whywould theywant to? The computers do allthe stufftheyneed for
themalready, don’t they? Isn’t that the point?”
As it happens, plentyofkids todayaren’t digitalnatives. We have yet to meet anyofthese imagined wild digitalchildren,
swingingfromropes oftwisted-pair cable and chantingwar songs innicelyparsed Python. Inthe RaspberryPiFoundation’s
educationaloutreachwork, we do meet a lot ofkids whose entire interactionwithtechnologyis limited to closed platforms with
graphicaluser interfaces (GUIs) that theyuse to playmovies, do a spot ofword-processed homework and playgames. They
canbrowse the web, upload pictures and video, and evendesignweb pages. (They’re oftenbetter at settingthe satellite TVbox
thanMumor Dad, too.) It’s a usefultoolset, but it’s shockinglyincomplete, and ina countrywhere 20%ofhouseholds stilldon’t
have a computer inthe home, eventhis toolset is not available to allchildren.
Despite the most fervent wishes ofmynewacquaintance at the fireworks party, computers don’t programthemselves. We need
anindustryfullofskilled engineers to keep technologymovingforward, and we need youngpeople to be takingthose jobs to fill
the pipeline as older engineers retire and leave the industry. But there’s muchmore to teachinga skilllike programmatic thinking
thanbreedinga newgenerationofcoders and hardware hackers. Beingable to structure your creative thoughts and tasks in
complex, non-linear ways is a learned talent, and one that has huge benefits for everyone who acquires it, fromhistorians to
designers, lawyers and chemists.
Programming is fun!
It’s enormous, rewarding, creative fun. Youcancreate gorgeous intricacies, as wellas (muchmore gorgeous, inmyopinion)
clever, devastatinglyquick and deceptivelysimple-lookingroutes through, under and over obstacles. Youcanmake stuffthat’ll
have other people lookingonjealously, and that’llmake youfeelwonderfullysmugallafternoon. Inmydayjob, where I design
the sort ofsiliconchips that we use inthe RaspberryPias a processor and work onthe low-levelsoftware that runs onthem, I
basicallyget paid to sit around alldayplaying. What could be better thanequippingpeople to be able to spend a lifetime doing
that?
It’s not evenas ifwe’re comingfroma positionwhere childrendon’t want to get involved inthe computer industry. Abigkick
up the backside came a fewyears ago, whenwe were movingquite slowlyonthe RaspberryPiproject. Allthe development
work onRaspberryPiwas done inthe spare evenings and weekends ofthe Foundation’s trustees and volunteers—we’re a
charity, so the trustees aren’t paid bythe Foundation, and we allhave full-time jobs to paythe bills. This meant that occasionally,
motivationwas hard to come bywhenallI wanted to do inthe eveningwas slump infront ofthe Arrested Development boxed
set witha glass ofwine. One evening, whennot slumping, I was talkingto a neighbour’s nephewabout the subjects he was
takingfor his GeneralCertificate ofSecondaryEducation(GCSE, the Britishsystemofpublic examinations takeninvarious
subjects fromthe age ofabout 16), and I asked himwhat he wanted to do for a livinglater on.
“I want to write computer games”, he said.
“Awesome. What sort ofcomputer do youhave at home? I’ve got some programmingbooks youmight be interested in.”
“AWiiand anXbox.”
Ontalkingwithhima bit more, it became clear that this perfectlysmart kid had never done anyrealprogrammingat all; that there
wasn’t anymachine that he could programinthe house; and that his informationand communicationtechnology(ICT) classes—
where he shared a computer and was taught about web page design, usingspreadsheets and word processing—hadn’t really
equipped himto use a computer eveninthe barest sense. But computer games were a passionfor him(and there’s nothing
peculiar about wantingto work onsomethingyou’re passionate about). So that was what he was hopingthe GCSEsubjects
he’d chosenwould enable himto do. He certainlyhad the artistic skills that the games industrylooks for, and his maths and
science marks weren’t bad. But his schoolinghad skirted around anyprogramming—there were no Computingoptions onhis
syllabus, just more ofthe same ICTclasses, withits emphasis onend users rather thanprogramming. And his home interactions
withcomputingmeant that he stood a vanishinglysmallchance ofacquiringthe skills he needed inorder to do what he really
wanted to do withhis life.
This is the sort ofsituationI want to see the back of, where potentialand enthusiasmis squandered to no purpose. Now,
obviously, I’mnot monomaniacalenoughto imagine that simplymakingthe RaspberryPiis enoughto effect allthe changes that
are needed. But I do believe that it canact as a catalyst. We’re alreadyseeingbigchanges inthe UK schools’ curriculum, where
Computingis arrivingonthe syllabus and ICTis beingreshaped, and we’ve seena massive change inawareness ofa gap inour
educationaland culturalprovisionfor kids just inthe short time since the RaspberryPiwas launched.
Too manyofthe computingdevices a child willinteract withdailyare so locked downthat theycan’t be used creativelyas a tool
—eventhoughcomputingis a creative subject. Tryusingyour iPhone to act as the brains ofa robot, or gettingyour PS3 to play
a game you’ve written. Sure, youcanprogramthe home PC, but there are significant barriers indoingthat whicha lot ofchildren
don’t overcome:the need to download specialsoftware, and havingthe sort ofparents who aren’t worried about youbreaking
somethingthat theydon’t knowhowto fix. And plentyofkids aren’t evenaware that doingsucha thingas programmingthe
home PC is possible. Theythink ofthe PC as a machine withnice clickyicons that give youaneasywayto do the things you
need to do so youdon’t need to think much. It comes ina sealed box, whichMumand Dad use to do the bankingand which
willcost lots ofmoneyto replace ifsomethinggoes wrong!
The RaspberryPiis cheap enoughto buywitha fewweeks’ pocket money, and youprobablyhave allthe equipment youneed
to make it work:a TV, anSDcard that cancome fromanold camera, a mobile phone charger, a keyboard and a mouse. It’s
not shared withthe family; it belongs to the kid; and it’s smallenoughto put ina pocket and take to a friend’s house. If
somethinggoes wrong, it’s no bigdeal—youjust swap out a newSDcard and your RaspberryPiis factory-newagain. And all
the tools, environments and learningmaterials that youneed to get started onthe long, smoothcurve to learninghowto program
your RaspberryPiare right there, waitingfor youas soonas youturnit on.
A bit of history
I started work ona tiny, affordable, bare-bones computer about sixyears ago, whenI was a Director ofStudies inComputer
Science at Cambridge University. I’d received a degree at the UniversityComputer Lab as wellas studyingfor a PhDwhile
teachingthere, and over that period, I’d noticed a distinct decline inthe skillset ofthe youngpeople who were applyingto read
Computer Science at the Lab. Froma positioninthe mid-1990s, when17-year-olds wantingto read Computer Science had
come to the Universitywitha groundinginseveralcomputer languages, knewa bit about hardware hacking, and ofteneven
worked inassemblylanguage, we graduallyfound ourselves ina positionwhere, by2005, those kids were arrivinghavingdone
some HTML—witha bit ofPHP and CascadingStyle Sheets ifyouwere lucky. Theywere stillfearsomelyclever kids withlots
ofpotential, but their experience withcomputers was entirelydifferent fromwhat we’d beenseeingbefore.
The Computer Science course at Cambridge includes about 60 weeks oflecture and seminar time over three years. Ifyou’re
usingthe whole first year to bringstudents up to speed, it’s harder to get themto a positionwhere theycanstart a PhDor go into
industryover the next two years. The best undergraduates—the ones who performed the best at the end oftheir three-year
course—were the ones who weren’t just programmingwhenthey’d beentold to for their weeklyassignment or for a class
project. Theywere the ones who were programmingintheir spare time. So the initialidea behind the RaspberryPiwas a very
parochialone witha verytight (and prettyunambitious) focus:I wanted to make a toolto get the smallnumber ofapplicants to
this smalluniversitycourse a kick start. Mycolleagues and I imagined we’d hand out these devices to schoolkids at opendays,
and iftheycame to Cambridge for aninterviewa fewmonths later, we’d ask what they’d done withthe free computer we’d
giventhem. Those who had done somethinginterestingwould be the ones that we’d be interested inhavinginthe program. We
thought maybe we’d make a fewhundred ofthese devices, or best case, a lifetime productionrunofa fewthousand.
Ofcourse, once work was seriouslyunderwayonthe project, it became obvious that there was a lot more we could address
witha cheap little computer like this. What we started withis a longwayindeed fromthe RaspberryPiyousee today. I began
bysolderingup the longest piece ofbreadboard youcanbuyat MaplinwithanAtmelchip at our kitchentable, and the first
crude prototypes used cheap microcontroller chips to drive a standard-definitionTVset directly. Withonly512 K ofRAM, and
a fewMIPS ofprocessingpower, these prototypes were verysimilar inperformance to the original8-bit microcomputers. It was
hard to imagine these machines capturingthe imaginations ofkids used to moderngames consoles and iPads.
There had beendiscussions at the UniversityComputer Lab about the generalstate ofcomputer education, and whenI left the
Lab for a non-academic job inthe industry, I noticed that I was seeingthe same issues inyoungjob applicants as I’d beenseeing
at the University. So I got together withmycolleagues Dr Rob Mullins and Professor AlanMycroft (two colleagues fromthe
Computer Lab), Jack Lang(who lectures inentrepreneurship at the University), Pete Lomas (a hardware guru) and David
Braben(a Cambridge games industryleadinglight withaninvaluable address book), and over beers (and, inJack’s case, cheese
and wine), we set up the RaspberryPiFoundation—a little charitywithbigideas.
Why “Raspberry Pi”?
We get askeda lot where the name “Raspberry Pi” came from. Bits of the name came fromdifferent trustees. It’s one of the very fewsuccessful bits
of design by committee I’ve seen, andto be honest, Ihatedit at first. (Ihave since come to love the name, because it works really well—but it took a
bit of getting usedto since I’dbeen calling the project the “ABC Micro” in my headforyears.) It’s “Raspberry” because there’s a long tradition of
fruit names in computercompanies (besides the obvious, there are the oldTangerine andApricot computers—andwe like to think of the Acorn as a
fruit as well). “Pi” is a mangling of “Python”, which we thought early on in development wouldbe the only programming language available on a
much less powerful platformthan the Raspberry Pi we endedupwith. As it happens, we still recommendPython as ourfavourite language for
learning anddevelopment, but there is a worldof otherlanguage options you can explore on the Raspberry Pi too.
Inmynewrole as a chip architect at Broadcom, a bigsemiconductor company, I had access to inexpensive but high-performing
hardware produced bythe companywiththe intentionofbeingused inveryhigh-end mobile phones—the sort withthe HD
video and the 14-megapixelcameras. I was amazed bythe difference betweenthe chips youcould buyfor $10 as a small
developer, and what youcould buyas a cell-phone manufacturer for roughlythe same amount ofmoney:generalpurpose
processing, 3Dgraphics, video and memorybundled into a single BGApackage the size ofa fingernail. These microchips
consume verylittle power, and have bigcapabilities. Theyare especiallygood at multimedia, and were alreadybeingused by
set-top boxcompanies to playhigh-definitionvideo. Achip like this seemed the obvious next step for the shape the RaspberryPi
was taking, so I worked ontapingout a low-cost variant that had anARM microprocessor onboard and could handle the
processinggrunt we needed.
We felt it was important to have a wayto get kids enthusiastic about usinga RaspberryPieveniftheydidn’t feelvery
enthusiastic about programming. Inthe 1980s, ifyouwanted to playa computer game, youhad to boot up a boxthat went
“bing”and fed youa command prompt. It required typinga little bit ofcode just to get started, and most users didn’t ever go
beyond that—but some did, and got beguiled into learninghowto programbythat little bit ofinteraction. We realised that the
RaspberryPicould work as a verycapable, verytiny, verycheap modernmedia centre, so we emphasised that capabilityto
suck inthe unwary—withthe hope that they’d pick up some programmingwhile they’re at it.
After about five years’ hard grind, we had created a verycute prototype board, about the size ofa thumb drive. We included a
permanent camera module ontop ofthe board to demonstrate the sort ofperipherals that caneasilybe added, and brought it
alongto a number ofmeetings withthe BBC’s R&Ddepartment. Those ofus who grewup inthe UK inthe 1980s had learned a
lot about 8-bit computingfromthe BBC Microcomputer and the ecosystemthat had grownup around it—withBBC-produced
books, magazines and TVprogrammes—so I’d hoped that theymight be interested indevelopingthe RaspberryPifurther. But
as it turned out, somethinghas changed since we were kids:various competitionlaws inthe UK and the EUmeant that “the
Beeb”couldn’t become involved inthe waywe’d hoped. Ina last-ditchattempt to get somethingorganised withthem, we
ditched the R&Ddepartment idea and David (he ofthe giant address book) organised a meetingwithRoryCellan-Jones, a
senior techjournalist, inMay2011. Rorydidn’t hold out muchhope for partnership withthe BBC, but he did ask ifhe could
take a video ofthe little prototype board withhis phone, to put onhis blog.
The next morning, Rory’s video had gone viral, and I realised that we had accidentallypromised the world that we’d make
everybodya $25 computer.
While Rorywent offto write another blogpost onexactlywhat it is that makes a video go viral, we went offto put our thinking
caps on. That original, thumb-drive-sized prototype didn’t fit the bill:withthe camera included as standard, it was waytoo
expensive to meet the cost modelwe’d suggested (the $25 figure came frommystatement to the BBC that the RaspberryPi
should cost around the same as a text book, and is a splendid demonstrationofthe fact that I had no idea howmuchtext books
cost these days), and the tinyprototype modeldidn’t have enoughroomaround its peripheryfor allthe ports we needed to
make it as useable as we wanted it to be. So we spent a year workingonengineeringthe board to lower cost as muchas
possible while retainingallthe features we wanted (engineeringcost downis a harder job thanyoumight think), and to get the
RaspberryPias useable as possible for people who might not be able to afford muchinthe wayofperipherals.
We knewwe wanted the RaspberryPito be used withTVs at home, just like the ZXSpectruminthe 1980s, savingthe user the
cost ofa monitor. But not everybodyhas access to anHDMI television, so we added a composite port to make the Raspberry
Piwork withanold cathode-raytelevisioninstead since SDcards are cheap and easyto find. We decided against microSDas
the storage medium, because the little fingernail-sized cards are so flimsyinthe hands ofchildrenand so easyto lose. And we
went throughseveraliterations ofpower supply, endingup witha micro USBcable. Recently, micro USBbecame the standard
charger cable for mobile telephones across the EU(and it’s becomingthe standard everywhere), whichmeans the cables are
becomingmore and more ubiquitous, and inmanycases, people alreadyhave themat home.
Bythe end of2011, witha projected Februaryrelease date, it was becomingobvious to us that things were movingfaster, and
demand was higher, thanwe were ever goingto be able to cope with. The initiallaunchwas always aimed at developers, with
the educationallaunchplanned for later in2012. We have a smallnumber ofverydedicated volunteers, but we need the wider
Linuxcommunityto help us prepare a software stack and ironout anyearly-life niggles withthe board before releasinginto the
educationalmarket. We had enoughcapitalinthe Foundationto buythe parts for and build 10,000 RaspberryPis over a period
ofa monthor so, and we thought that the people inthe communitywho would be interested inanearlyboard would come to
around that number. Fortunatelyand unfortunately, we’d beenreallysuccessfulinbuildinga bigonline communityaround the
device, and interest wasn’t limited to the UK, or to the educationalmarket. Tenthousand was lookingless and less realistic.
OurCommunity
The Raspberry Pi community is one of the things we’re proudest of. We startedwith a very bare-bones blog at www.raspberrypi.org just afterRory’s
May 2011 video, andput upa forumon the same website shortly afterthat. That forumnowhas more than 20,000 members—between themthey’ve
contributedmore than 100,000 posts of wit andwisdomabout the Raspberry Pi. If there’s any question, no matterhowabstruse, that you want to ask
about the Raspberry Pi orabout programming in general, someone there will have the answer(if it’s not in this book, you’ll findit in the forums).
Part of my jobat Raspberry Pi involves giving talks to hackergroups, computing conferences, teachers, programming collectives andthe like, and
there’s always someone in the audience who has talkedto me orto my wife Liz (who runs the community) on the Raspberry Pi website—andsome
of these people have become goodfriends of ours. The Raspberry Pi website gets aroundone request every single secondof the day.
There are nowhundreds of fan sites out there. There’s also a fan magazine calledThe MagPi (a free downloadfromwww.themagpi.com), which is
producedmonthly by community members, with type-in listings, lots of articles, project guides, tutorials andmore. Type-in games in magazines and
books providedan easy route into programming forme—my earliest programming experience with the BBC Micro was of modifying a type-in
helicoptergame to addenemies andpick-ups.
We blog something interesting about the device at www.raspberrypi.org at least once every day. Come andjoin in the conversation!
There were 100,000 people onour mailinglist wantinga RaspberryPi—and theyallput anorder inondayone! Not
surprisingly, this brought up a fewissues.
First off, there are the inevitable paper cuts you’re goingto get boxingup 100,000 little computers and mailingthemout—and
the fact was that we had absolutelyno moneyto hire people to do this for us. We didn’t have a warehouse—we had Jack’s
garage. There was no waywe could raise the moneyto build 100,000 units at once—we’d envisaged makingtheminbatches of
2,000 everycouple ofweeks, which, withthis levelofinterest, was goingto take so longthat the thingwould be obsolete before
we managed to fulfilallthe orders. Clearly, manufacturingand distributionwere somethingwe were goingto have to give up on
and hand over to somebodyelse who alreadyhad the infrastructure and capitalto do that, so we got intouchwithelement14
and RS Components, bothUK microelectronics suppliers withworldwide businesses, and contracted withthemto do the actual
manufacture and distributionside ofthings worldwide so we could concentrate ondevelopment and the RaspberryPi
Foundation’s charitable goals.
Demand onthe first daywas stillso large that RS and element14’s websites bothcrashed for most ofthe day—at one point in
the day, element14 were gettingsevenorders a second, and for a couple ofhours onFebruary29, Google showed more
searches were made worldwide for “RaspberryPi”thanwere made for “LadyGaga”. I’mwritingthis inearlyJune 2012, and
orders inthe three months since we opened for business have topped halfa millionunits, eventhoughwe’re stillat a point when
neither companywillsellyoumore thanone RaspberryPi(they’re tryingto get rid oftheir order backlogs before theyturnonthe
abilityto multiorder). At this point, ifwe’d gone withour originalplans, we’d have made 100 or so ofthese devices for
Universityopendays, and that would have beenit.
There is nothingthat affects the blood pressure quite like accidentallyendingup runninga large computer company!
So what can you do with the Raspberry Pi?
This book explores a number ofthings youcando withyour RaspberryPi, fromcontrollinghardware withPython, to usingit as
a media centre, or buildinggames inScratch. The beautyofthe RaspberryPiis that it’s just a verytinygeneral-purpose
computer (whichmaybe a little slower thanyou’re used to for some desktop applications, but muchbetter at some other stuff
thana regular PC), so youcando anythingyoucould do ona regular computer withit. Inaddition, the RaspberryPihas
powerfulmultimedia and 3Dgraphics capabilities, so it has the potentialto be used as a games platform, and we verymuchhope
to see people startingto write games for it.
We think physicalcomputing—buildingsystems usingsensors, motors, lights and microcontrollers—is somethingthat gets
overlooked infavour ofpure software projects ina lot ofinstances, and it’s a shame, because physicalcomputingis massive fun.
To the extent that there’s anychildren’s computingmovement at the moment, it’s a physicalcomputingmovement. The LOGO
turtles that represented physicalcomputingwhenwe were kids are nowfightingrobots, quadcopters or parent-sensingbedroom
doors, and we love it. However, the lack ofGeneralPurpose Input/Output (GPIO) onhome PCs is a realhandicap for many
people gettingstarted withrobotics projects. The RaspberryPiexposes GPIO so youcanget to work straight away.
I keep beingsurprised byideas the communitycomes up withwhichwouldn’t have crossed mymind ina thousand years:the
Australianschoolmeteor-trackingproject; the BoreattonScouts inthe UK and their robot, whichis controlled via an
electroencephalographyheadset (the world’s first robot controlled byScoutingbrainwaves); the familywho are buildinga robot
vacuumcleaner. And I’ma realspace cadet, so readingabout the people sendingRaspberryPis into near-earthorbit onrockets
and balloons gives me goosebumps.
Success for us would be another 1,000 people everyyear takingup Computer Science at the universitylevelinthe UK. That
would not onlybe beneficialfor the country, the software and hardware industries, and the economy; but it would be evenmore
beneficialfor everyone ofthose 1,000 people, who, I hope, discover that there’s a whole world ofpossibilities and a great deal
offunto be had out there. Buildinga robot whenyou’re a kid cantake youto places younever imagined—I knowbecause it
happened to me!
—EbenUpton
Part I: Connecting the Board
Chapter 1:Meet the RaspberryPi
Chapter 2:LinuxSystemAdministration
Chapter 3:Troubleshooting
Chapter 4:Network Configuration
Chapter 5:PartitionManagement
Chapter 6:Configuringthe RaspberryPi
Chapter 1: Meet the Raspberry Pi
YourRaspberry Pi board is a miniature marvel, packingconsiderable computingpower into a footprint no larger thana credit
card. It’s capable ofsome amazingthings, but there are a fewthings you’re goingto need to knowbefore youplunge head-first
into the bramble patch.
If you’re eagerto get started, skipaheada couple of pages to findout howto connect yourRaspberry Pi to a display, keyboardandmouse.
ARM vs. x86
The processor at the heart ofthe RaspberryPisystemis a BroadcomBCM2835 system-on-chip (SoC) multimedia processor.
This means that the vast majorityofthe system’s components, includingits centraland graphics processingunits alongwiththe
audio and communications hardware, are built onto that single component hiddenbeneaththe 256 MBmemorychip at the
centre ofthe board (see Figure 1-1).
It’s not just this SoC designthat makes the BCM2835 different to the processor found inyour desktop or laptop, however. It
also uses a different instructionset architecture (ISA), knownas ARM.
Figure 1-1:The BCM2835 SoC, located beneatha Hynixmemorychip
Developed byAcornComputers back inthe late 1980s, the ARM architecture is a relativelyuncommonsight inthe desktop
world. Where it excels, however, is inmobile devices:the phone inyour pocket almost certainlyhas at least one ARM-based
processingcore hiddenawayinside. Its combinationofa simple reduced instructionset (RISC) architecture and lowpower
drawmake it the perfect choice over desktop chips withhighpower demands and complexinstructionset (CISC) architectures.
The ARM-based BCM2835 is the secret ofhowthe RaspberryPiis able to operate onjust the 5V1Apower supplyprovided
bythe onboard micro-USBport. It’s also the reasonwhyyouwon’t find anyheat-sinks onthe device:the chip’s lowpower
drawdirectlytranslates into verylittle waste heat, evenduringcomplicated processingtasks.
It does, however, meanthat the RaspberryPiisn’t compatible withtraditionalPC software. The majorityofsoftware for
desktops and laptops is built withthe x86 instructionset architecture inmind, as found inprocessors fromthe likes ofAMD,
Inteland VIA. As a result, it won’t runonthe ARM-based RaspberryPi.
The BCM2835 uses a generationofARM’s processor designknownas ARM11, whichinturnis designed around a versionof
the instructionset architecture knownas ARMv6. This is worthremembering:ARMv6 is a lightweight and powerfularchitecture,
but has a rivalinthe more advanced ARMv7 architecture used bythe ARM Cortexfamilyofprocessors. Software developed
for ARMv7, like software developed for x86, is sadlynot compatible withthe RaspberryPi’s BCM2835—althoughdevelopers
canusuallyconvert the software to make it suitable.
That’s not to sayyou’re goingto be restricted inyour choices. As you’lldiscover later inthe book, there is plentyofsoftware
available for the ARMv6 instructionset, and as the RaspberryPi’s popularitycontinues to grow, that willonlyincrease. Inthis
book, you’llalso learnhowto create your ownsoftware for the Pievenifyouhave no experience withprogramming.
Windows vs. Linux
Another important difference betweenthe RaspberryPiand your desktop or laptop, other thanthe size and price, is the
operatingsystem—the software that allows youto controlthe computer.
The majorityofdesktop and laptop computers available todayrunone oftwo operatingsystems:Microsoft Windows or Apple
OS X. Bothplatforms are closed source, created ina secretive environment usingproprietarytechniques.
These operatingsystems are knownas closed source for the nature oftheir source code, the computer-language recipe that tells
the systemwhat to do. Inclosed-source software, this recipe is kept a closely-guarded secret. Users are able to obtainthe
finished software, but never to see howit’s made.
The RaspberryPi, bycontrast, is designed to runanoperatingsystemcalled GNU/Linux—hereafter referred to simplyas Linux.
Unlike Windows or OS X, Linuxis opensource:it’s possible to download the source code for the entire operatingsystemand
make whatever changes youdesire. Nothingis hidden, and allchanges are made infullviewofthe public. This opensource
development ethos has allowed Linuxto be quicklyaltered to runonthe RaspberryPi, a process knownas porting. At the time
ofthis writing, severalversions ofLinux—knownas distributions—have beenported to the RaspberryPi’s BCM2835 chip,
includingDebian, Fedora Remixand ArchLinux.
The different distributions cater to different needs, but theyallhave somethingincommon:they’re allopensource. They’re also
all, byand large, compatible witheachother:software writtenona Debiansystemwilloperate perfectlywellonArchLinuxand
vice versa.
Linuxisn’t exclusive to the RaspberryPi. Hundreds ofdifferent distributions are available for desktops, laptops and evenmobile
devices; and Google’s popular Android platformis developed ontop ofa Linuxcore. Ifyoufind that youenjoythe experience
ofusingLinuxonthe RaspberryPi, youcould consider addingit to other computingdevices youuse as well. It willhappily
coexist withyour current operatingsystem, allowingyouto enjoythe benefits ofbothwhile givingyoua familiar environment
whenyour Piis unavailable.
As withthe difference betweenARM and x86, there’s a keypoint to make about the practicaldifference betweenWindows,
OS Xand Linux:software writtenfor Windows or OS Xwon’t runonLinux. Thankfully, there are plentyofcompatible
alternatives for the overwhelmingmajorityofcommonsoftware products—better still, the majorityare free to use and as open
source as the operatingsystemitself.
Getting Started with the Raspberry Pi
Nowthat youhave a basic understandingofhowthe Pidiffers fromother computingdevices, it’s time to get started. Ifyou’ve
just received your Pi, take it out ofits protective anti-static bagand place it ona flat, non-conductive surface before continuing
withthis chapter.
Connecting a Display
Before youcanstart usingyour RaspberryPi, you’re goingto need to connect a display. The Pisupports three different video
outputs:composite video, HDMI video and DSI video. Composite video and HDMI video are readilyaccessible to the end
user, as described inthis section, while DSI video requires some specialised hardware.
Composite Video
Composite video, available via the yellow-and-silver port at the top ofthe Piknownas anRCAphono connector (see Figure 1-
2), is designed for connectingthe RaspberryPito older displaydevices. As the name suggests, the connector creates a
composite ofthe colours found withinanimage—red, greenand blue—and sends it downa single wire to the displaydevice,
typicallyanold cathode-raytube (CRT) TV.
Figure 1-2:The yellowRCAphono connector, for composite video output
Whenno other displaydevice is available, a composite video connectionwillget youstarted withthe Pi. The quality, however,
isn’t great. Composite video connections are significantlymore prone to interference, lack clarityand runat a limited resolution,
meaningthat youcanfit fewer icons and lines oftext onthe screenat once.
HDMI Video
Abetter-qualitypicture canbe obtained usingthe HDMI (HighDefinitionMultimedia Interface) connector, the onlyport found
onthe bottomofthe Pi(see Figure 1-3). Unlike the analogue composite connection, the HDMI port provides a high-speed
digitalconnectionfor pixel-perfect pictures onbothcomputer monitors and high-definitionTVsets. Usingthe HDMI port, a Pi
candisplayimages at the FullHD1920x1080 resolutionofmost modernHDTVsets. At this resolution, significantlymore detail
is available onthe screen.
Ifyou’re hopingto use the Piwithanexistingcomputer monitor, youmayfind that your displaydoesn’t have anHDMI input.
That’s not a disaster:the digitalsignals present onthe HDMI cable map to a commoncomputer monitor standard called DVI
(DigitalVideo Interconnect). BypurchasinganHDMI-to-DVI cable, you’llbe able to connect the Pi’s HDMI port to a monitor
withDVI-Dconnectivity.
Figure 1-3:The silver HDMI connector, for high-definitionvideo output
Ifyour monitor has a VGAinput—a D-shaped connector with15 pins, typicallycoloured silver and blue—the RaspberryPi
can’t connect to it. Adapters are available that willtake ina digitalDVI signaland convert it to ananalogue VGAsignal, but
these are expensive and bulky. The best optionhere is simplyto buya more-modernmonitor witha DVI or HDMI input.
DSI Video
The finalvideo output onthe Picanbe found above the SDcard slot onthe top ofthe printed circuit board—it’s a smallribbon
connector protected bya layer ofplastic. This is for a video standard knownas DisplaySerialInterface (DSI), whichis used in
the flat-paneldisplays oftablets and smartphones. Displays witha DSI connector are rarelyavailable for retailpurchase, and are
typicallyreserved for engineers lookingto create a compact, self-contained system. ADSI displaycanbe connected byinserting
a ribboncable into the matched connector onthe Pi, but for beginners, the use ofa composite or HDMI displayis
recommended.
Connecting Audio
Ifyou’re usingthe RaspberryPi’s HDMI port, audio is simple:whenproperlyconfigured, the HDMI port carries boththe video
signaland a digitalaudio signal. This means that youcanconnect a single cable to your displaydevice to enjoybothsound and
pictures.
Assumingyou’re connectingthe Pito a standard HDMI display, there’s verylittle to do at this point. For now, it’s enoughto
simplyconnect the cable.
Ifyou’re usingthe Piwitha DVI-Dmonitor via anadapter or cable, audio willnot be included. This highlights the maindifference
betweenHDMI and DVI:while HDMI cancarryaudio signals, DVI cannot.
For those withDVI-Dmonitors, or those usingthe composite video output, a black 3.5 mmaudio jack located onthe top edge
ofthe Pinext to the yellowphono connector provides analogue audio (see Figure 1-2). This is the same connector used for
headphones and microphones onconsumer audio equipment, and it’s wired inexactlythe same way. Ifyouwant, youcansimply
connect a pair ofheadphones to this port for quick access to audio.
While headphones can be connecteddirectly to the Raspberry Pi, you may findthe volume a little lacking. If possible, connect a pairof powered
speakers instead. The amplifierinside will helpboost the signal to a more audible level.
Ifyou’re lookingfor somethingmore permanent, youcaneither use standard PC speakers that have a 3.5 mmconnector or you
canbuysome adapter cables. For composite video users, a 3.5 mmto RCAphono cable is useful. This provides the two white-
and-red RCAphono connections that sit alongside the video connection, eachcarryinga channelofthe stereo audio signalto the
TV.
For those connectingthe Pito anamplifier or stereo system, you’lleither need a 3.5 mmto RCAphono cable or a 3.5 mmto
3.5 mmcable, dependingonwhat spare connections youhave onyour system. Bothcable types are readilyand cheaply
available at consumer electronics shops, or canbe purchased evencheaper at online retailers suchas Amazon.
Connecting a Keyboard and Mouse
Nowthat you’ve got your RaspberryPi’s output devices sorted, it’s time to think about input. As a bare minimum, you’re going
to need a keyboard, and for the majorityofusers, a mouse or trackballis a necessitytoo.
First, some bad news:ifyou’ve got a keyboard and mouse witha PS/2 connector—a round plugwitha horseshoe-shaped array
ofpins—thenyou’re goingto have to go out and buya replacement. The old PS/2 connectionhas beensuperseded, and the Pi
expects your peripherals to be connected over the UniversalSerialBus (USB) port.
Dependingonwhether youpurchased the ModelAor ModelB, you’llhave either one or two USBports available onthe right
side ofthe Pi(see Figure 1-4). Ifyou’re usingModelB, youcanconnect the keyboard and mouse directlyto these ports. If
you’re usingModelA, you’llneed to purchase a USBhub inorder to connect two USBdevices simultaneously.
Figure 1-4:ModelB’s two USBports
AUSBhub is a good investment for anyPiuser:evenifyou’ve got a ModelB, you’lluse up bothyour available ports just
connectingyour keyboard and mouse, leavingnothingfree for additionaldevices suchas anexternalopticaldrive, storage device
or joystick. Make sure youbuya powered USBhub:passive models are cheaper and smaller, but lack the abilityto runcurrent-
hungrydevices like CDdrives and externalhard drives.
If you want to reduce the numberof powersockets in use, connect the Raspberry Pi’s USBpowerleadto yourpoweredUSBhub. This way, the Pi
can drawits powerdirectly fromthe hub, ratherthan needing its own dedicatedpowersocket andmains adapter. This will only work on hubs with a
powersupply capable of providing 700mAto the Pi’s USBport, along with whateverpoweris requiredby otherperipherals.
Connectingthe keyboard and mouse is as simple as pluggingtheminto the USBports, either directlyinthe case ofa ModelB
or via a USBhub inthe case ofa ModelA.
A Note on Storage
As you’veprobably noticed, theRaspberry Pi doesn’t haveatraditional hard drive. Instead it uses aSecureDigital (SD) memory card, asolid-statestorage
systemtypically used in digital cameras. Almost any SD card will work with theRaspberry Pi, but becauseit holds theentireoperatingsystem, it is
necessary for thecard to beat least 2 GBin capacity to storeall therequired files.
SD cards with theoperatingsystempreloaded areavailablefromtheofficial Raspberry Pi Storealongwith numerous other sites on theInternet. If you’ve
purchased oneof these, or received it in abundlewith your Pi, you can simply plugit in to theSD card slot on thebottomsideof theleft-hand edge. If not,
you’ll need to install an operatingsystem—known as flashing—onto thecard beforeit’s ready to go.
SomeSD cards work better than others, with somemodels refusingto work at all with theRaspberry Pi. For an up-to-datelist of SD card models known to
work with thePi, visit theeLinuxWiki page: http://www.elinux.org/RPi_VerifiedPeripherals#SD_cards
Flashing the SD Card
To prepare a blank SDcard for use withthe RaspberryPi, you’llneed to flashanoperatingsystemonto the card. While this is
slightlymore complicated thansimplydraggingand droppingfiles onto the card, it shouldn’t take more thana fewminutes to
complete.
Firstly, you’llneed to decide whichLinuxdistributionyouwould like to use withyour RaspberryPi. Eachhas its advantages and
disadvantages. Don’t worryifyouchange your mind later and want to trya different versionofLinux:anSDcard canbe flashed
againwitha newoperatingsystemat anypoint.
The most up-to-date list ofLinuxreleases compatible withthe Piis available fromthe RaspberryPiwebsite at
http://www.raspberrypi.org/downloads.
The Foundationprovides BitTorrent links for eachdistribution. These are smallfiles that canbe used withBitTorrent software to
download the files fromother users. Usingthese links is anefficient and fast wayto distribute large files, and keeps the
Foundation’s download servers frombecomingoverloaded.
To use a BitTorrent link, you’llneed to have a compatible client installed. Ifyoudon’t alreadyhave a BitTorrent client installed,
download one and installit before tryingto download the RaspberryPiLinuxdistribution. One client for Windows, OS Xand
Linuxis µTorrent, available fromhttp://www.utorrent.com/downloads.
Whichdistributionyouchoose to download is up to you. Instructions inthe rest ofthe book willbe based onthe Debian
RaspberryPidistribution, a good choice for beginners. Where possible, we’llgive youinstructions for other distributions as well.
Linuxdistributions for the RaspberryPiare provided as a single image file, compressed to make it faster to download. Once
you’ve downloaded the Zip archive (a compressed file, whichtakes less time to download thanthe uncompressed files would)
for your chosendistribution, you’llneed to decompress it somewhere onyour system. Inmost operatingsystems, youcansimply
double-click the file to openit, and thenchoose Extract or Unzip to retrieve the contents.
After you’ve decompressed the archive, you’llend up withtwo separate files. The file endinginsha1 is a hash, whichcanbe
used to verifythat the download hasn’t beencorrupted intransit. The file endinginimg contains anexact copyofanSDcard set
up bythe distribution’s creators ina waythat the RaspberryPiunderstands. This is the file that needs to be flashed to the SD
card.
During the following, you’ll be using a software utility calleddd. Usedincorrectly dd will happily write the image to yourmain harddrive, erasing
youroperating systemandall yourstoreddata. Make sure you readthe instructions in each section thoroughly andnote the device address of your
SD cardcarefully. Readtwice, write once!
Flashing from Linux
Ifyour current PC is runninga variant ofLinuxalready, youcanuse the dd command to write the contents ofthe image file out to
the SDcard. This is a text-interface programoperated fromthe command prompt, knownas a terminalinLinuxparlance.
Followthese steps to flashthe SDcard:
1. Opena terminalfromyour distribution’s applications menu.
2. Plugyour blank SDcard into a card reader connected to the PC.
3. Type sudo fdisk -l to see a list ofdisks. Find the SDcard byits size, and note the device address (/dev/sdX, where
Xis a letter identifyingthe storage device. Some systems withintegrated SDcard readers mayuse the alternative format
/dev/mmcblkX—ifthis is the case, remember to change the target inthe followinginstructions accordingly).
4. Use cd to change to the directorywiththe .img file youextracted fromthe Zip archive.
5. Type sudo dd if=imagefilename.img of=/dev/sdX bs=2M to write the file imagefilename.img to the SDcard
connected to the device address fromstep 3. Replace imagefilename.imgwiththe actualname ofthe file extracted fromthe
Zip archive. This step takes a while, so be patient! Duringflashing, nothingwillbe shownonthe screenuntilthe process is
fullycomplete (see Figure 1-5).
Figure 1-5:Flashingthe SDcard usingthe dd command inLinux
Flashing from OS X
Ifyour current PC is a Mac runningApple OS X, you’llbe pleased to hear that things are as simple as withLinux. Thanks to a
similar ancestry, OS Xand Linuxbothcontainthe dd utility, whichyoucanuse to flashthe systemimage to your blank SDcard
as follows:
1. Select Utilities fromthe Applicationmenu, and thenclick onthe Terminalapplication.
2. Plugyour blank SDcard into a card reader connected to the Mac.
3. Type diskutil list to see a list ofdisks. Find the SDcard byits size, and note the device address (/dev/diskX,
where Xis a letter identifyingthe storage device).
4. Ifthe SDcard has beenautomaticallymounted and is displayed onthe desktop, type diskutil unmountdisk
/dev/diskXto unmount it before proceeding.
5. Use cd to change to the directorywiththe .img file youextracted fromthe Zip archive.
6. Type dd if=imagefilename.img of=/dev/diskX bs=2M to write the file imagefilename.img to the SDcard connected
to the device address fromstep 3. Replace imagefilename.imgwiththe actualname ofthe file extracted fromthe Zip archive.
This step takes a while, so be patient!
Flashing from Windows
Ifyour current PC is runningWindows, things are slightlytrickier thanwithLinuxor OS X. Windows does not have a utilitylike
dd, so some third-partysoftware is required to get the image file flashed onto the SDcard. Althoughit’s possible to installa
Windows-compatible versionofdd, there is aneasier way:the Image Writer for Windows. Designed specificallyfor creating
USBor SDcard images ofLinuxdistributions, it features a simple graphicaluser interface that makes the creationofa
RaspberryPiSDcard straightforward.
The latest versionofImage Writer for Windows canbe found at the officialwebsite:https://launchpad.net/win32-
image-writer. Followthese steps to download, installand use the Image Writer for Windows software to prepare the SD
card for the Pi:
1. Download the binary(not source) Image Writer for Windows Zip file, and extract it to a folder onyour computer.
2. Plugyour blank SDcard into a card reader connected to the PC.
3. Double-click the Win32DiskImager.exe file to openthe program, and click the blue folder iconto opena file browse
dialogue box.
4. Browse to the imagefilename.img file youextracted fromthe distributionarchive, replacingimagefilename.imgwiththe
actualname ofthe file extracted fromthe Zip archive, and thenclick the Openbutton.
5. Select the drive letter correspondingto the SDcard fromthe Device drop-downdialogue box. Ifyou’re unsure which
drive letter to choose, openMyComputer or Windows Explorer to check.
6. Click the Write buttonto flashthe image file to the SDcard. This process takes a while, so be patient!
No matterwhich operating systemyou’re writing from, it’s important to ensure you leave the SD cardconnecteduntil the image has been
completely written. If you don’t, you may findthat Pi doesn’t boot when the SD cardis connected. If this happens, start the process again.
When the image has been flashedonto the SD card, remove it fromthe computerandinsert it into the Raspberry Pi’s SD cardslot, located
underneath the circuit board. The SD cardshouldbe insertedwith the label facing away fromthe boardandpushedfully home to ensure a good
connection.
Connecting External Storage
While the RaspberryPiuses anSDcard for its mainstorage device—knownas a boot device—youmayfind that youruninto
space limitations quite quickly. Althoughlarge SDcards holding32 GB, 64 GBor more are available, theyare oftenprohibitively
expensive.
Thankfully, there are devices that provide anadditionalhard drive to anycomputer whenconnected via a USBcable. Knownas
USBMass Storage (UMS) devices, these canbe physicalhard drives, solid-state drives (SSDs) or evenportable pocket-sized
flashdrives (see Figure 1-6).
Figure 1-6:Two USBMass Storage devices:a pendrive and anexternalhard drive
The majorityofUSBMass Storage devices canbe read bythe Pi, whether or not theyhave existingcontent. Inorder for the Pi
to be able to access these devices, their drives must be mounted—a process youwilllearninChapter 2, “LinuxSystem
Administration”. For now, it’s enoughto connect the drives to the Piinreadiness.
Connecting the Network
While the majorityofthese setup instructions are equallyapplicable to boththe RaspberryPiModelAand the ModelB,
networkingis a specialexception. To keep the component count—and therefore the cost—as lowas possible, the ModelA
doesn’t feature anyonboard networking. Thankfully, that doesn’t meanyoucan’t network the ModelA; onlythat you’llneed
some additionalequipment to do so.
Networking the Model A
To givetheModel A thesamenetworkingcapabilities as its moreexpensiveModel Bcounterpart, you’ll need aUSB-connected Ethernet adapter. This
connects to afreeUSBport on theRaspberry Pi or aconnected hub and provides awired Ethernet connection with an RJ45 connector, thesameas is
availableon theModel B.
A 10/100 USBEthernet adapter—with thenumbers referringto its two-speed mode, 10 Mb/s and 100 Mb/s—can bepurchased fromonlineretailers for very
littlemoney. When buyingan Ethernet adapter, besureto check that Linuxis listed as asupported operatingsystem. A few models only work with
Microsoft Windows, and areincompatiblewith theRaspberry Pi.
Don’t betempted to go for agigabit-class adapter, which will bereferred to as a10/100/1000 USBEthernet adapter. Standard USBports, as used on the
Raspberry Pi, can’t copewith thespeed of agigabit Ethernet connection, and you’ll seeno benefit to themoreexpensiveadapter.
Wired Networking
To get your RaspberryPionthe network, you’llneed to connect anRJ45 Ethernet patchcable betweenthe Piand a switch,
router or hub. Ifyoudon’t have a router or hub, youcanget your desktop or laptop talkingto the Pibyconnectingthe two
directlytogether witha patchcable.
Usually, connectingtwo network clients together inthis wayrequires a specialcable, knownas a crossover cable. Ina crossover
cable, the receive and transmit pairs are swapped so that the two devices are prevented fromtalkingover eachother—a task
usuallyhandled bya network switchor hub.
The RaspberryPiis cleverer thanthat, however. The RJ45 port onthe side ofthe Pi(see Figure 1-7) includes a feature known
as auto-MDI, whichallows it to reconfigure itselfautomatically. As a result, youcanuse anyRJ45 cable—crossover or not—to
connect the Pito the network, and it willadjust its configurationaccordingly.
Figure 1-7:The RaspberryPiModelB’s Ethernet port
Ifyoudo connect the Pidirectlyto a PC or laptop, youwon’t be able to connect out onto the Internet bydefault. To do so,
you’llneed to configure your PC to bridge the wired Ethernet port and another (typicallywireless) connection. Doingso is
outside the scope ofthis book, but ifyouare completelyunable to connect the Pito the Internet inanyother way, youcantry
searchingyour operatingsystem’s help file for “bridge network”to find more guidance.
Witha cable connected, the Piwillautomaticallyreceive the details it needs to access the Internet whenit loads its operating
systemthroughthe Dynamic Host ConfigurationProtocol(DHCP). This assigns the PianInternet Protocol(IP) address onyour
network, and tells it the gatewayit needs to use to access the Internet (typicallythe IP address ofyour router or modem).
For some networks, there is no DHCP server to provide the PiwithanIP address. Whenconnected to sucha network, the Pi
willneed manualconfiguration. You’lllearnmore about this inChapter 4, “Network Configuration”.
Wireless Networking
Current RaspberryPimodels don’t feature anyformofwireless network capabilityonboard, but—as withaddingwired Ethernet
to the ModelA—it’s possible to add Wi-Fisupport to anyPiusinga USBwireless adapter (see Figure 1-8).
Figure 1-8:Two USBwireless adapters, suitable for use withthe RaspberryPi
Usingsucha device, the Picanconnect to a wide range ofwireless networks, includingthose runningonthe latest 802.11nhigh-
speed standard. Before purchasinga USBwireless adapter, check the following:
• Ensure that Linuxis listed as a supported operatingsystem. Some wireless adapters are provided withdrivers for Windows
and OS Xonly, makingthemincompatible withthe RaspberryPi. Alist ofWi-Fiadapters knownto work withthe
RaspberryPicanbe found onthe followingwebsite:
http://elinux.org/RPi_VerifiedPeripherals#USB_WiFi_Adapters
• Ensure that your Wi-Finetwork type is supported bythe USBwireless adapter. The network type willbe listed inthe
specifications as a number followed bya letter. Ifyour network type is 802.11a, for example, an802.11gwireless adapter
won’t work.
• Check the frequencies supported bythe card. Some wireless network standards, like 802.11a, support more thanone
frequency. Ifa USBwireless adapter is designed to work ona 2.4GHznetwork, it won’t connect to a 5GHznetwork.
• Check the encryptiontype used byyour wireless network. Most modernUSBwireless adapters support allforms of
encryption, but ifyou’re buyinga second-hand or older model, youmayfind it won’t connect to your network. Common
encryptiontypes include the outdated WEP and more modernWPAand WPA2.
Configurationofthe wireless connectionis done withinLinux, so for nowit’s enoughto simplyconnect the adapter to the Pi
(ideallythrougha powered USBhub.) You’lllearnhowto configure the connectioninChapter 4, “Network Configuration”.
Connecting Power
The RaspberryPiis powered bythe smallmicro-USBconnector found onthe lower left side ofthe circuit board. This connector
is the same as found onthe majorityofsmartphones and some tablet devices.
Manychargers designed for smartphones willwork withthe RaspberryPi, but not all. The Piis more power-hungrythanmost
micro-USBdevices, and requires up to 700mAinorder to operate. Some chargers canonlysupplyup to 500mA, causing
intermittent problems inthe Pi’s operation(see Chapter 3, “Troubleshooting”).
Connectingthe Pito the USBport ona desktop or laptop computer is possible, but not recommended. As withsmaller
chargers, the USBports ona computer can’t provide the power required for the Pito work properly.
Onlyconnect the micro-USBpower supplywhenyouare readyto start usingthe Pi. Withno power buttononthe device, it will
start workingthe instant power is connected and canonlybe turned offagainbyphysicallyremovingthe power cable.
Chapter 2: Linux System Administration
The majority of modernLinuxdistributions are user-friendly, witha graphicaluser interface (GUI) that provides aneasywayto
performcommontasks. It is, however, quite different to bothWindows and OS X, so ifyou’re goingto get the most out ofyour
RaspberryPi, you’llneed a quick primer inusingthe operatingsystem.
Linux: An Overview
As brieflyexplained inChapter 1, “Meet the RaspberryPi”, Linuxis anopen-source project whichwas originallyfounded to
produce a kernelthat would be free for anyone to use. The kernelis the heart ofanoperatingsystem, and handles the
communicationbetweenthe user and the hardware.
Althoughonlythe kernelitselfis rightlycalled Linux, the termis oftenused to refer to a collectionofdifferent open-source
projects froma varietyofcompanies. These collections come together to formdifferent flavours ofLinux, knownas distributions.
The originalversionofLinuxwas combined witha collectionoftools created bya group called GNU. The resultingsystem,
knownas GNU/Linux, was basic but powerful. Unlike other operatingsystems ofthe era, it offered facilities like multiple user
accounts where severalusers canshare a single computer. That’s somethingrivalclosed-source operatingsystems have takenon
board, withbothWindows and OS Xnowsupportingmultiple user accounts onthe same system. It’s also stillpresent inLinux,
and provides securityand protectionfor the operatingsystem.
InLinux, you’llspend most ofyour time runninga restricted user account. This doesn’t meanyou’re beinglimited inwhat you
cando. Instead, it prevents youfromaccidentallydoingsomethingthat willbreak the software onyour RaspberryPi. It also
prevents viruses and other malware frominfectingthe systembylockingdownaccess to criticalsystemfiles and directories.
Before youcanget started, it’s worthbecomingfamiliar withsome ofthe terms and concepts used inthe world ofLinux, as
defined inTable 2-1. Evenifyou’re experienced withother operatingsystems, it’s a good idea to reviewthis table before
bootingup your Pifor the first time.
The Terminal and the GUI
As in OSX and Windows, therearetypically two main ways to achieveagiven goal in Linux: through thegraphical user interface(GUI) and through the
command line(known in Linuxparlanceas theconsoleor theterminal).
Theappearanceof various Linuxdistributions can bequitedifferent, dependingon thedesktop environment in use. In this book, therecommended Debian
distribution is used, but most of thecommands you will belearningareentered at theterminal and aretypically thesameacross all distributions.
Whereother distributions differ, you will begiven alternativemethods of achievingthesamegoals.
Table 2.1 The Quick Linux Glossary
Term
/Concept Definition
Bash The most popular shell choice, used in the majority of Linux distributions.
Bootloader Software responsible for loading the Linux kernel. The most common is GRUB.
Console A version of the terminal which is always available, and the first thing you see on the Pi.
Desktop environment Software to make the GUI lookpretty. GNOME and KDE are popular desktop environments.
Directory The Linux term for what Windows calls folders, where files are stored.
Distribution A particular version of Linux. Fedora Remix, Arch and Debian are distributions.
Executable A file that can be run as a program. Linux files must be marked executable in order to run.
EXT2/3/4 The EXTended file system, the most common format used in Linux.
File system The way a hard drive or other storage device is formatted so it’s ready for file storage.
GNOME One of the most common Linux desktop environments around.
GNU A free software project, which provides many of the tools used in Linux distributions.
GRUB The GRand Unified Bootloader, created by GNU and used to load the Linux kernel.
GUI A graphical user interface, in which the user operates the computer via a mouse or touch.
KDE Another extremely popular Linux desktop environment.
Linux Properly, the kernel used by GNU/Linux. Popularly, an open-source operating system.
Live CD A Linux distribution provided as a CD or DVD, which doesn’t require installation.
Package A collection of files required to run an application, typically handled by the package manager.
Package manager A tool for keeping trackof, and installing new, software.
Partition A section of a hard drive which is ready to have a file system applied to it for storage.
Root The main user account in Linux, equivalent to the Windows administrator account.
Shell A text-based command prompt, loaded in a terminal.
sudo A program that allows restricted users to run a command as the root user.
Superuser See Root.
Terminal A text-based command prompt in which the user interacts with a shell program.
X11 The X Window system, a package that provides a graphical user interface (GUI).
Linux Basics
Althoughthere are hundreds ofdifferent Linuxdistributions available, theyallshare a commonset oftools. These tools, which
are operated via the terminal, are analogous to similar tools onWindows and OS X. To get started, you’llneed to learnthe
followingcommands:
• ls—Short for listing, ls provides a list ofthe contents ofthe current directory. Alternatively, it canbe called withan
argument ofthe directoryto be listed. As anexample, typingls /home willprovide a list ofthe contents of/home,
regardless ofyour current directory. The Windows equivalent is dir.
• cd—Aninitialismofchange directory, cd allows youto navigate your waythroughthe file system. Typingcd onits own
puts youback inyour home directory. Typingthe command alongwiththe name ofthe directoryyouwishto move to, by
contrast, switches to that directory. Note that directories canbe absolute or relative:cd boot willmove youto the directory
called boot under your current directory, but cd /boot willmove youstraight to the /boot directorywherever youare.
• mv—The move command has two purposes inLinux:it allows a file to be moved fromone directoryto another, and it also
allows files to be renamed. That latter feature mayseemout ofplace, but inLinuxterms, the file is beingmoved fromone
name to another. The command is called as mv oldfile newfile.
• rm—Short for remove, rm deletes files. Anyfile—or list offiles—provided after the command name willbe deleted. The
Windows equivalent is del, and the two share a commonrequirement that care should be takento ensure the right file is
deleted.
• rmdir—Byitself, rm cannot usuallyremove directories. As a result, rmdir is provided to delete directories once theyhave
beenemptied offiles byrm.
• mkdir—The opposite ofrmdir, the mkdir command creates newdirectories. For example, typingmkdir myfolder at
the terminalwillcreate a newdirectorycalled myfolder under the current workingdirectory. As withcd, directories
provided to the command canbe relative or absolute.
Introducing Debian
Debianis one ofthe oldest Linuxdistributions around, and a great choice for the RaspberryPithanks to its lightweight nature.
This is whythe RaspberryPiFoundationhas chosenit to be the recommended software for newcomers, and the one used for
the examples inthis book.
To keep the download size to a minimum, the RaspberryPiimage for Debianincludes onlya subset ofthe software you’d find
ona regular desktop version. These include tools for browsingthe web, programminginPython, and usingthe Piwitha GUI.
Additionalsoftware canbe quicklyinstalled thoughthe use ofthe distribution’s package manager apt.
The RaspberryPibuild ofDebianincludes a desktop environment knownas the Lightweight X11 Desktop Environment
(LXDE). Designed to offer anattractive user interface usingthe XWindowSystemsoftware, LXDEprovides a familiar point-
and-click interface whichwillbe immediatelyaccessible to anyone who has used Windows, OS Xor other GUI-based operating
systems inthe past.
The GUIdoesn’t loadby default in most Raspberry Pi distributions. To quickly loadit andleave the text-basedconsole behind, log in, type startx
andthen press the Enterkey.
Ifyou’re usingthe recommended Debiandistribution, you’llfind that youhave plentyofpreinstalled software to get started.
While hardlyanexhaustive example ofthe software available for the Pi, whichnumbers inthe thousands ofpackages, it’s a good
introductionto preciselywhat the systemcando.
The software provided withthe Debiandistributionis split into themed categories. To viewthese categories, youcanleft-click
the menuicon, located onthe bottom-left ofthe screeninLXDE(see Figure 2-1).
Figure 2-1:The LXDEdesktop, as loaded onthe DebianRaspberryPidistribution
The followinglists describe the software packages, grouped bycategory.
Accessories
• DebianReference—Abuilt-inreference guide, this provides a detailed explanationofthe DebianLinuxdistributionand how
programmers cancontribute to its development.
• File Manager—The PCManFM file manager provides a graphicalbrowser for files stored onthe Pior anyconnected
storage device.
• Image Viewer—The GPicViewlets youviewimages, suchas those froma digitalcamera or ona connected storage device.
• Leafpad—This is a simple text editor, whichis usefulfor makingquick notes or writingsimple programs.
• LXTerminal—This LXDEterminalpackage allows youto use the Linuxcommand line ina windowwithout leavingthe
graphicaluser interface.
• Root Terminal—Similar to LXTerminal, the Root Terminalautomaticallylogs youinas the root super-user account inorder
to carryout systemmaintenance tasks unavailable to a regular user account.
• Xarchiver—Ifyouneed to create or extract compressed files, suchas ZIP archives, this is the toolfor the job.
Education
• Scratch—Agraphicalprogramminglanguage aimed at youngchildren. You’lllearnmore about Scratchand its capabilities
inChapter 10, “AnIntroductionto Scratch”.
• Squeak—The platformonwhichScratchruns. Youwillrarelyneed to use this menuentry, and should instead use the
Scratchentryabove.
Internet
• Midori—Afast yet lightweight web browser, Midoriis equivalent to Internet Explorer inWindows or to SafarionOS X.
• MidoriPrivate Browsing—Clickingonthis menuentryloads the Midoriweb browser inprivate mode, meaningthat sites
youvisit aren’t saved into the browser’s history.
• NetSurfWeb Browser—Analternative to Midori, NetSurfcanperformbetter oncertaintypes ofweb page. Tryingboth
willallowyouto experiment and find the one whichworks best for you.
Programming
• IDLE—Anintegrated development environment (IDE) writtenspecificallyfor Python. You’lllearnmore about usingIDLE
to write your ownPythonprograms inChapter 11, “AnIntroductionto Python”.
• IDLE3—Clickingthis entryloads IDLEconfigured to use the newer Python3 programminglanguage, rather thanthe
default Python2.7 language. Bothare largelycompatible witheachother, but some programs mayrequire features ofPython
3.
• Scratch—This shortcut opens the Scratcheducationallanguage, and is the same as the Scratchentryfound inthe Education
category. Either canbe used to start the program.
• Squeak—As withScratch, this is a duplicate ofthe shortcut found inthe Educationcategory. Youwillrarelywant to click
this directly, and should instead use the Scratchshortcut.
Sound & Video
• Music Player—LXMusic is a simple and lightweight interface to the XMMS2 music playback software, allowingyouto
listento music files while youwork onthe Pi.
System Tools
• Task Manager—Atoolfor checkingthe amount offree memoryavailable onthe Pi, the current workload ofthe processor,
and for closingprograms whichhave crashed or are otherwise unresponsive.
Preferences
• Customise Look and Feel—Atoolkit for adjustingthe appearance ofthe GUI, includingthe style and colour ofwindows.
• Desktop SessionSettings—Atoolfor changinghowthe systemworks whenthe user is logged in, includingwhat programs
are automaticallyloaded and whichwindowmanager—the software that draws the borders and title bars ofwindows—is
used.
• Keyboard and Mouse—Atoolfor adjustinginput devices. Ifyour keyboard is typingthe wrongcharacters for certainkeys,
or your mouse is too sensitive, the settings canbe altered here.
• Monitor Settings—The resolutionthat the monitor or TVconnected to the Piruns at canbe altered here, althoughadvanced
changes require modificationofconfigurationfiles. You’lllearnabout this inChapter 6, “Configuringthe RaspberryPi”.
• OpenboxConfigurationManager—The LXDEGUI uses a desktop environment called Openbox, whichcanbe adjusted
here. Usingthist tool, youcanapplynewthemes to change the GUI’s appearance, or alter howcertainaspects ofthe
interface operate.
• Preferred Applications—Atoolfor changingwhichapplications are opened for particular file types. Ifyouchoose to use an
alternative web browser, the systemdefault canbe changed here.
Finding Help
Linuxis designed to beas user-friendly as possibleto new users, even at theterminal command prompt. Although you’ll learn themost common ways to use
each command in this chapter, not every option will becovered—to do so would requireamuch larger book.
If you find yourself stuck, or if you want to learn moreabout any of thetools that arediscussed in thefollowingpages, there’s acommand you should learn:
man.
Each Linuxapplication comes with ahelp file, known as aman page—short for “manual page”. It provides background on thesoftwareas well as details on
what its options do and how to usethem.
To access theman pagefor agiven tool, just typeman followed by thecommand name. To seetheman pagefor ls, atool for listingthecontents of
directories, just typeman ls.
Using External Storage Devices
The Pi’s SDcard, whichstores allthe various Pifiles and directories, isn’t verybig. The largest available SDcard at the time of
writingis 64 GB, whichis tinycompared to the 3,000 GB(3 TB) available fromthe largest full-size desktop hard drives.
Ifyou’re usingyour Pito playback video files (see Chapter 7, “The Pias a Home Theatre PC”) you’lllikelyneed more storage
thanyoucanget fromanSDcard. As youlearned inChapter 1, “Meet the RaspberryPi”, it’s possible to connect USBMass
Storage (UMS) devices to the Piinorder to gainaccess to more storage space.
Before these externaldevices are accessible, however, the operatingsystemneeds to knowabout them. InLinux, this process is
knownas mounting. Ifyou’re runninga versionofLinuxwitha desktop environment loaded—like the recommended Debian
distribution’s LXDE, loaded fromthe console withthe startx command—this process is automatic. Simplyconnect the device
to a free USBport onthe Pior a USBhub, and the device and its contents willbe immediatelyaccessible (see Figure 2-2).
Figure 2-2:LXDEautomaticallymountinga USBmass storage device
Fromthe console, things are onlyslightlymore difficult. To make a device accessible to Linuxwhenthe desktop environment
isn’t loaded, followthese steps:
1. Connect the USBstorage device to the Pi, either directlyor througha connected USBhub.
2. Type sudo fdisk -l to get a list ofdrives connected to the Pi, and find the USBstorage device bysize. Note the device
name:/dev/sdXN, where Xis the drive letter and N is the partitionnumber. Ifit is the onlydevice connected to the Pi, this
willbe /dev/sda1.
3. Before the USBstorage device is accessible, Linuxneeds a mount point for it. Create this bytypingsudo mkdir
/media/externaldrive.
4. Currently, the device is onlyaccessible to the root user. To make it accessible to allusers, type the followingas a single
line:
sudo chgrp -R users /media/externaldrive &&
sudo chmod -R g+w /media/externaldrive
5. Mount the USBstorage device withsudo mount /dev/sdXN /media/externaldrive -o=rw to gainaccess to the
device and its contents.
Creating a New User Account
Unlike Windows and OS X, whichare largelydesigned for use bya single individual, Linuxis at heart a socialoperatingsystem
designed to accommodate numerous users. Bydefault, Debianis configured withtwo user accounts:pi, whichis the normaluser
account, and root, whichis a superuser account withadditionalpermissions.
Don’t be temptedto log in as root all the time. Using a nonprivilegeduseraccount, you’re protectedagainst accidentally wrecking youroperating
systemandfromthe ravages of viruses andothermalware downloadedfromthe Internet.
While it’s certainlypossible for youto use the piaccount, it’s better ifyoucreate your owndedicated user account. Further
accounts canalso be created, for anyfriends or familymembers who might want to use the Pi.
Creatinga newaccount onthe Piis straightforward, and the same onalldistributions, except for the username and password
used to logonto the Piinitially. Just followthese steps:
1. Loginto the Piusingthe existinguser account (user name pi and password raspberry ifyou’re usingthe recommended
Debiandistribution).
2. Type the followingas a single line:
sudo useradd -m -G adm,dialout,cdrom,audio,plugdev,users,
lpadmin,sambashare,vchiq,powerdev username
This creates a new, blank user account. Note that the command should be typed as a single line, withno spaces after the
commas.
3. To set a password onthe newaccount, type sudo passwd username followed bythe newpassword whenprompted.
To explainwhat just happened:the command sudo tells the operatingsystemthat the command you’re typingshould be runas if
youwere logged inas the root account. The useradd command says youwant to create a newuser account. The -m section—
knownas a flagor anoption—tells the useradd programto create a home directorywhere the newuser canstore his or her
files. The biglist followingthe -G flagis the list ofgroups ofwhichthe user should be a member.
Users and Groups
In Linux, each user has threemain attributes: their User ID (UID), their Group ID (GID) and alist of supplementary group memberships. A user can bea
member of as many groups as heor shepleases, although only oneof thesecan betheuser’s primary group. This is usually aself-named group matchingthe
user name.
Group membership is important. Whileusers can begranted direct access to files and devices on thesystem, it’s morecommon for auser to receiveaccess to
theseviagroup membership. Thegroup audio, for example, grants all members theability to access thePi’s sound playback hardware. Without that
membership, theuser won’t belisteningto any music.
To seeauser’s group memberships, typegroups usernameat theterminal. If you usethis on thedefault user pi, you’ll seethelist of groups any new
member should join to makeuseof thePi. This is wheretheinformation used in step 2 of theprecedingprocedurewas found.
File System Layout
The content ofthe SDcard is knownas its file system, and is split into multiple sections eachwitha particular purpose. Although
it’s not necessaryfor youto understand what eachsectiondoes inorder to use the RaspberryPi, it canbe helpfulbackground
knowledge should anythinggo wrong.
Logical Layout
The wayLinuxdeals withdrives, files, folders and devices is somewhat different to other operatingsystems. Instead ofhaving
multiple drives labelled witha letter, everythingappears as a branchbeneathwhat is knownas the root file system.
Ifyouloginto the Piand type ls / you’llsee various directories displayed (see Figure 2-3). Some ofthese are areas ofthe SD
card for storingfiles, while others are virtualdirectories for accessingdifferent portions ofthe operatingsystemor hardware.
Figure 2-3:Adirectorylistingfor the Pi’s root file system
The directories visible onthe default Debiandistributionare as follows:
• boot—This contains the Linuxkerneland other packages needed to start the Pi.
• bin—Operatingsystem-related binaryfiles, like those required to runthe GUI, are stored here.
• dev—This is a virtualdirectory, whichdoesn’t actuallyexist onthe SDcard. Allthe devices connected to the system—
includingstorage devices, the sound card and the HDMI port—canbe accessed fromhere.
• etc—This stores miscellaneous configurationfiles, includingthe list ofusers and their encrypted passwords.
• home—Eachuser gets a subdirectorybeneaththis directoryto store alltheir personalfiles.
• lib—This is a storage space for libraries, whichare shared bits ofcode required bynumerous different applications.
• lost+found—This is a specialdirectorywhere file fragments are stored ifthe systemcrashes.
• media—This is a specialdirectoryfor removable storage devices, like USBmemorysticks or externalCDdrives.
• mnt—This folder is used to manuallymount storage devices, suchas externalhard drives.
• opt—This stores optionalsoftware that is not part ofthe operatingsystemitself. Ifyouinstallnewsoftware to your Pi, it will
usuallygo here.
• proc—This is another virtualdirectory, containinginformationabout runningprograms whichare knowninLinuxas
processes.
• selinux—Files related to SecurityEnhanced Linux, a suite ofsecurityutilities originallydeveloped bythe US National
SecurityAgency.
• sbin—This stores specialbinaryfiles, primarilyused bythe root (superuser) account for systemmaintenance.
• sys—This directoryis where specialoperatingsystemfiles are stored.
• tmp—Temporaryfiles are stored here automatically.
• usr—This directoryprovides storage for user-accessible programs.
• var—This is a virtualdirectorythat programs use to store changingvalues or variables.
Physical Layout
Althoughthe precedinglist is howthe file systemappears to the Linuxoperatingsystem, it’s not howit’s laid out onthe SDcard
itself. For the default Debiandistribution, the SDcard is organised into two mainsections, knownas partitions because theysplit
the device into different areas inmuchthe same wayas the chapters ofthis book help to organise its contents.
The first partitiononthe disk is a small(75 MB) partitionformatted as VFAT, the same partitionformat used byMicrosoft
Windows for removable drives. This is mounted, or made accessible, byLinuxinthe /boot directoryand contains allthe files
required to configure the RaspberryPiand to load Linuxitself.
The second partitionis far larger and formatted as EXT4, a native Linuxfile systemdesigned for high-speed access and data
safety. This partitioncontains the mainchunk ofthe distribution. Allthe programs, the desktop, the users’ files and anysoftware
that youinstallyourselfare stored here. This takes up the bulk ofthe SDcard.
Installing and Uninstalling Software
The default software installed withthe Debiandistributionis enoughto get youstarted, but chances are you’re goingto want to
customise your Piaccordingto your ownrequirements.
Installingnewsoftware onto the Piis simple. The Debiandistributionincludes a toolcalled apt, whichis a powerfulpackage
manager. Packages are what Linuxcalls a piece ofsoftware, or a collectionofdifferent pieces ofsoftware designed to work
together.
Althoughapt is designed to be operated fromthe command line, it’s veryuser-friendlyand easyto learn. There are GUIs for
apt, suchas the popular Synaptic Package Manager, but theyoftenstruggle to runonthe Pidue to the lack ofmemory. As a
result, we recommend that software be installed at the terminal.
Other Distributions
Debian, and distributions based on Debian, typically useapt as thepackagemanager. It’s not theonly tool out there, and other distributions makedifferent
choices. FedoraRemix, for example, uses thepacman tool.
Pacman is no moredifficult to usethan apt, but its syntax(theway it expects you to phraseinstructions to install new softwareor removeexistingsoftware)
is different. For instructions on how to usepacman instead of apt, typeman pacman at theFedoraRemixterminal.
Other distributions may usetheyum packagemanager. If you’retryingadistribution that uses yum, simply typeman yum at theterminal for instructions.
Apackage manager’s job is to keep track ofallthe software installed onthe system. It doesn’t just installnewsoftware—it also
keeps tabs onwhat is currentlyinstalled, allows old software to be removed and installs updates as theybecome available.
Package management is one ofthe areas where Linuxdiffers greatlyfromoperatingsystems like Windows or OS X. Although
it’s possible to manuallydownload newsoftware to install, it’s far more commonto use the built-inpackage management tools
instead.
Before trying to install newsoftware orupgrade existing software, you needto make sure the apt cache is upto date. To do this, simply type the
commandsudo apt-get update.
Finding Software
The first step to installinga newpiece ofsoftware is to find out what it’s called. The easiest wayto do this is to searchthe cache
ofavailable software packages. This cache is a list ofallthe software available to installvia apt, stored onInternet servers
knownas repositories.
The apt software includes a utilityfor managingthis cache, called apt-cache. Usingthis software, it’s possible to runa search
onallthe available software packages for a particular word or phrase.
For example, to find a game to play, youcantype the followingcommand:
apt-cache search game
That tells apt-cache to searchits list ofavailable software for anythingwhichhas the word “game”inits title or description. For
commonsearchterms, youcanend up withquite a list (see Figure 2-4), so tryto be as specific as youcan.
Figure 2-4:The last fewresults for anapt-cache “game”search
If yoursearch termbrings uptoo many different packages to see on a single screen display, you can tell Linux that you want it to pause on each
screenfull by piping the output of apt-cache through a tool calledless. Simply change the commandto apt-cache search game | less anduse the
cursorkeys to scroll through the list. Press the letterQ on the keyboardto exit.
Installing Software
Once youknowthe name ofthe package youwant to install, switchto the apt-get command inorder to installit. Installing
software is a privilege afforded onlyto the root user, as it affects allusers ofthe Pi. As a result, the commands willneed to be
prefaced withsudo to tellthe operatingsystemthat it should be runas the root user.
For example, to installthe package thrust (a Linuxversionofa popular Commodore 64 game fromdays gone by), youwould
simplyuse the install command withapt-get as follows:
sudo apt-get install thrust
Some packages relyonother packages inorder to operate. Aprogramminglanguage maydepend ona compiler, a game engine
ongraphics files, or anaudio player oncodecs for playingback different formats. These are knowninLinuxterms as
dependencies.
Dependencies are one ofthe biggest reasons for usinga package manager like apt rather thaninstallingsoftware manually. Ifa
package depends onother packages, apt willautomaticallyfind them(see Figure 2-5) and prepare themfor installation. Ifthis
happens, you’llbe showna prompt askingwhether youwant to continue. Ifyoudo, type the letter Yand press the Enter key.
Figure 2-5:Apt listingthe dependencies for the OpenOffice.orgpackage
Uninstalling Software
Ifyoudecide youno longer want a piece ofsoftware, apt-get also includes a remove command that cleanlyuninstalls the
package alongwithanydependencies whichare no longer required. Whenyou’re usinga smaller SDcard withthe Pi, the ability
to tryout software and quicklyremove it is extremelyuseful.
To remove thrust, simplyopenthe terminaland type the followingcommand:
sudo apt-get remove thrust
The remove command has a more powerfulbrother inthe formofthe purge command. Like remove, the purge command
gets rid ofsoftware youno longer require. Where remove leaves the software’s configurationfiles intact, however, purge
removes everything. Ifyou’ve got yourselfinto a mess customisinga particular package and it no longer works, purge is the
command to use. For example, to purge thrust, youwould just type this:
sudo apt-get purge thrust
Upgrading Software
Inadditionto installingand uninstallingpackages, apt canbe used to keep themup to date. Upgradinga package throughapt
ensures that you’ve received the latest updates, bugfixes and securitypatches.
Before tryingto upgrade a package, make sure the apt cache is as freshas possible byrunninganupdate:
sudo apt-get update
Whenupgradingsoftware, youhave two choices:youcanupgrade everythingonthe systemat once or upgrade individual
programs. Ifyoujust want to keep your distributionupdated, the former is achieved bytypingthe following:
sudo apt-get upgrade
To upgrade anindividualpackage, simplytellapt to installit again. For example, to installa thrust upgrade, youwould type
this:
sudo apt-get install thrust
Ifthe package is alreadyinstalled, apt willtreat it as anin-place upgrade. Ifyou’re alreadyrunningthe latest versionavailable,
apt willsimplytellyouit cannot upgrade the software and exit.
Formore information on package management with apt—in particular, howcertain packages can be “kept back” andexcludedfromupgrades—type
man apt at the terminal.
Chapter 3: Troubleshooting
Sometimes, things don’t go entirelysmoothly. The more complexthe device, the more complexthe problems that canoccur—
and the Piis anextremelycomplexdevice indeed.
Thankfully, manyofthe most commonproblems are straightforward to diagnose and fix. Inthis chapter, we’lllook at some of
the most commonreasons for the Pito misbehave and howto fixthem.
Keyboard and Mouse Diagnostics
Perhaps the most commonproblemthat users experience withthe RaspberryPiis whenthe keyboard repeats certaincharacters.
For example, ifthe command startx appears onscreenas sttttttttttartxxxxxxxxxxxx, it will, understandably, failto
work whenthe Enter keyis pressed.
There are typicallytwo reasons whya USBkeyboard fails to operate correctlywhenconnected to the RaspberryPi:it’s
drawingtoo muchpower, or its internalchipset is conflictingwiththe USBcircuitryonthe Pi.
Check the documentationfor your keyboard, or the labelonits underside, to see ifit has a power ratinggiveninmilliamps (mA).
This is howmuchpower the keyboard attempts to drawfromthe USBport whenit’s inuse.
The Pi’s USBports have a component called a polyfuse connected to them, whichprotects the Piinthe event that a device
attempts to drawtoo muchpower. Whenthis polyfuse is tripped, it causes the USBport to shut off, at around 150 mA. Ifyour
keyboard draws anywhere around that muchpower, it mayoperate strangely—or not at all. This canbe a problemfor
keyboards that have built-inLEDlighting, whichrequire far more power to operate thana standard keyboard.
Ifyoufind that your USBkeyboard maybe drawingtoo muchpower, tryconnectingit to a powered USBhub instead of
directlyto the Pi. This willallowthe keyboard to drawits power fromthe hub’s power supplyunit, instead offromthe Piitself.
Alternatively, swap the keyboard out for a modelwithlower power demands. The repeating-letter problemmayalso be traced
to aninadequate power supplyfor the Piitself, whichis addressed inthe next section, “Power Diagnostics”.
The issue ofcompatibility, sadly, is harder to diagnose. While the overwhelmingmajorityofkeyboards work just fine withthe Pi,
a smallnumber exhibit strange symptoms. These range fromintermittent response, the repeating-letter syndrome or evencrashes
that prevent the Pifromoperating. Sometimes, these issues don’t appear untilother USBdevices are connected to the Pi. Ifyour
keyboard was workingfine untilanother USBdevice, inparticular a USBwireless adapter, was connected, youmayhave an
issue ofincompatibility.
Ifpossible, tryswappingthe keyboard out for another model. Ifthe newkeyboard works, your old one maybe incompatible
withthe Pi. For a list ofknown-incompatible keyboards, visit the eLinuxwiki:
http://elinux.org/RPi_VerifiedPeripherals#Problem_USB_Keyboards
The same advice oncheckingcompatibilityinadvance applies to problems withthe mouse:the majorityofUSBmice and
trackballs work fine, but some exhibit incompatibilitywiththe Pi’s ownUSBcircuitry. This usuallyresults insymptoms like a
jerkyor unresponsive mouse pointer, but it cansometimes lead to the Pifailingto load or crashingat randomintervals. Ifyou’re
lookingto buya newmouse, anup-to-date list ofmodels knownto work withthe Piis available at the eLinuxwikisite:
http://elinux.org/RPi_VerifiedPeripherals#Working_USB_Mouse_Devices
Power Diagnostics
Manyproblems withthe RaspberryPicanbe traced to aninadequate power supply. The ModelArequires a 5 Vsupply
capable ofprovidinga 500 mAcurrent, while the ModelB’s extra components bump up the current requirement to 700 mA.
Not allUSBpower adapters are designed to offer this muchpower, eveniftheir labellingclaims otherwise.
The formal USBstandardstates that devices shoulddrawno more than 500 mA, with even that level of poweronly available to the device following a
process callednegotiation. Because the Pi doesn’t negotiate forpower, it’s unlikely that it will work if you connect it to the USBports on a desktop
orlaptopcomputer.
Ifyou’re havingintermittent problems withyour Pi—particularlyifit works untilyouconnect somethingto a USBport or start a
processor-intensive operationlike playingvideo—the chances are that the power supplyinuse is inadequate. The Piprovides a
relativelyeasywayto check ifthis is the case inthe formoftwo voltage test points.
To use the voltage test points, you’llneed a voltmeter or multimeter withdirect current (DC) voltage measuringcapabilities. If
your meter has multiple inputs for different voltages, use anappropriate setting.
Avoidtouching the test probes to anything not labelledas a test point. It’s possible to bridge the 5 Vsupply that comes in to the Pi to the internal 3.3
Vsupply, creating a short circuit which can damage the device. Be especially careful aroundexposedheaderpins.
The two test points are small, copper-clad holes knownas vias, whichare connected to the Pi’s 5 Vand ground circuits. Put the
positive (red) meter probe onTP1, located to the left ofthe board just above a smallblack component called a regulator labelled
RG2. Connect the black (negative) meter probe to TP2, located betweenthe copper GPIO pins and the yellow-and-silver RCA
phono connector at the top-left ofthe board (see Figure 3-1).
Figure 3-1:The two voltage test points, labelled TP1 and TP2
The readingonthe voltmeter should be somewhere between4.8 Vand 5 V. Ifit’s lower than4.8 V, this indicates that the Piis
not beingprovided withenoughpower. Tryswappingthe USBadapter for a different model, and check that the labelsays it can
supply700 mAor more. Amodelrated at 1Ais recommended, but beware ofcheap models—theysometimes have inaccurate
labelling, and failto supplythe promised current. Genuine branded mobile phone chargers rarelyhave this problem, but cheap
unbranded devices—oftensold as compatible adapters—should be avoided
Ifyour voltmeter reads a negative number, don’t worry:this just means you’ve got the positive and negative probes inthe wrong
place. Either swap themaround or just ignore the negative signwhennotingyour reading.
Display Diagnostics
Althoughthe Piis designed to work withalmost anyHDMI, DVI or composite video displaydevice, it simplymaynot work as
expected whenyouplugit in. For example, youmayfind that your picture is shifted to the side or not fullydisplayed, or is only
visible as a postage-stamp-sized cut-out inthe middle ofthe screenor inblack-and-white—or evenmissingentirely.
First, check the type ofdevice to whichthe Piis connected. This is especiallyimportant whenyou’re usingthe composite RCA
connectionto plugthe Piinto a TV. Different countries use different standards for TVvideo, meaningthat a Piconfigured for one
countrymaynot work inanother. This is the usualexplanationfor a Pishowingblack-and-white video. You’lllearnhowto
adjust this settinginChapter 6, “Configuringthe RaspberryPi”.
Whenyouuse the HDMI output, the displaytype is usuallyautomaticallydetected. Ifyou’re usinganHDMI to DVI adapter to
plugthe Piinto a computer monitor, however, this occasionallygoes awry. Commonsymptoms include snow-like static, missing
picture portions or no displayat all. To fixthis, note the resolutionand refreshrate ofyour connected display, and thenjump to
Chapter 6 to find out howto set these manually.
Another issue is a too-large or too-smallimage, either missingportions at the edge ofthe screenor sittinginthe middle ofa large
black border. This is caused bya settingknownas overscan, whichis used whenthe Piis connected to TVs to avoid printingto
portions ofthe displaywhichmaybe hiddenunder a bezel. As withother display-related settings, youwilllearnhowto adjust—
or evencompletelydisable—overscaninChapter 6.
Boot Diagnostics
The most commoncause for a Pito failto boot is a problemwiththe SDcard. Unlike a desktop or laptop computer, the Pi
relies onfiles stored onthe SDcard for everything. IfPican’t talk to the card, it won’t displayanythingonthe screenor show
anysigns oflife at all.
Ifyour Pi’s power light glows whenyouconnect the micro-USBpower supply, but nothingelse happens and the OK light
remains dark, youhave anSDcard problem. First, ensure that the card works whenyouconnect it to a PC, and that it shows
the partitions and files expected ofa well-flashed card. (For more details, see Chapter 2, “LinuxSystemAdministration”,
particularlythe sectiontitled “File SystemLayout”inthat chapter.)
Ifthe card works ona PC but not inthe Pi, it maybe a compatibilityproblem. Some SDcards—especiallyhigh-speed cards
marked as Class 10 ontheir labelling—don’t operate correctlywhenconnected to the Pi’s onboard SDcard reader. Alist of
cards knownto cause compatibilityproblems withthe Picanbe found onthe eLinuxwiki:
http://elinux.org/RPi_VerifiedPeripherals#Problem_SD_Cards
Sadly, ifyouhave one ofthe cards onthe list, youmayneed to replace it witha different card inorder for the Pito work. As the
Pi’s software base is developed, however, work is beingcarried out to ensure that a wider range ofcards operate correctlywith
the Pi. Before givingup ona high-speed card completely, check to see ifanupdated versionofyour chosenLinuxdistributionis
available. (See Chapter 1, “Meet the RaspberryPi”, for more informationabout distributions.)
Network Diagnostics
The most usefultoolfor diagnosingnetwork problems is ifconfig. Ifyou’re usinga wireless network connection, jump to
Chapter 4, “Network Configuration”, for informationona similar toolfor those devices. Otherwise, read on.
Designed to provide informationonconnected network ports, ifconfig is a powerfultoolfor controllingand configuringthe
Pi’s network ports. For its most basic usage, simplytype the tool’s name inthe terminal:
ifconfig
Called inthis manner, ifconfig provides informationonallthe network ports it canfind (see Figure 3-2). For the standard
RaspberryPiModelB, there are two ports:the physicalEthernet port onthe right side ofthe board, and a virtualloopback
interface that allows programs onthe Pito talk to eachother.
Figure 3-2:The output ofifconfig ona RaspberryPiModelB
The output ofifconfig is split into the followingsections:
• Link encap—The type ofencapsulationused bythe network, whichonthe ModelBwilleither read Ethernet for the
physicalnetwork port or Local Loopback for the virtualloopback adaptor.
• Hwaddr—The Media Access Control(MAC) address ofthe network interface, writteninhexadecimal. This is unique for
everydevice onthe network, and eachPihas its ownMAC address, whichis set at the factory.
• inet addr—The internet protocol(IP) address ofthe network interface. This is howyoufind the Pionthe network ifyou’re
usingit to runa network-accessible service, suchas a web server or file server.
• Bcast—The broadcast address for the network to whichthe Piis connected. Anytraffic sent to this address willbe
received byeverydevice onthe network.
• Mask—The network mask, whichcontrols the maximumsize ofthe network to whichthe Piis connected. For most home
users, this willread 255.255.255.0.
• MTU—The maximumtransmissionunit size, whichis howbiga single packet ofdata canbe before the systemneeds to
split it into multiple packets.
• RX—This sectionprovides feedback onthe received network traffic, includingthe number oferrors and dropped packets
recorded. Ifyoustart to see errors appearinginthis section, there’s somethingwrongwiththe network.
• TX—This provides the same informationas the RXsection, but for transmitted packets. Again, anyerrors recorded here
indicate a problemwiththe network.
• collisions—Iftwo systems onthe network tryto talk at the same time, youget a collisionwhichrequires themto retransmit
their packets. Smallnumbers ofcollisions aren’t a problem, but a large number here indicates a network issue.
• txqueuelen—The lengthofthe transmissionqueue, whichwillusuallybe set to 1000 and rarelyneeds changing.
• RXbytes, TXbytes—Asummaryofthe amount oftraffic the network interface has passed.
Ifyou’re havingproblems withthe network onthe Pi, youshould first tryto disable and thenre-enable the network interface.
The easiest wayto do this is withtwo tools called ifup and ifdown.
Ifthe network is up, but not workingcorrectly—for example, ififconfig doesn’t list anythinginthe inet addr section—start
bydisablingthe network port. Fromthe terminal, type the followingcommand:
sudo ifdown eth0
Once the network is disabled, make sure that the cable is inserted tightlyat bothends, and that whatever network device the Pi
is connected to (hub, switchor router) is powered onand working. Thenbringthe interface back up againwiththe following
command:
sudo ifup eth0
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton
Guía de usuario de Raspberry Pi por Eben Upton

More Related Content

Similar to Guía de usuario de Raspberry Pi por Eben Upton

Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.
Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.
Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.SANTIAGO PABLO ALBERTO
 
IoT Levels of AUtomation-case study topic
IoT Levels of AUtomation-case study topicIoT Levels of AUtomation-case study topic
IoT Levels of AUtomation-case study topicpcmech
 
Raspberry Pi - Unlocking New Ideas for Your Library
Raspberry Pi - Unlocking New Ideas for Your LibraryRaspberry Pi - Unlocking New Ideas for Your Library
Raspberry Pi - Unlocking New Ideas for Your LibraryBrian Pichman
 
Introduction to the Raspberry Pi
Introduction to the Raspberry PiIntroduction to the Raspberry Pi
Introduction to the Raspberry Pihailetes
 
FINAL SEMINAR REPORT OF RASPBERRY PI
FINAL SEMINAR REPORT OF RASPBERRY PIFINAL SEMINAR REPORT OF RASPBERRY PI
FINAL SEMINAR REPORT OF RASPBERRY PIGANESH GOVIND BHOR
 
SEMINAR REPORT OF RASPBERRY PI
SEMINAR REPORT OF RASPBERRY PI SEMINAR REPORT OF RASPBERRY PI
SEMINAR REPORT OF RASPBERRY PI GANESH GOVIND BHOR
 
Hands-on Raspberry Pi and VA Smalltalk - Starting Workshop
Hands-on Raspberry Pi and VA Smalltalk - Starting WorkshopHands-on Raspberry Pi and VA Smalltalk - Starting Workshop
Hands-on Raspberry Pi and VA Smalltalk - Starting WorkshopFAST
 
BeginnersGuide-4thEd-Eng_v2.pdf
BeginnersGuide-4thEd-Eng_v2.pdfBeginnersGuide-4thEd-Eng_v2.pdf
BeginnersGuide-4thEd-Eng_v2.pdfangelofgodj
 
Getting started with Raspberry Pi - By Ibrahim
Getting started with Raspberry Pi - By IbrahimGetting started with Raspberry Pi - By Ibrahim
Getting started with Raspberry Pi - By IbrahimMurugadoss Balasubramanian
 
Iaetsd the world’s smallest computer for programmers and app developers
Iaetsd the world’s smallest computer for programmers and app developersIaetsd the world’s smallest computer for programmers and app developers
Iaetsd the world’s smallest computer for programmers and app developersIaetsd Iaetsd
 
Raspberry pi history, tips and use case
Raspberry pi history, tips and use caseRaspberry pi history, tips and use case
Raspberry pi history, tips and use caseMasafumi Ohta
 
Raspberry pi setting_cambodia
Raspberry pi setting_cambodiaRaspberry pi setting_cambodia
Raspberry pi setting_cambodiagongdigi24
 
Raspberry Pi Introductory Lecture
Raspberry Pi Introductory LectureRaspberry Pi Introductory Lecture
Raspberry Pi Introductory LectureSyed Umaid Ahmed
 
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30Thinkful
 

Similar to Guía de usuario de Raspberry Pi por Eben Upton (20)

Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.
Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.
Raspberry pi: Aspectos básicos del servidor Raspberry pi 2 de piotr j. kula.
 
IoT Levels of AUtomation-case study topic
IoT Levels of AUtomation-case study topicIoT Levels of AUtomation-case study topic
IoT Levels of AUtomation-case study topic
 
Raspberry Pi - Unlocking New Ideas for Your Library
Raspberry Pi - Unlocking New Ideas for Your LibraryRaspberry Pi - Unlocking New Ideas for Your Library
Raspberry Pi - Unlocking New Ideas for Your Library
 
Introduction to the Raspberry Pi
Introduction to the Raspberry PiIntroduction to the Raspberry Pi
Introduction to the Raspberry Pi
 
FINAL SEMINAR REPORT OF RASPBERRY PI
FINAL SEMINAR REPORT OF RASPBERRY PIFINAL SEMINAR REPORT OF RASPBERRY PI
FINAL SEMINAR REPORT OF RASPBERRY PI
 
SEMINAR REPORT OF RASPBERRY PI
SEMINAR REPORT OF RASPBERRY PI SEMINAR REPORT OF RASPBERRY PI
SEMINAR REPORT OF RASPBERRY PI
 
Intelligent IoT Projects In 7 Days
Intelligent IoT Projects In 7 Days Intelligent IoT Projects In 7 Days
Intelligent IoT Projects In 7 Days
 
Hands-on Raspberry Pi and VA Smalltalk - Starting Workshop
Hands-on Raspberry Pi and VA Smalltalk - Starting WorkshopHands-on Raspberry Pi and VA Smalltalk - Starting Workshop
Hands-on Raspberry Pi and VA Smalltalk - Starting Workshop
 
BeginnersGuide-4thEd-Eng_v2.pdf
BeginnersGuide-4thEd-Eng_v2.pdfBeginnersGuide-4thEd-Eng_v2.pdf
BeginnersGuide-4thEd-Eng_v2.pdf
 
Getting started with Raspberry Pi - By Ibrahim
Getting started with Raspberry Pi - By IbrahimGetting started with Raspberry Pi - By Ibrahim
Getting started with Raspberry Pi - By Ibrahim
 
Raaaaassspberry pi
Raaaaassspberry piRaaaaassspberry pi
Raaaaassspberry pi
 
Raspberry pi
Raspberry piRaspberry pi
Raspberry pi
 
Iaetsd the world’s smallest computer for programmers and app developers
Iaetsd the world’s smallest computer for programmers and app developersIaetsd the world’s smallest computer for programmers and app developers
Iaetsd the world’s smallest computer for programmers and app developers
 
Raspberry pi
Raspberry piRaspberry pi
Raspberry pi
 
Raspberry pi history, tips and use case
Raspberry pi history, tips and use caseRaspberry pi history, tips and use case
Raspberry pi history, tips and use case
 
Artificial99a
Artificial99aArtificial99a
Artificial99a
 
Artificial99a
Artificial99aArtificial99a
Artificial99a
 
Raspberry pi setting_cambodia
Raspberry pi setting_cambodiaRaspberry pi setting_cambodia
Raspberry pi setting_cambodia
 
Raspberry Pi Introductory Lecture
Raspberry Pi Introductory LectureRaspberry Pi Introductory Lecture
Raspberry Pi Introductory Lecture
 
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30
Deck 8983a1d9-68df-4447-8481-3b4fd0de734c-30
 

More from SANTIAGO PABLO ALBERTO

Manual de teoría y practica electroneumática avanzada
Manual de teoría y practica electroneumática avanzadaManual de teoría y practica electroneumática avanzada
Manual de teoría y practica electroneumática avanzadaSANTIAGO PABLO ALBERTO
 
Programacion de PLC basado en Rslogix 500 por Roni Domínguez
Programacion de PLC basado en Rslogix 500 por Roni Domínguez Programacion de PLC basado en Rslogix 500 por Roni Domínguez
Programacion de PLC basado en Rslogix 500 por Roni Domínguez SANTIAGO PABLO ALBERTO
 
Programación de microcontroladores PIC en C con Fabio Pereira
Programación de microcontroladores PIC en  C con Fabio PereiraProgramación de microcontroladores PIC en  C con Fabio Pereira
Programación de microcontroladores PIC en C con Fabio PereiraSANTIAGO PABLO ALBERTO
 
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...SANTIAGO PABLO ALBERTO
 
Programación de autómatas PLC OMRON CJ/CP1
Programación de  autómatas PLC OMRON CJ/CP1Programación de  autómatas PLC OMRON CJ/CP1
Programación de autómatas PLC OMRON CJ/CP1SANTIAGO PABLO ALBERTO
 
Manual del sistema del controlador programable S7-200 SMART
Manual del sistema del controlador programable S7-200 SMARTManual del sistema del controlador programable S7-200 SMART
Manual del sistema del controlador programable S7-200 SMARTSANTIAGO PABLO ALBERTO
 
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...SANTIAGO PABLO ALBERTO
 
PLC y Electroneumática: Electricidad y Automatismo eléctrico por Luis Miguel...
PLC y Electroneumática: Electricidad y Automatismo eléctrico por  Luis Miguel...PLC y Electroneumática: Electricidad y Automatismo eléctrico por  Luis Miguel...
PLC y Electroneumática: Electricidad y Automatismo eléctrico por Luis Miguel...SANTIAGO PABLO ALBERTO
 
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...SANTIAGO PABLO ALBERTO
 
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...SANTIAGO PABLO ALBERTO
 
Electrónica digital: Introducción a la Lógica Digital - Teoría, Problemas y ...
Electrónica digital:  Introducción a la Lógica Digital - Teoría, Problemas y ...Electrónica digital:  Introducción a la Lógica Digital - Teoría, Problemas y ...
Electrónica digital: Introducción a la Lógica Digital - Teoría, Problemas y ...SANTIAGO PABLO ALBERTO
 

More from SANTIAGO PABLO ALBERTO (20)

secuencia electroneumática parte 1
secuencia electroneumática parte 1secuencia electroneumática parte 1
secuencia electroneumática parte 1
 
secuencia electroneumática parte 2
secuencia electroneumática parte 2secuencia electroneumática parte 2
secuencia electroneumática parte 2
 
Manual de teoría y practica electroneumática avanzada
Manual de teoría y practica electroneumática avanzadaManual de teoría y practica electroneumática avanzada
Manual de teoría y practica electroneumática avanzada
 
Programacion de PLC basado en Rslogix 500 por Roni Domínguez
Programacion de PLC basado en Rslogix 500 por Roni Domínguez Programacion de PLC basado en Rslogix 500 por Roni Domínguez
Programacion de PLC basado en Rslogix 500 por Roni Domínguez
 
Programación de microcontroladores PIC en C con Fabio Pereira
Programación de microcontroladores PIC en  C con Fabio PereiraProgramación de microcontroladores PIC en  C con Fabio Pereira
Programación de microcontroladores PIC en C con Fabio Pereira
 
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...
Análisis y Diseño de Sistemas de Control Digital por Ricardo Fernandez del Bu...
 
Arduino: Arduino de cero a experto
Arduino: Arduino de cero a expertoArduino: Arduino de cero a experto
Arduino: Arduino de cero a experto
 
Fisica I
Fisica IFisica I
Fisica I
 
Quimica.pdf
Quimica.pdfQuimica.pdf
Quimica.pdf
 
Manual básico PLC OMRON
Manual básico PLC OMRON Manual básico PLC OMRON
Manual básico PLC OMRON
 
Programación de autómatas PLC OMRON CJ/CP1
Programación de  autómatas PLC OMRON CJ/CP1Programación de  autómatas PLC OMRON CJ/CP1
Programación de autómatas PLC OMRON CJ/CP1
 
Manual del sistema del controlador programable S7-200 SMART
Manual del sistema del controlador programable S7-200 SMARTManual del sistema del controlador programable S7-200 SMART
Manual del sistema del controlador programable S7-200 SMART
 
Catálogo de PLC S7-200 SMART
Catálogo de PLC S7-200 SMART Catálogo de PLC S7-200 SMART
Catálogo de PLC S7-200 SMART
 
PLC: Automatismos industriales
PLC: Automatismos industrialesPLC: Automatismos industriales
PLC: Automatismos industriales
 
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...
PLC: Buses industriales y de campo practicas de laboratorio por Jose Miguel R...
 
PLC y Electroneumática: Electricidad y Automatismo eléctrico por Luis Miguel...
PLC y Electroneumática: Electricidad y Automatismo eléctrico por  Luis Miguel...PLC y Electroneumática: Electricidad y Automatismo eléctrico por  Luis Miguel...
PLC y Electroneumática: Electricidad y Automatismo eléctrico por Luis Miguel...
 
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...
Electrónica: Diseño y desarrollo de circuitos impresos con Kicad por Miguel P...
 
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...
PLC: Diseño, construcción y control de un motor doble Dahlander(cuatro veloci...
 
PLC: Motor Dahlander
PLC: Motor DahlanderPLC: Motor Dahlander
PLC: Motor Dahlander
 
Electrónica digital: Introducción a la Lógica Digital - Teoría, Problemas y ...
Electrónica digital:  Introducción a la Lógica Digital - Teoría, Problemas y ...Electrónica digital:  Introducción a la Lógica Digital - Teoría, Problemas y ...
Electrónica digital: Introducción a la Lógica Digital - Teoría, Problemas y ...
 

Recently uploaded

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 

Recently uploaded (20)

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 

Guía de usuario de Raspberry Pi por Eben Upton

  • 1.
  • 2. Raspberry Pi® User Guide Table of Contents Introduction Programming is fun! A bit of history So what can you do with the Raspberry Pi? Part I: Connecting the Board Chapter 1: Meet the Raspberry Pi ARM vs. x86 Windows vs. Linux Getting Started with the Raspberry Pi Connecting a Display Connecting Audio Connecting a Keyboard and Mouse Flashing the SD Card Connecting External Storage Connecting the Network Connecting Power Chapter 2: Linux System Administration Linux: An Overview Linux Basics Introducing Debian Using External Storage Devices Creating a New User Account File System Layout Logical Layout Physical Layout Installing and Uninstalling Software Finding Software Installing Software Uninstalling Software
  • 3. Upgrading Software Chapter 3: Troubleshooting Keyboard and Mouse Diagnostics Power Diagnostics Display Diagnostics Boot Diagnostics Network Diagnostics The Emergency Kernel Chapter 4: Network Configuration Wired Networking Wireless Networking Chapter 5: Partition Management Creating a New Partition Resizing Existing Partitions Automatic Resizing Manual Resizing Moving to a Bigger SD Card Imaging from Linux Imaging from OS X Imaging from Windows Chapter 6: Configuring the Raspberry Pi Hardware Settings—config.txt Modifying the Display Boot Options Overclocking the Raspberry Pi Disabling L2 Cache Enabling Test Mode Memory Partitioning—start.elf Software Settings—cmdline.txt Part II: Using the Pi as a Media Centre, Productivity Machine and Web Server
  • 4. Chapter 7: The Pi as a Home Theatre PC Playing Music at the Console Dedicated HTPC with Rasbmc Streaming Internet Media Streaming Local Network Media Configuring Rasbmc Chapter 8: The Pi as a Productivity Machine Using Cloud-Based Apps Using OpenOffice.org Image Editing with The Gimp Chapter 9: The Pi as a Web Server Installing a LAMP Stack Installing WordPress Part III: Programming and Hacking Chapter 10: An Introduction to Scratch Introducing Scratch Example 1: Hello World Example 2: Animation and Sound Example 3: A Simple Game Robotics and Sensors Sensing with the PicoBoard Robotics with LEGO Further Reading Chapter 11: An Introduction to Python Introducing Python Example 1: Hello World Example 2: Comments, Inputs, Variables and Loops Example 3: Gaming with pygame Example 4: Python and Networking Further Reading
  • 5. Chapter 12: Hardware Hacking Electronic Equipment Reading Resistor Colour Codes Sourcing Components Online Sources Offline Sources Hobby Specialists The GPIO Port UART Serial Bus I²C Bus SPI Bus Using the GPIO Port in Python Installing the GPIO Python Library GPIO Output: Flashing an LED GPIO Input: Reading a Button Moving Up From the Breadboard A Brief Guide to Soldering Chapter 13: Add-on Boards Ciseco Slice of Pi Adafruit Prototyping Pi Plate Fen Logic Gertboard Part IV: Appendixes Appendix A: Python Recipes Appendix B: HDMI Display Modes
  • 6. Raspberry Pi® User Guide Eben Upton and Gareth Halfacree
  • 7. Raspberry Pi® User Guide This edition first published 2012 © 2012 Eben Upton and Gareth Halfacree Registered office John Wiley & Sons Ltd., The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom For details of our global editorial offices, 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. The right of the authors to be identified 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. The publisher is not associated with any product or vendor mentioned in this book. This 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 and Sons, Ltd. and/or its affiliates 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-46446-5 (pbk); ISBN 978-1-118-46448-9 (ebk); ISBN 978-1-118-46447-2 (ebk); ISBN 978-1-118-46449-6 (ebk) 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:
  • 8. 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 Assistant Editor Ellie Scott Project Editor Kathryn Duggan Copy Editor Kathryn Duggan Technical Editor Omer Kilic Editorial Manager Jodi Jensen Senior Project Editor Sara Shlaer Editorial Assistant Leslie Saxman Marketing Associate Marketing Director Louise Breinholt Marketing Manager Lorna Mein
  • 9. Senior Marketing Executive Kate Parrett Composition Services Compositor Erin Zeltner Proofreader Wordsmith Editorial Indexer BIM Indexing & Proofreading Services
  • 10. About the Authors EbenUptonis a founder and trustee ofthe RaspberryPiFoundation, and serves as its Executive Director. He is responsible for the overallsoftware and hardware architecture ofthe RaspberryPi, and for the Foundation's relationships withits keysuppliers and customers. Inanearlier life, he founded two successfulmobile games and middleware companies, Ideaworks 3d Ltd. and PodfunLtd., and held the post ofDirector ofStudies for Computer Science at St John's College, Cambridge. He holds a BA, a PhDand anMBAfromthe UniversityofCambridge. Inhis dayjob, Ebenworks for Broadcomas anASIC architect and generaltroublemaker. GarethHalfacree is a freelance technologyjournalist and the co-author ofthe RaspberryPiUser Guide alongside project co- founder EbenUpton. Formerlya systemadministrator workinginthe educationsector, Gareth’s passionfor opensource projects has followed himfromone career to another, and he canoftenbe seenreviewing, documentingor evencontributingto projects includingGNU/Linux, LibreOffice, Fritzingand Arduino. He is also the creator ofthe Sleepduino and Burnduino open hardware projects, whichextend the capabilities ofthe Arduino electronics prototypingsystem. Asummaryofhis current work canbe found at http://freelance.halfacree.co.uk. For Liz, who made it all possible. —Eben
  • 11. For my father, the enthusiastic past, and my daughter, the exciting future. —Gareth
  • 12. Introduction “Childrentoday are digitalnatives”, said a manI got talkingto at a fireworks partylast year. “I don’t understand whyyou’re makingthis thing. Mykids knowmore about settingup our PC thanI do.” I asked himiftheycould program, to whichhe replied:“Whywould theywant to? The computers do allthe stufftheyneed for themalready, don’t they? Isn’t that the point?” As it happens, plentyofkids todayaren’t digitalnatives. We have yet to meet anyofthese imagined wild digitalchildren, swingingfromropes oftwisted-pair cable and chantingwar songs innicelyparsed Python. Inthe RaspberryPiFoundation’s educationaloutreachwork, we do meet a lot ofkids whose entire interactionwithtechnologyis limited to closed platforms with graphicaluser interfaces (GUIs) that theyuse to playmovies, do a spot ofword-processed homework and playgames. They canbrowse the web, upload pictures and video, and evendesignweb pages. (They’re oftenbetter at settingthe satellite TVbox thanMumor Dad, too.) It’s a usefultoolset, but it’s shockinglyincomplete, and ina countrywhere 20%ofhouseholds stilldon’t have a computer inthe home, eventhis toolset is not available to allchildren. Despite the most fervent wishes ofmynewacquaintance at the fireworks party, computers don’t programthemselves. We need anindustryfullofskilled engineers to keep technologymovingforward, and we need youngpeople to be takingthose jobs to fill the pipeline as older engineers retire and leave the industry. But there’s muchmore to teachinga skilllike programmatic thinking thanbreedinga newgenerationofcoders and hardware hackers. Beingable to structure your creative thoughts and tasks in complex, non-linear ways is a learned talent, and one that has huge benefits for everyone who acquires it, fromhistorians to designers, lawyers and chemists. Programming is fun! It’s enormous, rewarding, creative fun. Youcancreate gorgeous intricacies, as wellas (muchmore gorgeous, inmyopinion) clever, devastatinglyquick and deceptivelysimple-lookingroutes through, under and over obstacles. Youcanmake stuffthat’ll have other people lookingonjealously, and that’llmake youfeelwonderfullysmugallafternoon. Inmydayjob, where I design the sort ofsiliconchips that we use inthe RaspberryPias a processor and work onthe low-levelsoftware that runs onthem, I basicallyget paid to sit around alldayplaying. What could be better thanequippingpeople to be able to spend a lifetime doing that? It’s not evenas ifwe’re comingfroma positionwhere childrendon’t want to get involved inthe computer industry. Abigkick up the backside came a fewyears ago, whenwe were movingquite slowlyonthe RaspberryPiproject. Allthe development work onRaspberryPiwas done inthe spare evenings and weekends ofthe Foundation’s trustees and volunteers—we’re a charity, so the trustees aren’t paid bythe Foundation, and we allhave full-time jobs to paythe bills. This meant that occasionally, motivationwas hard to come bywhenallI wanted to do inthe eveningwas slump infront ofthe Arrested Development boxed set witha glass ofwine. One evening, whennot slumping, I was talkingto a neighbour’s nephewabout the subjects he was takingfor his GeneralCertificate ofSecondaryEducation(GCSE, the Britishsystemofpublic examinations takeninvarious subjects fromthe age ofabout 16), and I asked himwhat he wanted to do for a livinglater on. “I want to write computer games”, he said. “Awesome. What sort ofcomputer do youhave at home? I’ve got some programmingbooks youmight be interested in.” “AWiiand anXbox.” Ontalkingwithhima bit more, it became clear that this perfectlysmart kid had never done anyrealprogrammingat all; that there wasn’t anymachine that he could programinthe house; and that his informationand communicationtechnology(ICT) classes— where he shared a computer and was taught about web page design, usingspreadsheets and word processing—hadn’t really equipped himto use a computer eveninthe barest sense. But computer games were a passionfor him(and there’s nothing peculiar about wantingto work onsomethingyou’re passionate about). So that was what he was hopingthe GCSEsubjects he’d chosenwould enable himto do. He certainlyhad the artistic skills that the games industrylooks for, and his maths and science marks weren’t bad. But his schoolinghad skirted around anyprogramming—there were no Computingoptions onhis syllabus, just more ofthe same ICTclasses, withits emphasis onend users rather thanprogramming. And his home interactions withcomputingmeant that he stood a vanishinglysmallchance ofacquiringthe skills he needed inorder to do what he really wanted to do withhis life.
  • 13. This is the sort ofsituationI want to see the back of, where potentialand enthusiasmis squandered to no purpose. Now, obviously, I’mnot monomaniacalenoughto imagine that simplymakingthe RaspberryPiis enoughto effect allthe changes that are needed. But I do believe that it canact as a catalyst. We’re alreadyseeingbigchanges inthe UK schools’ curriculum, where Computingis arrivingonthe syllabus and ICTis beingreshaped, and we’ve seena massive change inawareness ofa gap inour educationaland culturalprovisionfor kids just inthe short time since the RaspberryPiwas launched. Too manyofthe computingdevices a child willinteract withdailyare so locked downthat theycan’t be used creativelyas a tool —eventhoughcomputingis a creative subject. Tryusingyour iPhone to act as the brains ofa robot, or gettingyour PS3 to play a game you’ve written. Sure, youcanprogramthe home PC, but there are significant barriers indoingthat whicha lot ofchildren don’t overcome:the need to download specialsoftware, and havingthe sort ofparents who aren’t worried about youbreaking somethingthat theydon’t knowhowto fix. And plentyofkids aren’t evenaware that doingsucha thingas programmingthe home PC is possible. Theythink ofthe PC as a machine withnice clickyicons that give youaneasywayto do the things you need to do so youdon’t need to think much. It comes ina sealed box, whichMumand Dad use to do the bankingand which willcost lots ofmoneyto replace ifsomethinggoes wrong! The RaspberryPiis cheap enoughto buywitha fewweeks’ pocket money, and youprobablyhave allthe equipment youneed to make it work:a TV, anSDcard that cancome fromanold camera, a mobile phone charger, a keyboard and a mouse. It’s not shared withthe family; it belongs to the kid; and it’s smallenoughto put ina pocket and take to a friend’s house. If somethinggoes wrong, it’s no bigdeal—youjust swap out a newSDcard and your RaspberryPiis factory-newagain. And all the tools, environments and learningmaterials that youneed to get started onthe long, smoothcurve to learninghowto program your RaspberryPiare right there, waitingfor youas soonas youturnit on. A bit of history I started work ona tiny, affordable, bare-bones computer about sixyears ago, whenI was a Director ofStudies inComputer Science at Cambridge University. I’d received a degree at the UniversityComputer Lab as wellas studyingfor a PhDwhile teachingthere, and over that period, I’d noticed a distinct decline inthe skillset ofthe youngpeople who were applyingto read Computer Science at the Lab. Froma positioninthe mid-1990s, when17-year-olds wantingto read Computer Science had come to the Universitywitha groundinginseveralcomputer languages, knewa bit about hardware hacking, and ofteneven worked inassemblylanguage, we graduallyfound ourselves ina positionwhere, by2005, those kids were arrivinghavingdone some HTML—witha bit ofPHP and CascadingStyle Sheets ifyouwere lucky. Theywere stillfearsomelyclever kids withlots ofpotential, but their experience withcomputers was entirelydifferent fromwhat we’d beenseeingbefore. The Computer Science course at Cambridge includes about 60 weeks oflecture and seminar time over three years. Ifyou’re usingthe whole first year to bringstudents up to speed, it’s harder to get themto a positionwhere theycanstart a PhDor go into industryover the next two years. The best undergraduates—the ones who performed the best at the end oftheir three-year course—were the ones who weren’t just programmingwhenthey’d beentold to for their weeklyassignment or for a class project. Theywere the ones who were programmingintheir spare time. So the initialidea behind the RaspberryPiwas a very parochialone witha verytight (and prettyunambitious) focus:I wanted to make a toolto get the smallnumber ofapplicants to this smalluniversitycourse a kick start. Mycolleagues and I imagined we’d hand out these devices to schoolkids at opendays, and iftheycame to Cambridge for aninterviewa fewmonths later, we’d ask what they’d done withthe free computer we’d giventhem. Those who had done somethinginterestingwould be the ones that we’d be interested inhavinginthe program. We thought maybe we’d make a fewhundred ofthese devices, or best case, a lifetime productionrunofa fewthousand. Ofcourse, once work was seriouslyunderwayonthe project, it became obvious that there was a lot more we could address witha cheap little computer like this. What we started withis a longwayindeed fromthe RaspberryPiyousee today. I began bysolderingup the longest piece ofbreadboard youcanbuyat MaplinwithanAtmelchip at our kitchentable, and the first crude prototypes used cheap microcontroller chips to drive a standard-definitionTVset directly. Withonly512 K ofRAM, and a fewMIPS ofprocessingpower, these prototypes were verysimilar inperformance to the original8-bit microcomputers. It was hard to imagine these machines capturingthe imaginations ofkids used to moderngames consoles and iPads. There had beendiscussions at the UniversityComputer Lab about the generalstate ofcomputer education, and whenI left the Lab for a non-academic job inthe industry, I noticed that I was seeingthe same issues inyoungjob applicants as I’d beenseeing at the University. So I got together withmycolleagues Dr Rob Mullins and Professor AlanMycroft (two colleagues fromthe Computer Lab), Jack Lang(who lectures inentrepreneurship at the University), Pete Lomas (a hardware guru) and David Braben(a Cambridge games industryleadinglight withaninvaluable address book), and over beers (and, inJack’s case, cheese and wine), we set up the RaspberryPiFoundation—a little charitywithbigideas. Why “Raspberry Pi”? We get askeda lot where the name “Raspberry Pi” came from. Bits of the name came fromdifferent trustees. It’s one of the very fewsuccessful bits
  • 14. of design by committee I’ve seen, andto be honest, Ihatedit at first. (Ihave since come to love the name, because it works really well—but it took a bit of getting usedto since I’dbeen calling the project the “ABC Micro” in my headforyears.) It’s “Raspberry” because there’s a long tradition of fruit names in computercompanies (besides the obvious, there are the oldTangerine andApricot computers—andwe like to think of the Acorn as a fruit as well). “Pi” is a mangling of “Python”, which we thought early on in development wouldbe the only programming language available on a much less powerful platformthan the Raspberry Pi we endedupwith. As it happens, we still recommendPython as ourfavourite language for learning anddevelopment, but there is a worldof otherlanguage options you can explore on the Raspberry Pi too. Inmynewrole as a chip architect at Broadcom, a bigsemiconductor company, I had access to inexpensive but high-performing hardware produced bythe companywiththe intentionofbeingused inveryhigh-end mobile phones—the sort withthe HD video and the 14-megapixelcameras. I was amazed bythe difference betweenthe chips youcould buyfor $10 as a small developer, and what youcould buyas a cell-phone manufacturer for roughlythe same amount ofmoney:generalpurpose processing, 3Dgraphics, video and memorybundled into a single BGApackage the size ofa fingernail. These microchips consume verylittle power, and have bigcapabilities. Theyare especiallygood at multimedia, and were alreadybeingused by set-top boxcompanies to playhigh-definitionvideo. Achip like this seemed the obvious next step for the shape the RaspberryPi was taking, so I worked ontapingout a low-cost variant that had anARM microprocessor onboard and could handle the processinggrunt we needed. We felt it was important to have a wayto get kids enthusiastic about usinga RaspberryPieveniftheydidn’t feelvery enthusiastic about programming. Inthe 1980s, ifyouwanted to playa computer game, youhad to boot up a boxthat went “bing”and fed youa command prompt. It required typinga little bit ofcode just to get started, and most users didn’t ever go beyond that—but some did, and got beguiled into learninghowto programbythat little bit ofinteraction. We realised that the RaspberryPicould work as a verycapable, verytiny, verycheap modernmedia centre, so we emphasised that capabilityto suck inthe unwary—withthe hope that they’d pick up some programmingwhile they’re at it. After about five years’ hard grind, we had created a verycute prototype board, about the size ofa thumb drive. We included a permanent camera module ontop ofthe board to demonstrate the sort ofperipherals that caneasilybe added, and brought it alongto a number ofmeetings withthe BBC’s R&Ddepartment. Those ofus who grewup inthe UK inthe 1980s had learned a lot about 8-bit computingfromthe BBC Microcomputer and the ecosystemthat had grownup around it—withBBC-produced books, magazines and TVprogrammes—so I’d hoped that theymight be interested indevelopingthe RaspberryPifurther. But as it turned out, somethinghas changed since we were kids:various competitionlaws inthe UK and the EUmeant that “the Beeb”couldn’t become involved inthe waywe’d hoped. Ina last-ditchattempt to get somethingorganised withthem, we ditched the R&Ddepartment idea and David (he ofthe giant address book) organised a meetingwithRoryCellan-Jones, a senior techjournalist, inMay2011. Rorydidn’t hold out muchhope for partnership withthe BBC, but he did ask ifhe could take a video ofthe little prototype board withhis phone, to put onhis blog. The next morning, Rory’s video had gone viral, and I realised that we had accidentallypromised the world that we’d make everybodya $25 computer. While Rorywent offto write another blogpost onexactlywhat it is that makes a video go viral, we went offto put our thinking caps on. That original, thumb-drive-sized prototype didn’t fit the bill:withthe camera included as standard, it was waytoo expensive to meet the cost modelwe’d suggested (the $25 figure came frommystatement to the BBC that the RaspberryPi should cost around the same as a text book, and is a splendid demonstrationofthe fact that I had no idea howmuchtext books cost these days), and the tinyprototype modeldidn’t have enoughroomaround its peripheryfor allthe ports we needed to make it as useable as we wanted it to be. So we spent a year workingonengineeringthe board to lower cost as muchas possible while retainingallthe features we wanted (engineeringcost downis a harder job thanyoumight think), and to get the RaspberryPias useable as possible for people who might not be able to afford muchinthe wayofperipherals. We knewwe wanted the RaspberryPito be used withTVs at home, just like the ZXSpectruminthe 1980s, savingthe user the cost ofa monitor. But not everybodyhas access to anHDMI television, so we added a composite port to make the Raspberry Piwork withanold cathode-raytelevisioninstead since SDcards are cheap and easyto find. We decided against microSDas the storage medium, because the little fingernail-sized cards are so flimsyinthe hands ofchildrenand so easyto lose. And we went throughseveraliterations ofpower supply, endingup witha micro USBcable. Recently, micro USBbecame the standard charger cable for mobile telephones across the EU(and it’s becomingthe standard everywhere), whichmeans the cables are becomingmore and more ubiquitous, and inmanycases, people alreadyhave themat home. Bythe end of2011, witha projected Februaryrelease date, it was becomingobvious to us that things were movingfaster, and demand was higher, thanwe were ever goingto be able to cope with. The initiallaunchwas always aimed at developers, with the educationallaunchplanned for later in2012. We have a smallnumber ofverydedicated volunteers, but we need the wider Linuxcommunityto help us prepare a software stack and ironout anyearly-life niggles withthe board before releasinginto the educationalmarket. We had enoughcapitalinthe Foundationto buythe parts for and build 10,000 RaspberryPis over a period ofa monthor so, and we thought that the people inthe communitywho would be interested inanearlyboard would come to around that number. Fortunatelyand unfortunately, we’d beenreallysuccessfulinbuildinga bigonline communityaround the device, and interest wasn’t limited to the UK, or to the educationalmarket. Tenthousand was lookingless and less realistic.
  • 15. OurCommunity The Raspberry Pi community is one of the things we’re proudest of. We startedwith a very bare-bones blog at www.raspberrypi.org just afterRory’s May 2011 video, andput upa forumon the same website shortly afterthat. That forumnowhas more than 20,000 members—between themthey’ve contributedmore than 100,000 posts of wit andwisdomabout the Raspberry Pi. If there’s any question, no matterhowabstruse, that you want to ask about the Raspberry Pi orabout programming in general, someone there will have the answer(if it’s not in this book, you’ll findit in the forums). Part of my jobat Raspberry Pi involves giving talks to hackergroups, computing conferences, teachers, programming collectives andthe like, and there’s always someone in the audience who has talkedto me orto my wife Liz (who runs the community) on the Raspberry Pi website—andsome of these people have become goodfriends of ours. The Raspberry Pi website gets aroundone request every single secondof the day. There are nowhundreds of fan sites out there. There’s also a fan magazine calledThe MagPi (a free downloadfromwww.themagpi.com), which is producedmonthly by community members, with type-in listings, lots of articles, project guides, tutorials andmore. Type-in games in magazines and books providedan easy route into programming forme—my earliest programming experience with the BBC Micro was of modifying a type-in helicoptergame to addenemies andpick-ups. We blog something interesting about the device at www.raspberrypi.org at least once every day. Come andjoin in the conversation! There were 100,000 people onour mailinglist wantinga RaspberryPi—and theyallput anorder inondayone! Not surprisingly, this brought up a fewissues. First off, there are the inevitable paper cuts you’re goingto get boxingup 100,000 little computers and mailingthemout—and the fact was that we had absolutelyno moneyto hire people to do this for us. We didn’t have a warehouse—we had Jack’s garage. There was no waywe could raise the moneyto build 100,000 units at once—we’d envisaged makingtheminbatches of 2,000 everycouple ofweeks, which, withthis levelofinterest, was goingto take so longthat the thingwould be obsolete before we managed to fulfilallthe orders. Clearly, manufacturingand distributionwere somethingwe were goingto have to give up on and hand over to somebodyelse who alreadyhad the infrastructure and capitalto do that, so we got intouchwithelement14 and RS Components, bothUK microelectronics suppliers withworldwide businesses, and contracted withthemto do the actual manufacture and distributionside ofthings worldwide so we could concentrate ondevelopment and the RaspberryPi Foundation’s charitable goals. Demand onthe first daywas stillso large that RS and element14’s websites bothcrashed for most ofthe day—at one point in the day, element14 were gettingsevenorders a second, and for a couple ofhours onFebruary29, Google showed more searches were made worldwide for “RaspberryPi”thanwere made for “LadyGaga”. I’mwritingthis inearlyJune 2012, and orders inthe three months since we opened for business have topped halfa millionunits, eventhoughwe’re stillat a point when neither companywillsellyoumore thanone RaspberryPi(they’re tryingto get rid oftheir order backlogs before theyturnonthe abilityto multiorder). At this point, ifwe’d gone withour originalplans, we’d have made 100 or so ofthese devices for Universityopendays, and that would have beenit. There is nothingthat affects the blood pressure quite like accidentallyendingup runninga large computer company! So what can you do with the Raspberry Pi? This book explores a number ofthings youcando withyour RaspberryPi, fromcontrollinghardware withPython, to usingit as a media centre, or buildinggames inScratch. The beautyofthe RaspberryPiis that it’s just a verytinygeneral-purpose computer (whichmaybe a little slower thanyou’re used to for some desktop applications, but muchbetter at some other stuff thana regular PC), so youcando anythingyoucould do ona regular computer withit. Inaddition, the RaspberryPihas powerfulmultimedia and 3Dgraphics capabilities, so it has the potentialto be used as a games platform, and we verymuchhope to see people startingto write games for it. We think physicalcomputing—buildingsystems usingsensors, motors, lights and microcontrollers—is somethingthat gets overlooked infavour ofpure software projects ina lot ofinstances, and it’s a shame, because physicalcomputingis massive fun. To the extent that there’s anychildren’s computingmovement at the moment, it’s a physicalcomputingmovement. The LOGO turtles that represented physicalcomputingwhenwe were kids are nowfightingrobots, quadcopters or parent-sensingbedroom doors, and we love it. However, the lack ofGeneralPurpose Input/Output (GPIO) onhome PCs is a realhandicap for many people gettingstarted withrobotics projects. The RaspberryPiexposes GPIO so youcanget to work straight away. I keep beingsurprised byideas the communitycomes up withwhichwouldn’t have crossed mymind ina thousand years:the Australianschoolmeteor-trackingproject; the BoreattonScouts inthe UK and their robot, whichis controlled via an electroencephalographyheadset (the world’s first robot controlled byScoutingbrainwaves); the familywho are buildinga robot vacuumcleaner. And I’ma realspace cadet, so readingabout the people sendingRaspberryPis into near-earthorbit onrockets and balloons gives me goosebumps. Success for us would be another 1,000 people everyyear takingup Computer Science at the universitylevelinthe UK. That would not onlybe beneficialfor the country, the software and hardware industries, and the economy; but it would be evenmore beneficialfor everyone ofthose 1,000 people, who, I hope, discover that there’s a whole world ofpossibilities and a great deal
  • 16. offunto be had out there. Buildinga robot whenyou’re a kid cantake youto places younever imagined—I knowbecause it happened to me! —EbenUpton
  • 17. Part I: Connecting the Board Chapter 1:Meet the RaspberryPi Chapter 2:LinuxSystemAdministration Chapter 3:Troubleshooting Chapter 4:Network Configuration Chapter 5:PartitionManagement Chapter 6:Configuringthe RaspberryPi
  • 18. Chapter 1: Meet the Raspberry Pi YourRaspberry Pi board is a miniature marvel, packingconsiderable computingpower into a footprint no larger thana credit card. It’s capable ofsome amazingthings, but there are a fewthings you’re goingto need to knowbefore youplunge head-first into the bramble patch. If you’re eagerto get started, skipaheada couple of pages to findout howto connect yourRaspberry Pi to a display, keyboardandmouse. ARM vs. x86 The processor at the heart ofthe RaspberryPisystemis a BroadcomBCM2835 system-on-chip (SoC) multimedia processor. This means that the vast majorityofthe system’s components, includingits centraland graphics processingunits alongwiththe audio and communications hardware, are built onto that single component hiddenbeneaththe 256 MBmemorychip at the centre ofthe board (see Figure 1-1). It’s not just this SoC designthat makes the BCM2835 different to the processor found inyour desktop or laptop, however. It also uses a different instructionset architecture (ISA), knownas ARM. Figure 1-1:The BCM2835 SoC, located beneatha Hynixmemorychip Developed byAcornComputers back inthe late 1980s, the ARM architecture is a relativelyuncommonsight inthe desktop world. Where it excels, however, is inmobile devices:the phone inyour pocket almost certainlyhas at least one ARM-based processingcore hiddenawayinside. Its combinationofa simple reduced instructionset (RISC) architecture and lowpower drawmake it the perfect choice over desktop chips withhighpower demands and complexinstructionset (CISC) architectures. The ARM-based BCM2835 is the secret ofhowthe RaspberryPiis able to operate onjust the 5V1Apower supplyprovided bythe onboard micro-USBport. It’s also the reasonwhyyouwon’t find anyheat-sinks onthe device:the chip’s lowpower drawdirectlytranslates into verylittle waste heat, evenduringcomplicated processingtasks. It does, however, meanthat the RaspberryPiisn’t compatible withtraditionalPC software. The majorityofsoftware for desktops and laptops is built withthe x86 instructionset architecture inmind, as found inprocessors fromthe likes ofAMD, Inteland VIA. As a result, it won’t runonthe ARM-based RaspberryPi. The BCM2835 uses a generationofARM’s processor designknownas ARM11, whichinturnis designed around a versionof the instructionset architecture knownas ARMv6. This is worthremembering:ARMv6 is a lightweight and powerfularchitecture, but has a rivalinthe more advanced ARMv7 architecture used bythe ARM Cortexfamilyofprocessors. Software developed
  • 19. for ARMv7, like software developed for x86, is sadlynot compatible withthe RaspberryPi’s BCM2835—althoughdevelopers canusuallyconvert the software to make it suitable. That’s not to sayyou’re goingto be restricted inyour choices. As you’lldiscover later inthe book, there is plentyofsoftware available for the ARMv6 instructionset, and as the RaspberryPi’s popularitycontinues to grow, that willonlyincrease. Inthis book, you’llalso learnhowto create your ownsoftware for the Pievenifyouhave no experience withprogramming. Windows vs. Linux Another important difference betweenthe RaspberryPiand your desktop or laptop, other thanthe size and price, is the operatingsystem—the software that allows youto controlthe computer. The majorityofdesktop and laptop computers available todayrunone oftwo operatingsystems:Microsoft Windows or Apple OS X. Bothplatforms are closed source, created ina secretive environment usingproprietarytechniques. These operatingsystems are knownas closed source for the nature oftheir source code, the computer-language recipe that tells the systemwhat to do. Inclosed-source software, this recipe is kept a closely-guarded secret. Users are able to obtainthe finished software, but never to see howit’s made. The RaspberryPi, bycontrast, is designed to runanoperatingsystemcalled GNU/Linux—hereafter referred to simplyas Linux. Unlike Windows or OS X, Linuxis opensource:it’s possible to download the source code for the entire operatingsystemand make whatever changes youdesire. Nothingis hidden, and allchanges are made infullviewofthe public. This opensource development ethos has allowed Linuxto be quicklyaltered to runonthe RaspberryPi, a process knownas porting. At the time ofthis writing, severalversions ofLinux—knownas distributions—have beenported to the RaspberryPi’s BCM2835 chip, includingDebian, Fedora Remixand ArchLinux. The different distributions cater to different needs, but theyallhave somethingincommon:they’re allopensource. They’re also all, byand large, compatible witheachother:software writtenona Debiansystemwilloperate perfectlywellonArchLinuxand vice versa. Linuxisn’t exclusive to the RaspberryPi. Hundreds ofdifferent distributions are available for desktops, laptops and evenmobile devices; and Google’s popular Android platformis developed ontop ofa Linuxcore. Ifyoufind that youenjoythe experience ofusingLinuxonthe RaspberryPi, youcould consider addingit to other computingdevices youuse as well. It willhappily coexist withyour current operatingsystem, allowingyouto enjoythe benefits ofbothwhile givingyoua familiar environment whenyour Piis unavailable. As withthe difference betweenARM and x86, there’s a keypoint to make about the practicaldifference betweenWindows, OS Xand Linux:software writtenfor Windows or OS Xwon’t runonLinux. Thankfully, there are plentyofcompatible alternatives for the overwhelmingmajorityofcommonsoftware products—better still, the majorityare free to use and as open source as the operatingsystemitself. Getting Started with the Raspberry Pi Nowthat youhave a basic understandingofhowthe Pidiffers fromother computingdevices, it’s time to get started. Ifyou’ve just received your Pi, take it out ofits protective anti-static bagand place it ona flat, non-conductive surface before continuing withthis chapter. Connecting a Display Before youcanstart usingyour RaspberryPi, you’re goingto need to connect a display. The Pisupports three different video outputs:composite video, HDMI video and DSI video. Composite video and HDMI video are readilyaccessible to the end user, as described inthis section, while DSI video requires some specialised hardware. Composite Video Composite video, available via the yellow-and-silver port at the top ofthe Piknownas anRCAphono connector (see Figure 1- 2), is designed for connectingthe RaspberryPito older displaydevices. As the name suggests, the connector creates a composite ofthe colours found withinanimage—red, greenand blue—and sends it downa single wire to the displaydevice, typicallyanold cathode-raytube (CRT) TV.
  • 20. Figure 1-2:The yellowRCAphono connector, for composite video output Whenno other displaydevice is available, a composite video connectionwillget youstarted withthe Pi. The quality, however, isn’t great. Composite video connections are significantlymore prone to interference, lack clarityand runat a limited resolution, meaningthat youcanfit fewer icons and lines oftext onthe screenat once. HDMI Video Abetter-qualitypicture canbe obtained usingthe HDMI (HighDefinitionMultimedia Interface) connector, the onlyport found onthe bottomofthe Pi(see Figure 1-3). Unlike the analogue composite connection, the HDMI port provides a high-speed digitalconnectionfor pixel-perfect pictures onbothcomputer monitors and high-definitionTVsets. Usingthe HDMI port, a Pi candisplayimages at the FullHD1920x1080 resolutionofmost modernHDTVsets. At this resolution, significantlymore detail is available onthe screen. Ifyou’re hopingto use the Piwithanexistingcomputer monitor, youmayfind that your displaydoesn’t have anHDMI input. That’s not a disaster:the digitalsignals present onthe HDMI cable map to a commoncomputer monitor standard called DVI (DigitalVideo Interconnect). BypurchasinganHDMI-to-DVI cable, you’llbe able to connect the Pi’s HDMI port to a monitor withDVI-Dconnectivity. Figure 1-3:The silver HDMI connector, for high-definitionvideo output
  • 21. Ifyour monitor has a VGAinput—a D-shaped connector with15 pins, typicallycoloured silver and blue—the RaspberryPi can’t connect to it. Adapters are available that willtake ina digitalDVI signaland convert it to ananalogue VGAsignal, but these are expensive and bulky. The best optionhere is simplyto buya more-modernmonitor witha DVI or HDMI input. DSI Video The finalvideo output onthe Picanbe found above the SDcard slot onthe top ofthe printed circuit board—it’s a smallribbon connector protected bya layer ofplastic. This is for a video standard knownas DisplaySerialInterface (DSI), whichis used in the flat-paneldisplays oftablets and smartphones. Displays witha DSI connector are rarelyavailable for retailpurchase, and are typicallyreserved for engineers lookingto create a compact, self-contained system. ADSI displaycanbe connected byinserting a ribboncable into the matched connector onthe Pi, but for beginners, the use ofa composite or HDMI displayis recommended. Connecting Audio Ifyou’re usingthe RaspberryPi’s HDMI port, audio is simple:whenproperlyconfigured, the HDMI port carries boththe video signaland a digitalaudio signal. This means that youcanconnect a single cable to your displaydevice to enjoybothsound and pictures. Assumingyou’re connectingthe Pito a standard HDMI display, there’s verylittle to do at this point. For now, it’s enoughto simplyconnect the cable. Ifyou’re usingthe Piwitha DVI-Dmonitor via anadapter or cable, audio willnot be included. This highlights the maindifference betweenHDMI and DVI:while HDMI cancarryaudio signals, DVI cannot. For those withDVI-Dmonitors, or those usingthe composite video output, a black 3.5 mmaudio jack located onthe top edge ofthe Pinext to the yellowphono connector provides analogue audio (see Figure 1-2). This is the same connector used for headphones and microphones onconsumer audio equipment, and it’s wired inexactlythe same way. Ifyouwant, youcansimply connect a pair ofheadphones to this port for quick access to audio. While headphones can be connecteddirectly to the Raspberry Pi, you may findthe volume a little lacking. If possible, connect a pairof powered speakers instead. The amplifierinside will helpboost the signal to a more audible level. Ifyou’re lookingfor somethingmore permanent, youcaneither use standard PC speakers that have a 3.5 mmconnector or you canbuysome adapter cables. For composite video users, a 3.5 mmto RCAphono cable is useful. This provides the two white- and-red RCAphono connections that sit alongside the video connection, eachcarryinga channelofthe stereo audio signalto the TV. For those connectingthe Pito anamplifier or stereo system, you’lleither need a 3.5 mmto RCAphono cable or a 3.5 mmto 3.5 mmcable, dependingonwhat spare connections youhave onyour system. Bothcable types are readilyand cheaply
  • 22. available at consumer electronics shops, or canbe purchased evencheaper at online retailers suchas Amazon. Connecting a Keyboard and Mouse Nowthat you’ve got your RaspberryPi’s output devices sorted, it’s time to think about input. As a bare minimum, you’re going to need a keyboard, and for the majorityofusers, a mouse or trackballis a necessitytoo. First, some bad news:ifyou’ve got a keyboard and mouse witha PS/2 connector—a round plugwitha horseshoe-shaped array ofpins—thenyou’re goingto have to go out and buya replacement. The old PS/2 connectionhas beensuperseded, and the Pi expects your peripherals to be connected over the UniversalSerialBus (USB) port. Dependingonwhether youpurchased the ModelAor ModelB, you’llhave either one or two USBports available onthe right side ofthe Pi(see Figure 1-4). Ifyou’re usingModelB, youcanconnect the keyboard and mouse directlyto these ports. If you’re usingModelA, you’llneed to purchase a USBhub inorder to connect two USBdevices simultaneously. Figure 1-4:ModelB’s two USBports AUSBhub is a good investment for anyPiuser:evenifyou’ve got a ModelB, you’lluse up bothyour available ports just connectingyour keyboard and mouse, leavingnothingfree for additionaldevices suchas anexternalopticaldrive, storage device or joystick. Make sure youbuya powered USBhub:passive models are cheaper and smaller, but lack the abilityto runcurrent- hungrydevices like CDdrives and externalhard drives. If you want to reduce the numberof powersockets in use, connect the Raspberry Pi’s USBpowerleadto yourpoweredUSBhub. This way, the Pi can drawits powerdirectly fromthe hub, ratherthan needing its own dedicatedpowersocket andmains adapter. This will only work on hubs with a powersupply capable of providing 700mAto the Pi’s USBport, along with whateverpoweris requiredby otherperipherals. Connectingthe keyboard and mouse is as simple as pluggingtheminto the USBports, either directlyinthe case ofa ModelB or via a USBhub inthe case ofa ModelA. A Note on Storage As you’veprobably noticed, theRaspberry Pi doesn’t haveatraditional hard drive. Instead it uses aSecureDigital (SD) memory card, asolid-statestorage systemtypically used in digital cameras. Almost any SD card will work with theRaspberry Pi, but becauseit holds theentireoperatingsystem, it is necessary for thecard to beat least 2 GBin capacity to storeall therequired files. SD cards with theoperatingsystempreloaded areavailablefromtheofficial Raspberry Pi Storealongwith numerous other sites on theInternet. If you’ve
  • 23. purchased oneof these, or received it in abundlewith your Pi, you can simply plugit in to theSD card slot on thebottomsideof theleft-hand edge. If not, you’ll need to install an operatingsystem—known as flashing—onto thecard beforeit’s ready to go. SomeSD cards work better than others, with somemodels refusingto work at all with theRaspberry Pi. For an up-to-datelist of SD card models known to work with thePi, visit theeLinuxWiki page: http://www.elinux.org/RPi_VerifiedPeripherals#SD_cards Flashing the SD Card To prepare a blank SDcard for use withthe RaspberryPi, you’llneed to flashanoperatingsystemonto the card. While this is slightlymore complicated thansimplydraggingand droppingfiles onto the card, it shouldn’t take more thana fewminutes to complete. Firstly, you’llneed to decide whichLinuxdistributionyouwould like to use withyour RaspberryPi. Eachhas its advantages and disadvantages. Don’t worryifyouchange your mind later and want to trya different versionofLinux:anSDcard canbe flashed againwitha newoperatingsystemat anypoint. The most up-to-date list ofLinuxreleases compatible withthe Piis available fromthe RaspberryPiwebsite at http://www.raspberrypi.org/downloads. The Foundationprovides BitTorrent links for eachdistribution. These are smallfiles that canbe used withBitTorrent software to download the files fromother users. Usingthese links is anefficient and fast wayto distribute large files, and keeps the Foundation’s download servers frombecomingoverloaded. To use a BitTorrent link, you’llneed to have a compatible client installed. Ifyoudon’t alreadyhave a BitTorrent client installed, download one and installit before tryingto download the RaspberryPiLinuxdistribution. One client for Windows, OS Xand Linuxis µTorrent, available fromhttp://www.utorrent.com/downloads. Whichdistributionyouchoose to download is up to you. Instructions inthe rest ofthe book willbe based onthe Debian RaspberryPidistribution, a good choice for beginners. Where possible, we’llgive youinstructions for other distributions as well. Linuxdistributions for the RaspberryPiare provided as a single image file, compressed to make it faster to download. Once you’ve downloaded the Zip archive (a compressed file, whichtakes less time to download thanthe uncompressed files would) for your chosendistribution, you’llneed to decompress it somewhere onyour system. Inmost operatingsystems, youcansimply double-click the file to openit, and thenchoose Extract or Unzip to retrieve the contents. After you’ve decompressed the archive, you’llend up withtwo separate files. The file endinginsha1 is a hash, whichcanbe used to verifythat the download hasn’t beencorrupted intransit. The file endinginimg contains anexact copyofanSDcard set up bythe distribution’s creators ina waythat the RaspberryPiunderstands. This is the file that needs to be flashed to the SD card. During the following, you’ll be using a software utility calleddd. Usedincorrectly dd will happily write the image to yourmain harddrive, erasing youroperating systemandall yourstoreddata. Make sure you readthe instructions in each section thoroughly andnote the device address of your SD cardcarefully. Readtwice, write once! Flashing from Linux Ifyour current PC is runninga variant ofLinuxalready, youcanuse the dd command to write the contents ofthe image file out to the SDcard. This is a text-interface programoperated fromthe command prompt, knownas a terminalinLinuxparlance. Followthese steps to flashthe SDcard: 1. Opena terminalfromyour distribution’s applications menu. 2. Plugyour blank SDcard into a card reader connected to the PC. 3. Type sudo fdisk -l to see a list ofdisks. Find the SDcard byits size, and note the device address (/dev/sdX, where Xis a letter identifyingthe storage device. Some systems withintegrated SDcard readers mayuse the alternative format /dev/mmcblkX—ifthis is the case, remember to change the target inthe followinginstructions accordingly). 4. Use cd to change to the directorywiththe .img file youextracted fromthe Zip archive. 5. Type sudo dd if=imagefilename.img of=/dev/sdX bs=2M to write the file imagefilename.img to the SDcard connected to the device address fromstep 3. Replace imagefilename.imgwiththe actualname ofthe file extracted fromthe Zip archive. This step takes a while, so be patient! Duringflashing, nothingwillbe shownonthe screenuntilthe process is fullycomplete (see Figure 1-5).
  • 24. Figure 1-5:Flashingthe SDcard usingthe dd command inLinux Flashing from OS X Ifyour current PC is a Mac runningApple OS X, you’llbe pleased to hear that things are as simple as withLinux. Thanks to a similar ancestry, OS Xand Linuxbothcontainthe dd utility, whichyoucanuse to flashthe systemimage to your blank SDcard as follows: 1. Select Utilities fromthe Applicationmenu, and thenclick onthe Terminalapplication. 2. Plugyour blank SDcard into a card reader connected to the Mac. 3. Type diskutil list to see a list ofdisks. Find the SDcard byits size, and note the device address (/dev/diskX, where Xis a letter identifyingthe storage device). 4. Ifthe SDcard has beenautomaticallymounted and is displayed onthe desktop, type diskutil unmountdisk /dev/diskXto unmount it before proceeding. 5. Use cd to change to the directorywiththe .img file youextracted fromthe Zip archive. 6. Type dd if=imagefilename.img of=/dev/diskX bs=2M to write the file imagefilename.img to the SDcard connected to the device address fromstep 3. Replace imagefilename.imgwiththe actualname ofthe file extracted fromthe Zip archive. This step takes a while, so be patient! Flashing from Windows Ifyour current PC is runningWindows, things are slightlytrickier thanwithLinuxor OS X. Windows does not have a utilitylike dd, so some third-partysoftware is required to get the image file flashed onto the SDcard. Althoughit’s possible to installa Windows-compatible versionofdd, there is aneasier way:the Image Writer for Windows. Designed specificallyfor creating USBor SDcard images ofLinuxdistributions, it features a simple graphicaluser interface that makes the creationofa RaspberryPiSDcard straightforward. The latest versionofImage Writer for Windows canbe found at the officialwebsite:https://launchpad.net/win32- image-writer. Followthese steps to download, installand use the Image Writer for Windows software to prepare the SD card for the Pi: 1. Download the binary(not source) Image Writer for Windows Zip file, and extract it to a folder onyour computer. 2. Plugyour blank SDcard into a card reader connected to the PC. 3. Double-click the Win32DiskImager.exe file to openthe program, and click the blue folder iconto opena file browse dialogue box. 4. Browse to the imagefilename.img file youextracted fromthe distributionarchive, replacingimagefilename.imgwiththe actualname ofthe file extracted fromthe Zip archive, and thenclick the Openbutton. 5. Select the drive letter correspondingto the SDcard fromthe Device drop-downdialogue box. Ifyou’re unsure which
  • 25. drive letter to choose, openMyComputer or Windows Explorer to check. 6. Click the Write buttonto flashthe image file to the SDcard. This process takes a while, so be patient! No matterwhich operating systemyou’re writing from, it’s important to ensure you leave the SD cardconnecteduntil the image has been completely written. If you don’t, you may findthat Pi doesn’t boot when the SD cardis connected. If this happens, start the process again. When the image has been flashedonto the SD card, remove it fromthe computerandinsert it into the Raspberry Pi’s SD cardslot, located underneath the circuit board. The SD cardshouldbe insertedwith the label facing away fromthe boardandpushedfully home to ensure a good connection. Connecting External Storage While the RaspberryPiuses anSDcard for its mainstorage device—knownas a boot device—youmayfind that youruninto space limitations quite quickly. Althoughlarge SDcards holding32 GB, 64 GBor more are available, theyare oftenprohibitively expensive. Thankfully, there are devices that provide anadditionalhard drive to anycomputer whenconnected via a USBcable. Knownas USBMass Storage (UMS) devices, these canbe physicalhard drives, solid-state drives (SSDs) or evenportable pocket-sized flashdrives (see Figure 1-6). Figure 1-6:Two USBMass Storage devices:a pendrive and anexternalhard drive The majorityofUSBMass Storage devices canbe read bythe Pi, whether or not theyhave existingcontent. Inorder for the Pi to be able to access these devices, their drives must be mounted—a process youwilllearninChapter 2, “LinuxSystem Administration”. For now, it’s enoughto connect the drives to the Piinreadiness. Connecting the Network While the majorityofthese setup instructions are equallyapplicable to boththe RaspberryPiModelAand the ModelB, networkingis a specialexception. To keep the component count—and therefore the cost—as lowas possible, the ModelA doesn’t feature anyonboard networking. Thankfully, that doesn’t meanyoucan’t network the ModelA; onlythat you’llneed some additionalequipment to do so. Networking the Model A To givetheModel A thesamenetworkingcapabilities as its moreexpensiveModel Bcounterpart, you’ll need aUSB-connected Ethernet adapter. This connects to afreeUSBport on theRaspberry Pi or aconnected hub and provides awired Ethernet connection with an RJ45 connector, thesameas is availableon theModel B. A 10/100 USBEthernet adapter—with thenumbers referringto its two-speed mode, 10 Mb/s and 100 Mb/s—can bepurchased fromonlineretailers for very littlemoney. When buyingan Ethernet adapter, besureto check that Linuxis listed as asupported operatingsystem. A few models only work with Microsoft Windows, and areincompatiblewith theRaspberry Pi.
  • 26. Don’t betempted to go for agigabit-class adapter, which will bereferred to as a10/100/1000 USBEthernet adapter. Standard USBports, as used on the Raspberry Pi, can’t copewith thespeed of agigabit Ethernet connection, and you’ll seeno benefit to themoreexpensiveadapter. Wired Networking To get your RaspberryPionthe network, you’llneed to connect anRJ45 Ethernet patchcable betweenthe Piand a switch, router or hub. Ifyoudon’t have a router or hub, youcanget your desktop or laptop talkingto the Pibyconnectingthe two directlytogether witha patchcable. Usually, connectingtwo network clients together inthis wayrequires a specialcable, knownas a crossover cable. Ina crossover cable, the receive and transmit pairs are swapped so that the two devices are prevented fromtalkingover eachother—a task usuallyhandled bya network switchor hub. The RaspberryPiis cleverer thanthat, however. The RJ45 port onthe side ofthe Pi(see Figure 1-7) includes a feature known as auto-MDI, whichallows it to reconfigure itselfautomatically. As a result, youcanuse anyRJ45 cable—crossover or not—to connect the Pito the network, and it willadjust its configurationaccordingly. Figure 1-7:The RaspberryPiModelB’s Ethernet port Ifyoudo connect the Pidirectlyto a PC or laptop, youwon’t be able to connect out onto the Internet bydefault. To do so, you’llneed to configure your PC to bridge the wired Ethernet port and another (typicallywireless) connection. Doingso is outside the scope ofthis book, but ifyouare completelyunable to connect the Pito the Internet inanyother way, youcantry searchingyour operatingsystem’s help file for “bridge network”to find more guidance. Witha cable connected, the Piwillautomaticallyreceive the details it needs to access the Internet whenit loads its operating systemthroughthe Dynamic Host ConfigurationProtocol(DHCP). This assigns the PianInternet Protocol(IP) address onyour network, and tells it the gatewayit needs to use to access the Internet (typicallythe IP address ofyour router or modem). For some networks, there is no DHCP server to provide the PiwithanIP address. Whenconnected to sucha network, the Pi willneed manualconfiguration. You’lllearnmore about this inChapter 4, “Network Configuration”. Wireless Networking Current RaspberryPimodels don’t feature anyformofwireless network capabilityonboard, but—as withaddingwired Ethernet to the ModelA—it’s possible to add Wi-Fisupport to anyPiusinga USBwireless adapter (see Figure 1-8).
  • 27. Figure 1-8:Two USBwireless adapters, suitable for use withthe RaspberryPi Usingsucha device, the Picanconnect to a wide range ofwireless networks, includingthose runningonthe latest 802.11nhigh- speed standard. Before purchasinga USBwireless adapter, check the following: • Ensure that Linuxis listed as a supported operatingsystem. Some wireless adapters are provided withdrivers for Windows and OS Xonly, makingthemincompatible withthe RaspberryPi. Alist ofWi-Fiadapters knownto work withthe RaspberryPicanbe found onthe followingwebsite: http://elinux.org/RPi_VerifiedPeripherals#USB_WiFi_Adapters • Ensure that your Wi-Finetwork type is supported bythe USBwireless adapter. The network type willbe listed inthe specifications as a number followed bya letter. Ifyour network type is 802.11a, for example, an802.11gwireless adapter won’t work. • Check the frequencies supported bythe card. Some wireless network standards, like 802.11a, support more thanone frequency. Ifa USBwireless adapter is designed to work ona 2.4GHznetwork, it won’t connect to a 5GHznetwork. • Check the encryptiontype used byyour wireless network. Most modernUSBwireless adapters support allforms of encryption, but ifyou’re buyinga second-hand or older model, youmayfind it won’t connect to your network. Common encryptiontypes include the outdated WEP and more modernWPAand WPA2. Configurationofthe wireless connectionis done withinLinux, so for nowit’s enoughto simplyconnect the adapter to the Pi (ideallythrougha powered USBhub.) You’lllearnhowto configure the connectioninChapter 4, “Network Configuration”. Connecting Power The RaspberryPiis powered bythe smallmicro-USBconnector found onthe lower left side ofthe circuit board. This connector is the same as found onthe majorityofsmartphones and some tablet devices. Manychargers designed for smartphones willwork withthe RaspberryPi, but not all. The Piis more power-hungrythanmost micro-USBdevices, and requires up to 700mAinorder to operate. Some chargers canonlysupplyup to 500mA, causing intermittent problems inthe Pi’s operation(see Chapter 3, “Troubleshooting”). Connectingthe Pito the USBport ona desktop or laptop computer is possible, but not recommended. As withsmaller chargers, the USBports ona computer can’t provide the power required for the Pito work properly. Onlyconnect the micro-USBpower supplywhenyouare readyto start usingthe Pi. Withno power buttononthe device, it will start workingthe instant power is connected and canonlybe turned offagainbyphysicallyremovingthe power cable.
  • 28. Chapter 2: Linux System Administration The majority of modernLinuxdistributions are user-friendly, witha graphicaluser interface (GUI) that provides aneasywayto performcommontasks. It is, however, quite different to bothWindows and OS X, so ifyou’re goingto get the most out ofyour RaspberryPi, you’llneed a quick primer inusingthe operatingsystem. Linux: An Overview As brieflyexplained inChapter 1, “Meet the RaspberryPi”, Linuxis anopen-source project whichwas originallyfounded to produce a kernelthat would be free for anyone to use. The kernelis the heart ofanoperatingsystem, and handles the communicationbetweenthe user and the hardware. Althoughonlythe kernelitselfis rightlycalled Linux, the termis oftenused to refer to a collectionofdifferent open-source projects froma varietyofcompanies. These collections come together to formdifferent flavours ofLinux, knownas distributions. The originalversionofLinuxwas combined witha collectionoftools created bya group called GNU. The resultingsystem, knownas GNU/Linux, was basic but powerful. Unlike other operatingsystems ofthe era, it offered facilities like multiple user accounts where severalusers canshare a single computer. That’s somethingrivalclosed-source operatingsystems have takenon board, withbothWindows and OS Xnowsupportingmultiple user accounts onthe same system. It’s also stillpresent inLinux, and provides securityand protectionfor the operatingsystem. InLinux, you’llspend most ofyour time runninga restricted user account. This doesn’t meanyou’re beinglimited inwhat you cando. Instead, it prevents youfromaccidentallydoingsomethingthat willbreak the software onyour RaspberryPi. It also prevents viruses and other malware frominfectingthe systembylockingdownaccess to criticalsystemfiles and directories. Before youcanget started, it’s worthbecomingfamiliar withsome ofthe terms and concepts used inthe world ofLinux, as defined inTable 2-1. Evenifyou’re experienced withother operatingsystems, it’s a good idea to reviewthis table before bootingup your Pifor the first time. The Terminal and the GUI As in OSX and Windows, therearetypically two main ways to achieveagiven goal in Linux: through thegraphical user interface(GUI) and through the command line(known in Linuxparlanceas theconsoleor theterminal). Theappearanceof various Linuxdistributions can bequitedifferent, dependingon thedesktop environment in use. In this book, therecommended Debian distribution is used, but most of thecommands you will belearningareentered at theterminal and aretypically thesameacross all distributions. Whereother distributions differ, you will begiven alternativemethods of achievingthesamegoals. Table 2.1 The Quick Linux Glossary Term /Concept Definition Bash The most popular shell choice, used in the majority of Linux distributions. Bootloader Software responsible for loading the Linux kernel. The most common is GRUB. Console A version of the terminal which is always available, and the first thing you see on the Pi. Desktop environment Software to make the GUI lookpretty. GNOME and KDE are popular desktop environments. Directory The Linux term for what Windows calls folders, where files are stored. Distribution A particular version of Linux. Fedora Remix, Arch and Debian are distributions. Executable A file that can be run as a program. Linux files must be marked executable in order to run. EXT2/3/4 The EXTended file system, the most common format used in Linux. File system The way a hard drive or other storage device is formatted so it’s ready for file storage. GNOME One of the most common Linux desktop environments around. GNU A free software project, which provides many of the tools used in Linux distributions. GRUB The GRand Unified Bootloader, created by GNU and used to load the Linux kernel. GUI A graphical user interface, in which the user operates the computer via a mouse or touch. KDE Another extremely popular Linux desktop environment. Linux Properly, the kernel used by GNU/Linux. Popularly, an open-source operating system. Live CD A Linux distribution provided as a CD or DVD, which doesn’t require installation.
  • 29. Package A collection of files required to run an application, typically handled by the package manager. Package manager A tool for keeping trackof, and installing new, software. Partition A section of a hard drive which is ready to have a file system applied to it for storage. Root The main user account in Linux, equivalent to the Windows administrator account. Shell A text-based command prompt, loaded in a terminal. sudo A program that allows restricted users to run a command as the root user. Superuser See Root. Terminal A text-based command prompt in which the user interacts with a shell program. X11 The X Window system, a package that provides a graphical user interface (GUI). Linux Basics Althoughthere are hundreds ofdifferent Linuxdistributions available, theyallshare a commonset oftools. These tools, which are operated via the terminal, are analogous to similar tools onWindows and OS X. To get started, you’llneed to learnthe followingcommands: • ls—Short for listing, ls provides a list ofthe contents ofthe current directory. Alternatively, it canbe called withan argument ofthe directoryto be listed. As anexample, typingls /home willprovide a list ofthe contents of/home, regardless ofyour current directory. The Windows equivalent is dir. • cd—Aninitialismofchange directory, cd allows youto navigate your waythroughthe file system. Typingcd onits own puts youback inyour home directory. Typingthe command alongwiththe name ofthe directoryyouwishto move to, by contrast, switches to that directory. Note that directories canbe absolute or relative:cd boot willmove youto the directory called boot under your current directory, but cd /boot willmove youstraight to the /boot directorywherever youare. • mv—The move command has two purposes inLinux:it allows a file to be moved fromone directoryto another, and it also allows files to be renamed. That latter feature mayseemout ofplace, but inLinuxterms, the file is beingmoved fromone name to another. The command is called as mv oldfile newfile. • rm—Short for remove, rm deletes files. Anyfile—or list offiles—provided after the command name willbe deleted. The Windows equivalent is del, and the two share a commonrequirement that care should be takento ensure the right file is deleted. • rmdir—Byitself, rm cannot usuallyremove directories. As a result, rmdir is provided to delete directories once theyhave beenemptied offiles byrm. • mkdir—The opposite ofrmdir, the mkdir command creates newdirectories. For example, typingmkdir myfolder at the terminalwillcreate a newdirectorycalled myfolder under the current workingdirectory. As withcd, directories provided to the command canbe relative or absolute. Introducing Debian Debianis one ofthe oldest Linuxdistributions around, and a great choice for the RaspberryPithanks to its lightweight nature. This is whythe RaspberryPiFoundationhas chosenit to be the recommended software for newcomers, and the one used for the examples inthis book. To keep the download size to a minimum, the RaspberryPiimage for Debianincludes onlya subset ofthe software you’d find ona regular desktop version. These include tools for browsingthe web, programminginPython, and usingthe Piwitha GUI. Additionalsoftware canbe quicklyinstalled thoughthe use ofthe distribution’s package manager apt. The RaspberryPibuild ofDebianincludes a desktop environment knownas the Lightweight X11 Desktop Environment (LXDE). Designed to offer anattractive user interface usingthe XWindowSystemsoftware, LXDEprovides a familiar point- and-click interface whichwillbe immediatelyaccessible to anyone who has used Windows, OS Xor other GUI-based operating systems inthe past. The GUIdoesn’t loadby default in most Raspberry Pi distributions. To quickly loadit andleave the text-basedconsole behind, log in, type startx andthen press the Enterkey. Ifyou’re usingthe recommended Debiandistribution, you’llfind that youhave plentyofpreinstalled software to get started. While hardlyanexhaustive example ofthe software available for the Pi, whichnumbers inthe thousands ofpackages, it’s a good introductionto preciselywhat the systemcando.
  • 30. The software provided withthe Debiandistributionis split into themed categories. To viewthese categories, youcanleft-click the menuicon, located onthe bottom-left ofthe screeninLXDE(see Figure 2-1). Figure 2-1:The LXDEdesktop, as loaded onthe DebianRaspberryPidistribution The followinglists describe the software packages, grouped bycategory. Accessories • DebianReference—Abuilt-inreference guide, this provides a detailed explanationofthe DebianLinuxdistributionand how programmers cancontribute to its development. • File Manager—The PCManFM file manager provides a graphicalbrowser for files stored onthe Pior anyconnected storage device. • Image Viewer—The GPicViewlets youviewimages, suchas those froma digitalcamera or ona connected storage device. • Leafpad—This is a simple text editor, whichis usefulfor makingquick notes or writingsimple programs. • LXTerminal—This LXDEterminalpackage allows youto use the Linuxcommand line ina windowwithout leavingthe graphicaluser interface. • Root Terminal—Similar to LXTerminal, the Root Terminalautomaticallylogs youinas the root super-user account inorder to carryout systemmaintenance tasks unavailable to a regular user account. • Xarchiver—Ifyouneed to create or extract compressed files, suchas ZIP archives, this is the toolfor the job. Education • Scratch—Agraphicalprogramminglanguage aimed at youngchildren. You’lllearnmore about Scratchand its capabilities inChapter 10, “AnIntroductionto Scratch”. • Squeak—The platformonwhichScratchruns. Youwillrarelyneed to use this menuentry, and should instead use the Scratchentryabove. Internet • Midori—Afast yet lightweight web browser, Midoriis equivalent to Internet Explorer inWindows or to SafarionOS X. • MidoriPrivate Browsing—Clickingonthis menuentryloads the Midoriweb browser inprivate mode, meaningthat sites youvisit aren’t saved into the browser’s history. • NetSurfWeb Browser—Analternative to Midori, NetSurfcanperformbetter oncertaintypes ofweb page. Tryingboth willallowyouto experiment and find the one whichworks best for you. Programming
  • 31. • IDLE—Anintegrated development environment (IDE) writtenspecificallyfor Python. You’lllearnmore about usingIDLE to write your ownPythonprograms inChapter 11, “AnIntroductionto Python”. • IDLE3—Clickingthis entryloads IDLEconfigured to use the newer Python3 programminglanguage, rather thanthe default Python2.7 language. Bothare largelycompatible witheachother, but some programs mayrequire features ofPython 3. • Scratch—This shortcut opens the Scratcheducationallanguage, and is the same as the Scratchentryfound inthe Education category. Either canbe used to start the program. • Squeak—As withScratch, this is a duplicate ofthe shortcut found inthe Educationcategory. Youwillrarelywant to click this directly, and should instead use the Scratchshortcut. Sound & Video • Music Player—LXMusic is a simple and lightweight interface to the XMMS2 music playback software, allowingyouto listento music files while youwork onthe Pi. System Tools • Task Manager—Atoolfor checkingthe amount offree memoryavailable onthe Pi, the current workload ofthe processor, and for closingprograms whichhave crashed or are otherwise unresponsive. Preferences • Customise Look and Feel—Atoolkit for adjustingthe appearance ofthe GUI, includingthe style and colour ofwindows. • Desktop SessionSettings—Atoolfor changinghowthe systemworks whenthe user is logged in, includingwhat programs are automaticallyloaded and whichwindowmanager—the software that draws the borders and title bars ofwindows—is used. • Keyboard and Mouse—Atoolfor adjustinginput devices. Ifyour keyboard is typingthe wrongcharacters for certainkeys, or your mouse is too sensitive, the settings canbe altered here. • Monitor Settings—The resolutionthat the monitor or TVconnected to the Piruns at canbe altered here, althoughadvanced changes require modificationofconfigurationfiles. You’lllearnabout this inChapter 6, “Configuringthe RaspberryPi”. • OpenboxConfigurationManager—The LXDEGUI uses a desktop environment called Openbox, whichcanbe adjusted here. Usingthist tool, youcanapplynewthemes to change the GUI’s appearance, or alter howcertainaspects ofthe interface operate. • Preferred Applications—Atoolfor changingwhichapplications are opened for particular file types. Ifyouchoose to use an alternative web browser, the systemdefault canbe changed here. Finding Help Linuxis designed to beas user-friendly as possibleto new users, even at theterminal command prompt. Although you’ll learn themost common ways to use each command in this chapter, not every option will becovered—to do so would requireamuch larger book. If you find yourself stuck, or if you want to learn moreabout any of thetools that arediscussed in thefollowingpages, there’s acommand you should learn: man. Each Linuxapplication comes with ahelp file, known as aman page—short for “manual page”. It provides background on thesoftwareas well as details on what its options do and how to usethem. To access theman pagefor agiven tool, just typeman followed by thecommand name. To seetheman pagefor ls, atool for listingthecontents of directories, just typeman ls. Using External Storage Devices The Pi’s SDcard, whichstores allthe various Pifiles and directories, isn’t verybig. The largest available SDcard at the time of writingis 64 GB, whichis tinycompared to the 3,000 GB(3 TB) available fromthe largest full-size desktop hard drives. Ifyou’re usingyour Pito playback video files (see Chapter 7, “The Pias a Home Theatre PC”) you’lllikelyneed more storage thanyoucanget fromanSDcard. As youlearned inChapter 1, “Meet the RaspberryPi”, it’s possible to connect USBMass Storage (UMS) devices to the Piinorder to gainaccess to more storage space.
  • 32. Before these externaldevices are accessible, however, the operatingsystemneeds to knowabout them. InLinux, this process is knownas mounting. Ifyou’re runninga versionofLinuxwitha desktop environment loaded—like the recommended Debian distribution’s LXDE, loaded fromthe console withthe startx command—this process is automatic. Simplyconnect the device to a free USBport onthe Pior a USBhub, and the device and its contents willbe immediatelyaccessible (see Figure 2-2). Figure 2-2:LXDEautomaticallymountinga USBmass storage device Fromthe console, things are onlyslightlymore difficult. To make a device accessible to Linuxwhenthe desktop environment isn’t loaded, followthese steps: 1. Connect the USBstorage device to the Pi, either directlyor througha connected USBhub. 2. Type sudo fdisk -l to get a list ofdrives connected to the Pi, and find the USBstorage device bysize. Note the device name:/dev/sdXN, where Xis the drive letter and N is the partitionnumber. Ifit is the onlydevice connected to the Pi, this willbe /dev/sda1. 3. Before the USBstorage device is accessible, Linuxneeds a mount point for it. Create this bytypingsudo mkdir /media/externaldrive. 4. Currently, the device is onlyaccessible to the root user. To make it accessible to allusers, type the followingas a single line: sudo chgrp -R users /media/externaldrive && sudo chmod -R g+w /media/externaldrive 5. Mount the USBstorage device withsudo mount /dev/sdXN /media/externaldrive -o=rw to gainaccess to the device and its contents. Creating a New User Account Unlike Windows and OS X, whichare largelydesigned for use bya single individual, Linuxis at heart a socialoperatingsystem designed to accommodate numerous users. Bydefault, Debianis configured withtwo user accounts:pi, whichis the normaluser account, and root, whichis a superuser account withadditionalpermissions. Don’t be temptedto log in as root all the time. Using a nonprivilegeduseraccount, you’re protectedagainst accidentally wrecking youroperating systemandfromthe ravages of viruses andothermalware downloadedfromthe Internet. While it’s certainlypossible for youto use the piaccount, it’s better ifyoucreate your owndedicated user account. Further accounts canalso be created, for anyfriends or familymembers who might want to use the Pi. Creatinga newaccount onthe Piis straightforward, and the same onalldistributions, except for the username and password
  • 33. used to logonto the Piinitially. Just followthese steps: 1. Loginto the Piusingthe existinguser account (user name pi and password raspberry ifyou’re usingthe recommended Debiandistribution). 2. Type the followingas a single line: sudo useradd -m -G adm,dialout,cdrom,audio,plugdev,users, lpadmin,sambashare,vchiq,powerdev username This creates a new, blank user account. Note that the command should be typed as a single line, withno spaces after the commas. 3. To set a password onthe newaccount, type sudo passwd username followed bythe newpassword whenprompted. To explainwhat just happened:the command sudo tells the operatingsystemthat the command you’re typingshould be runas if youwere logged inas the root account. The useradd command says youwant to create a newuser account. The -m section— knownas a flagor anoption—tells the useradd programto create a home directorywhere the newuser canstore his or her files. The biglist followingthe -G flagis the list ofgroups ofwhichthe user should be a member. Users and Groups In Linux, each user has threemain attributes: their User ID (UID), their Group ID (GID) and alist of supplementary group memberships. A user can bea member of as many groups as heor shepleases, although only oneof thesecan betheuser’s primary group. This is usually aself-named group matchingthe user name. Group membership is important. Whileusers can begranted direct access to files and devices on thesystem, it’s morecommon for auser to receiveaccess to theseviagroup membership. Thegroup audio, for example, grants all members theability to access thePi’s sound playback hardware. Without that membership, theuser won’t belisteningto any music. To seeauser’s group memberships, typegroups usernameat theterminal. If you usethis on thedefault user pi, you’ll seethelist of groups any new member should join to makeuseof thePi. This is wheretheinformation used in step 2 of theprecedingprocedurewas found. File System Layout The content ofthe SDcard is knownas its file system, and is split into multiple sections eachwitha particular purpose. Although it’s not necessaryfor youto understand what eachsectiondoes inorder to use the RaspberryPi, it canbe helpfulbackground knowledge should anythinggo wrong. Logical Layout The wayLinuxdeals withdrives, files, folders and devices is somewhat different to other operatingsystems. Instead ofhaving multiple drives labelled witha letter, everythingappears as a branchbeneathwhat is knownas the root file system. Ifyouloginto the Piand type ls / you’llsee various directories displayed (see Figure 2-3). Some ofthese are areas ofthe SD card for storingfiles, while others are virtualdirectories for accessingdifferent portions ofthe operatingsystemor hardware. Figure 2-3:Adirectorylistingfor the Pi’s root file system
  • 34. The directories visible onthe default Debiandistributionare as follows: • boot—This contains the Linuxkerneland other packages needed to start the Pi. • bin—Operatingsystem-related binaryfiles, like those required to runthe GUI, are stored here. • dev—This is a virtualdirectory, whichdoesn’t actuallyexist onthe SDcard. Allthe devices connected to the system— includingstorage devices, the sound card and the HDMI port—canbe accessed fromhere. • etc—This stores miscellaneous configurationfiles, includingthe list ofusers and their encrypted passwords. • home—Eachuser gets a subdirectorybeneaththis directoryto store alltheir personalfiles. • lib—This is a storage space for libraries, whichare shared bits ofcode required bynumerous different applications. • lost+found—This is a specialdirectorywhere file fragments are stored ifthe systemcrashes. • media—This is a specialdirectoryfor removable storage devices, like USBmemorysticks or externalCDdrives. • mnt—This folder is used to manuallymount storage devices, suchas externalhard drives. • opt—This stores optionalsoftware that is not part ofthe operatingsystemitself. Ifyouinstallnewsoftware to your Pi, it will usuallygo here. • proc—This is another virtualdirectory, containinginformationabout runningprograms whichare knowninLinuxas processes. • selinux—Files related to SecurityEnhanced Linux, a suite ofsecurityutilities originallydeveloped bythe US National SecurityAgency. • sbin—This stores specialbinaryfiles, primarilyused bythe root (superuser) account for systemmaintenance. • sys—This directoryis where specialoperatingsystemfiles are stored. • tmp—Temporaryfiles are stored here automatically. • usr—This directoryprovides storage for user-accessible programs. • var—This is a virtualdirectorythat programs use to store changingvalues or variables. Physical Layout Althoughthe precedinglist is howthe file systemappears to the Linuxoperatingsystem, it’s not howit’s laid out onthe SDcard itself. For the default Debiandistribution, the SDcard is organised into two mainsections, knownas partitions because theysplit the device into different areas inmuchthe same wayas the chapters ofthis book help to organise its contents. The first partitiononthe disk is a small(75 MB) partitionformatted as VFAT, the same partitionformat used byMicrosoft Windows for removable drives. This is mounted, or made accessible, byLinuxinthe /boot directoryand contains allthe files required to configure the RaspberryPiand to load Linuxitself.
  • 35. The second partitionis far larger and formatted as EXT4, a native Linuxfile systemdesigned for high-speed access and data safety. This partitioncontains the mainchunk ofthe distribution. Allthe programs, the desktop, the users’ files and anysoftware that youinstallyourselfare stored here. This takes up the bulk ofthe SDcard. Installing and Uninstalling Software The default software installed withthe Debiandistributionis enoughto get youstarted, but chances are you’re goingto want to customise your Piaccordingto your ownrequirements. Installingnewsoftware onto the Piis simple. The Debiandistributionincludes a toolcalled apt, whichis a powerfulpackage manager. Packages are what Linuxcalls a piece ofsoftware, or a collectionofdifferent pieces ofsoftware designed to work together. Althoughapt is designed to be operated fromthe command line, it’s veryuser-friendlyand easyto learn. There are GUIs for apt, suchas the popular Synaptic Package Manager, but theyoftenstruggle to runonthe Pidue to the lack ofmemory. As a result, we recommend that software be installed at the terminal. Other Distributions Debian, and distributions based on Debian, typically useapt as thepackagemanager. It’s not theonly tool out there, and other distributions makedifferent choices. FedoraRemix, for example, uses thepacman tool. Pacman is no moredifficult to usethan apt, but its syntax(theway it expects you to phraseinstructions to install new softwareor removeexistingsoftware) is different. For instructions on how to usepacman instead of apt, typeman pacman at theFedoraRemixterminal. Other distributions may usetheyum packagemanager. If you’retryingadistribution that uses yum, simply typeman yum at theterminal for instructions. Apackage manager’s job is to keep track ofallthe software installed onthe system. It doesn’t just installnewsoftware—it also keeps tabs onwhat is currentlyinstalled, allows old software to be removed and installs updates as theybecome available. Package management is one ofthe areas where Linuxdiffers greatlyfromoperatingsystems like Windows or OS X. Although it’s possible to manuallydownload newsoftware to install, it’s far more commonto use the built-inpackage management tools instead. Before trying to install newsoftware orupgrade existing software, you needto make sure the apt cache is upto date. To do this, simply type the commandsudo apt-get update. Finding Software The first step to installinga newpiece ofsoftware is to find out what it’s called. The easiest wayto do this is to searchthe cache ofavailable software packages. This cache is a list ofallthe software available to installvia apt, stored onInternet servers knownas repositories. The apt software includes a utilityfor managingthis cache, called apt-cache. Usingthis software, it’s possible to runa search onallthe available software packages for a particular word or phrase. For example, to find a game to play, youcantype the followingcommand: apt-cache search game That tells apt-cache to searchits list ofavailable software for anythingwhichhas the word “game”inits title or description. For commonsearchterms, youcanend up withquite a list (see Figure 2-4), so tryto be as specific as youcan. Figure 2-4:The last fewresults for anapt-cache “game”search
  • 36. If yoursearch termbrings uptoo many different packages to see on a single screen display, you can tell Linux that you want it to pause on each screenfull by piping the output of apt-cache through a tool calledless. Simply change the commandto apt-cache search game | less anduse the cursorkeys to scroll through the list. Press the letterQ on the keyboardto exit. Installing Software Once youknowthe name ofthe package youwant to install, switchto the apt-get command inorder to installit. Installing software is a privilege afforded onlyto the root user, as it affects allusers ofthe Pi. As a result, the commands willneed to be prefaced withsudo to tellthe operatingsystemthat it should be runas the root user. For example, to installthe package thrust (a Linuxversionofa popular Commodore 64 game fromdays gone by), youwould simplyuse the install command withapt-get as follows: sudo apt-get install thrust Some packages relyonother packages inorder to operate. Aprogramminglanguage maydepend ona compiler, a game engine ongraphics files, or anaudio player oncodecs for playingback different formats. These are knowninLinuxterms as dependencies. Dependencies are one ofthe biggest reasons for usinga package manager like apt rather thaninstallingsoftware manually. Ifa package depends onother packages, apt willautomaticallyfind them(see Figure 2-5) and prepare themfor installation. Ifthis happens, you’llbe showna prompt askingwhether youwant to continue. Ifyoudo, type the letter Yand press the Enter key. Figure 2-5:Apt listingthe dependencies for the OpenOffice.orgpackage
  • 37. Uninstalling Software Ifyoudecide youno longer want a piece ofsoftware, apt-get also includes a remove command that cleanlyuninstalls the package alongwithanydependencies whichare no longer required. Whenyou’re usinga smaller SDcard withthe Pi, the ability to tryout software and quicklyremove it is extremelyuseful. To remove thrust, simplyopenthe terminaland type the followingcommand: sudo apt-get remove thrust The remove command has a more powerfulbrother inthe formofthe purge command. Like remove, the purge command gets rid ofsoftware youno longer require. Where remove leaves the software’s configurationfiles intact, however, purge removes everything. Ifyou’ve got yourselfinto a mess customisinga particular package and it no longer works, purge is the command to use. For example, to purge thrust, youwould just type this: sudo apt-get purge thrust Upgrading Software Inadditionto installingand uninstallingpackages, apt canbe used to keep themup to date. Upgradinga package throughapt ensures that you’ve received the latest updates, bugfixes and securitypatches. Before tryingto upgrade a package, make sure the apt cache is as freshas possible byrunninganupdate: sudo apt-get update Whenupgradingsoftware, youhave two choices:youcanupgrade everythingonthe systemat once or upgrade individual programs. Ifyoujust want to keep your distributionupdated, the former is achieved bytypingthe following: sudo apt-get upgrade To upgrade anindividualpackage, simplytellapt to installit again. For example, to installa thrust upgrade, youwould type this: sudo apt-get install thrust Ifthe package is alreadyinstalled, apt willtreat it as anin-place upgrade. Ifyou’re alreadyrunningthe latest versionavailable, apt willsimplytellyouit cannot upgrade the software and exit. Formore information on package management with apt—in particular, howcertain packages can be “kept back” andexcludedfromupgrades—type
  • 38. man apt at the terminal.
  • 39. Chapter 3: Troubleshooting Sometimes, things don’t go entirelysmoothly. The more complexthe device, the more complexthe problems that canoccur— and the Piis anextremelycomplexdevice indeed. Thankfully, manyofthe most commonproblems are straightforward to diagnose and fix. Inthis chapter, we’lllook at some of the most commonreasons for the Pito misbehave and howto fixthem. Keyboard and Mouse Diagnostics Perhaps the most commonproblemthat users experience withthe RaspberryPiis whenthe keyboard repeats certaincharacters. For example, ifthe command startx appears onscreenas sttttttttttartxxxxxxxxxxxx, it will, understandably, failto work whenthe Enter keyis pressed. There are typicallytwo reasons whya USBkeyboard fails to operate correctlywhenconnected to the RaspberryPi:it’s drawingtoo muchpower, or its internalchipset is conflictingwiththe USBcircuitryonthe Pi. Check the documentationfor your keyboard, or the labelonits underside, to see ifit has a power ratinggiveninmilliamps (mA). This is howmuchpower the keyboard attempts to drawfromthe USBport whenit’s inuse. The Pi’s USBports have a component called a polyfuse connected to them, whichprotects the Piinthe event that a device attempts to drawtoo muchpower. Whenthis polyfuse is tripped, it causes the USBport to shut off, at around 150 mA. Ifyour keyboard draws anywhere around that muchpower, it mayoperate strangely—or not at all. This canbe a problemfor keyboards that have built-inLEDlighting, whichrequire far more power to operate thana standard keyboard. Ifyoufind that your USBkeyboard maybe drawingtoo muchpower, tryconnectingit to a powered USBhub instead of directlyto the Pi. This willallowthe keyboard to drawits power fromthe hub’s power supplyunit, instead offromthe Piitself. Alternatively, swap the keyboard out for a modelwithlower power demands. The repeating-letter problemmayalso be traced to aninadequate power supplyfor the Piitself, whichis addressed inthe next section, “Power Diagnostics”. The issue ofcompatibility, sadly, is harder to diagnose. While the overwhelmingmajorityofkeyboards work just fine withthe Pi, a smallnumber exhibit strange symptoms. These range fromintermittent response, the repeating-letter syndrome or evencrashes that prevent the Pifromoperating. Sometimes, these issues don’t appear untilother USBdevices are connected to the Pi. Ifyour keyboard was workingfine untilanother USBdevice, inparticular a USBwireless adapter, was connected, youmayhave an issue ofincompatibility. Ifpossible, tryswappingthe keyboard out for another model. Ifthe newkeyboard works, your old one maybe incompatible withthe Pi. For a list ofknown-incompatible keyboards, visit the eLinuxwiki: http://elinux.org/RPi_VerifiedPeripherals#Problem_USB_Keyboards The same advice oncheckingcompatibilityinadvance applies to problems withthe mouse:the majorityofUSBmice and trackballs work fine, but some exhibit incompatibilitywiththe Pi’s ownUSBcircuitry. This usuallyresults insymptoms like a jerkyor unresponsive mouse pointer, but it cansometimes lead to the Pifailingto load or crashingat randomintervals. Ifyou’re lookingto buya newmouse, anup-to-date list ofmodels knownto work withthe Piis available at the eLinuxwikisite: http://elinux.org/RPi_VerifiedPeripherals#Working_USB_Mouse_Devices Power Diagnostics Manyproblems withthe RaspberryPicanbe traced to aninadequate power supply. The ModelArequires a 5 Vsupply capable ofprovidinga 500 mAcurrent, while the ModelB’s extra components bump up the current requirement to 700 mA. Not allUSBpower adapters are designed to offer this muchpower, eveniftheir labellingclaims otherwise. The formal USBstandardstates that devices shoulddrawno more than 500 mA, with even that level of poweronly available to the device following a process callednegotiation. Because the Pi doesn’t negotiate forpower, it’s unlikely that it will work if you connect it to the USBports on a desktop orlaptopcomputer. Ifyou’re havingintermittent problems withyour Pi—particularlyifit works untilyouconnect somethingto a USBport or start a processor-intensive operationlike playingvideo—the chances are that the power supplyinuse is inadequate. The Piprovides a
  • 40. relativelyeasywayto check ifthis is the case inthe formoftwo voltage test points. To use the voltage test points, you’llneed a voltmeter or multimeter withdirect current (DC) voltage measuringcapabilities. If your meter has multiple inputs for different voltages, use anappropriate setting. Avoidtouching the test probes to anything not labelledas a test point. It’s possible to bridge the 5 Vsupply that comes in to the Pi to the internal 3.3 Vsupply, creating a short circuit which can damage the device. Be especially careful aroundexposedheaderpins. The two test points are small, copper-clad holes knownas vias, whichare connected to the Pi’s 5 Vand ground circuits. Put the positive (red) meter probe onTP1, located to the left ofthe board just above a smallblack component called a regulator labelled RG2. Connect the black (negative) meter probe to TP2, located betweenthe copper GPIO pins and the yellow-and-silver RCA phono connector at the top-left ofthe board (see Figure 3-1). Figure 3-1:The two voltage test points, labelled TP1 and TP2 The readingonthe voltmeter should be somewhere between4.8 Vand 5 V. Ifit’s lower than4.8 V, this indicates that the Piis not beingprovided withenoughpower. Tryswappingthe USBadapter for a different model, and check that the labelsays it can supply700 mAor more. Amodelrated at 1Ais recommended, but beware ofcheap models—theysometimes have inaccurate labelling, and failto supplythe promised current. Genuine branded mobile phone chargers rarelyhave this problem, but cheap unbranded devices—oftensold as compatible adapters—should be avoided Ifyour voltmeter reads a negative number, don’t worry:this just means you’ve got the positive and negative probes inthe wrong place. Either swap themaround or just ignore the negative signwhennotingyour reading. Display Diagnostics Althoughthe Piis designed to work withalmost anyHDMI, DVI or composite video displaydevice, it simplymaynot work as expected whenyouplugit in. For example, youmayfind that your picture is shifted to the side or not fullydisplayed, or is only visible as a postage-stamp-sized cut-out inthe middle ofthe screenor inblack-and-white—or evenmissingentirely. First, check the type ofdevice to whichthe Piis connected. This is especiallyimportant whenyou’re usingthe composite RCA connectionto plugthe Piinto a TV. Different countries use different standards for TVvideo, meaningthat a Piconfigured for one countrymaynot work inanother. This is the usualexplanationfor a Pishowingblack-and-white video. You’lllearnhowto
  • 41. adjust this settinginChapter 6, “Configuringthe RaspberryPi”. Whenyouuse the HDMI output, the displaytype is usuallyautomaticallydetected. Ifyou’re usinganHDMI to DVI adapter to plugthe Piinto a computer monitor, however, this occasionallygoes awry. Commonsymptoms include snow-like static, missing picture portions or no displayat all. To fixthis, note the resolutionand refreshrate ofyour connected display, and thenjump to Chapter 6 to find out howto set these manually. Another issue is a too-large or too-smallimage, either missingportions at the edge ofthe screenor sittinginthe middle ofa large black border. This is caused bya settingknownas overscan, whichis used whenthe Piis connected to TVs to avoid printingto portions ofthe displaywhichmaybe hiddenunder a bezel. As withother display-related settings, youwilllearnhowto adjust— or evencompletelydisable—overscaninChapter 6. Boot Diagnostics The most commoncause for a Pito failto boot is a problemwiththe SDcard. Unlike a desktop or laptop computer, the Pi relies onfiles stored onthe SDcard for everything. IfPican’t talk to the card, it won’t displayanythingonthe screenor show anysigns oflife at all. Ifyour Pi’s power light glows whenyouconnect the micro-USBpower supply, but nothingelse happens and the OK light remains dark, youhave anSDcard problem. First, ensure that the card works whenyouconnect it to a PC, and that it shows the partitions and files expected ofa well-flashed card. (For more details, see Chapter 2, “LinuxSystemAdministration”, particularlythe sectiontitled “File SystemLayout”inthat chapter.) Ifthe card works ona PC but not inthe Pi, it maybe a compatibilityproblem. Some SDcards—especiallyhigh-speed cards marked as Class 10 ontheir labelling—don’t operate correctlywhenconnected to the Pi’s onboard SDcard reader. Alist of cards knownto cause compatibilityproblems withthe Picanbe found onthe eLinuxwiki: http://elinux.org/RPi_VerifiedPeripherals#Problem_SD_Cards Sadly, ifyouhave one ofthe cards onthe list, youmayneed to replace it witha different card inorder for the Pito work. As the Pi’s software base is developed, however, work is beingcarried out to ensure that a wider range ofcards operate correctlywith the Pi. Before givingup ona high-speed card completely, check to see ifanupdated versionofyour chosenLinuxdistributionis available. (See Chapter 1, “Meet the RaspberryPi”, for more informationabout distributions.) Network Diagnostics The most usefultoolfor diagnosingnetwork problems is ifconfig. Ifyou’re usinga wireless network connection, jump to Chapter 4, “Network Configuration”, for informationona similar toolfor those devices. Otherwise, read on. Designed to provide informationonconnected network ports, ifconfig is a powerfultoolfor controllingand configuringthe Pi’s network ports. For its most basic usage, simplytype the tool’s name inthe terminal: ifconfig Called inthis manner, ifconfig provides informationonallthe network ports it canfind (see Figure 3-2). For the standard RaspberryPiModelB, there are two ports:the physicalEthernet port onthe right side ofthe board, and a virtualloopback interface that allows programs onthe Pito talk to eachother. Figure 3-2:The output ofifconfig ona RaspberryPiModelB
  • 42. The output ofifconfig is split into the followingsections: • Link encap—The type ofencapsulationused bythe network, whichonthe ModelBwilleither read Ethernet for the physicalnetwork port or Local Loopback for the virtualloopback adaptor. • Hwaddr—The Media Access Control(MAC) address ofthe network interface, writteninhexadecimal. This is unique for everydevice onthe network, and eachPihas its ownMAC address, whichis set at the factory. • inet addr—The internet protocol(IP) address ofthe network interface. This is howyoufind the Pionthe network ifyou’re usingit to runa network-accessible service, suchas a web server or file server. • Bcast—The broadcast address for the network to whichthe Piis connected. Anytraffic sent to this address willbe received byeverydevice onthe network. • Mask—The network mask, whichcontrols the maximumsize ofthe network to whichthe Piis connected. For most home users, this willread 255.255.255.0. • MTU—The maximumtransmissionunit size, whichis howbiga single packet ofdata canbe before the systemneeds to split it into multiple packets. • RX—This sectionprovides feedback onthe received network traffic, includingthe number oferrors and dropped packets recorded. Ifyoustart to see errors appearinginthis section, there’s somethingwrongwiththe network. • TX—This provides the same informationas the RXsection, but for transmitted packets. Again, anyerrors recorded here indicate a problemwiththe network. • collisions—Iftwo systems onthe network tryto talk at the same time, youget a collisionwhichrequires themto retransmit their packets. Smallnumbers ofcollisions aren’t a problem, but a large number here indicates a network issue. • txqueuelen—The lengthofthe transmissionqueue, whichwillusuallybe set to 1000 and rarelyneeds changing. • RXbytes, TXbytes—Asummaryofthe amount oftraffic the network interface has passed. Ifyou’re havingproblems withthe network onthe Pi, youshould first tryto disable and thenre-enable the network interface. The easiest wayto do this is withtwo tools called ifup and ifdown. Ifthe network is up, but not workingcorrectly—for example, ififconfig doesn’t list anythinginthe inet addr section—start bydisablingthe network port. Fromthe terminal, type the followingcommand: sudo ifdown eth0 Once the network is disabled, make sure that the cable is inserted tightlyat bothends, and that whatever network device the Pi is connected to (hub, switchor router) is powered onand working. Thenbringthe interface back up againwiththe following command: sudo ifup eth0