Raspberry Pi
®
01_9781118554210-ffirs.indd i
by Sean McManus and Mike Cook
Raspberry Pi
®
01_9781118554210-ffirs.indd iii
Published by
John Wiley & Sons, Inc.
111 River Street Hoboken, NJ 07030-5774 www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Hoboken, New Jersey Published by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada
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, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!,
The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier,and
related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
Raspberry Pi and the Raspberry Pi logo are registered trademarks of the Raspberry Pi Foundation in the United Kingdom and other countries. Raspberry Pi For Dummies is not endorsed by the Raspberry Pi Foundation.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
ISBN 978-1-118-55421-0 (pbk); ISBN 978-1-118-55422-7 (ebk); ISBN 978-1-118-55423-4 (ebk); ISBN 978-1-118-55424-1 (ebk)
Manufactured in the United States of America at Bind-Rite 10 9 8 7 6 5 4 3 2 1
01_9781118554210-ffirs.indd iv
About the Authors
Sean McManus is an expert technology and business author. His other books
include Microsoft Offi ce for the Older and Wiser,Social Networking for the
Older and Wiser,Web Design in Easy Steps, andiPad for the Older and Wiser.
His tutorials and articles have appeared in magazines including Internet
Magazine, Internet Works, Business 2.0, Making Music
,
andPersonal ComputerWorld.His personal website is atwww.sean.co.uk.
Mike Cook has been making electronic things since he was at school. Former
Lecturer in Physics at Manchester Metropolitan University, he wrote more than three hundred computing and electronics articles in the pages of com-puter magazines for 20 years starting in the 1980s. Leaving the University after 21 years when the Physics department closed down, he got a series of proper jobs where he designed digital TV set top boxes and access control systems. Now retired and freelancing, he spends his days surrounded by wires, patrolling the forums as Grumpy Mike.
01_9781118554210-ffirs.indd v
Dedication
Thank you to my wife, Karen, for all her support throughout this project. —Sean
To my wife, Wendy, who always acts delighted whenever I show her yet another blinking LED. And also to the late Leicester Taylor, World War II radar researcher and inspirational supervisor of my post-graduate research at the University of Salford. —Mike
Authors’ Acknowledgments
Thank you to my co-author, Mike, for bringing his electronics expertise and fantastic project ideas. Thank you to Craig Smith for commissioning us to write this book, to Linda Morris for her editing support, and to Paul Hallett, our technical editor. Thanks also to Lorna Mein and Natasha Lee in market-ing, and to the . . . For Dummies team for making it all happen.
Many people helped with research or permissions requests, including Karen McManus, Leo McHugh, Mark Turner, Peter Sayer, Bill Kendrick, Simon Cox, Jon Williamson, Paul Beech, Peter de Rivaz, Michał Męciński, Ruairi Glynn, Stephen Revill, and Lawrence James.
We wouldn’t have a book to write if it weren’t for the wonderful work of the Raspberry Pi Foundation, the manufacturers who took a gamble on it, and the many thousands of people who have contributed to the Raspberry Pi’s soft-ware. —Sean
I would like to thank Sean McManus for inviting me to contribute to this book and the staff at Wiley for making the process of producing this book as pain-less as possible. —Mike
01_9781118554210-ffirs.indd vii
We’re proud of this book; please send us your comments at http://dummies.custhelp.com. For other comments, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
Some of the people who helped bring this book to market include the following:
Acquisitions and Editorial
Project Editor: Linda Morris Acquisitions Editor: Craig Smith Copy Editor: Linda Morris Technical Editor: Paul Hallett Editorial Manager: Jodi Jensen Editorial Assistant: Anne Sullivan Sr. Editorial Assistant: Cherie Case Cover Photo: © Dr. Andrew Robinson
Composition Services
Sr. Project Coordinator: Kristie Rees Layout and Graphics: Carrie A. Cesavice,
Jennifer Creasey, Joyce Haughey
Proofreader: Linda Seifert Indexer: Potomac Indexing, LLC
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Kathleen Nebenhaus, Vice President and Executive Publisher Composition Services
Debbie Stailey, Director of Composition Services
01_9781118554210-ffirs.indd viii
Contents at a Glance
Introduction ... 1
Part I: Getting Started with Raspberry Pi ... 7
Chapter 1: Introducing the Raspberry Pi ... 9
Chapter 2: Downloading the Operating System ... 19
Chapter 3: Connecting Your Raspberry Pi ... 31
Part II: Getting Started with Linux ... 43
Chapter 4: Using the Desktop Environment ... 45
Chapter 5: Using the Linux Shell ... 71
Part III: Using the Raspberry Pi
for Both Work and Play ... 107
Chapter 6: Being Productive with the Raspberry Pi... 109
Chapter 7: Editing Photos on the Raspberry Pi with GIMP ... 121
Chapter 8: Building Your First Website with the Raspberry Pi ... 131
Chapter 9: Playing Audio and Video on the Raspberry Pi ... 159
Part IV: Programming the Raspberry Pi ... 171
Chapter 10: Introducing Programming with Scratch ... 173
Chapter 11: Programming an Arcade Game Using Scratch ... 189
Chapter 12: Writing Programs in Python ... 211
Chapter 13: Creating a Game with Python and Pygame ... 241
Part V: Exploring Electronics with the Raspberry Pi .... 259
Chapter 14: Understanding Circuits and Soldering ... 261
Chapter 15: Making Your First Project with the Raspberry Pi ... 281
Chapter 16: Putting the Raspberry Pi in Control ... 313
Chapter 17: The Raspberry Pi in an Analog World ... 337
Part VI: The Part of Tens ... 359
Chapter 18: Ten Great Software Packages for the Raspberry Pi ... 361
Chapter 19: Ten Inspiring Projects for the Raspberry Pi ... 371
02_9781118554210-ftoc.indd ix
Appendix A: Troubleshooting and Configuring the
Raspberry Pi ... 377
Appendix B: The GPIO on the Raspberry Pi ... 391
Index ... 393
02_9781118554210-ftoc.indd x
Table of Contents
Introduction ... 1
About Raspberry Pi For Dummies ... 1
Why You Need This Book ... 2
Foolish Assumptions ... 2
How This Book Is Organized ... 3
Icons Used in This Book ... 5
Visit the Book’s Website ... 5
Part I: Getting Started with Raspberry Pi ... 7
Chapter 1: Introducing the Raspberry Pi . . . .9
Getting Familiar with the Raspberry Pi ... 11
Figuring Out What You Can Do with a Raspberry Pi ... 12
Determining Its Limitations ... 13
Getting Your Hands on a Raspberry Pi ... 13
Deciding What Else You Need ... 14
Chapter 2: Downloading the Operating System . . . .19
Introducing Linux ... 19
Determining Which Distribution to Use ... 20
Using RISC OS on the Raspberry Pi ... 21
Downloading a Linux Distribution ... 21
Unzipping Your Linux Distribution ... 22
Flashing Your SD Card ... 22
Flashing an SD card in Windows ... 23
Flashing an SD card on a Mac ... 24
Flashing an SD card using Linux ... 27
Chapter 3: Connecting Your Raspberry Pi . . . .31
Inserting the SD Card ... 32
Connecting a Monitor or TV ... 33
Connecting an HDMI or DVI display ... 33
Connecting a television using composite video ... 34
Connecting a USB Hub ... 34
Connecting a Keyboard and Mouse ... 35
Connecting Audio ... 35
Connecting to Your Router ... 36
02_9781118554210-ftoc.indd xi
Raspberry Pi For Dummies
xii
Connecting the Power and Turning on the Raspberry Pi ... 37
Using Raspi-confi g to Set Up Your Raspberry Pi ... 37
Logging In ... 41
Creating a Protective Case for Your Raspberry Pi ... 41
Part II: Getting Started with Linux ... 43
Chapter 4: Using the Desktop Environment . . . .45
Starting the Desktop Environment ... 45
Navigating the Desktop Environment ... 46
Using the icons on the desktop ... 46
Using the Programs menu... 47
Using multiple desktops... 48
Resizing and closing your program windows ... 49
Using the Task Manager ... 50
Using External Storage Devices in the Desktop Environment ... 51
Using the File Manager ... 51
Navigating the fi le manager ... 52
Copying and moving fi les and folders ... 55
Selecting multiple fi les and folders ... 55
Creating new folders and blank fi les ... 56
Changing how fi les are displayed ... 57
Opening a folder as root or in the terminal ... 58
Browsing the Web ... 59
Using Midori to browse the web ... 59
Searching for and within web pages... 61
Using tabbed browsing ... 61
Adding and using bookmarks ... 62
Zooming the page and opening it full screen ... 63
Protecting your privacy ... 63
Using the Image Viewer ... 64
Using the Leafpad Text Editor ... 66
Customizing Your Desktop ... 67
Logging Out from LXDE ... 69
Chapter 5: Using the Linux Shell . . . .71
Understanding the Prompt ... 72
Exploring Your Linux System ... 72
Listing fi les and directories ... 72
Changing directories ... 73
Checking fi le types ... 73
Changing to the parent directory ... 74
Understanding the directory tree ... 75
Using relative and absolute paths ... 78
Investigating more advanced listing options ... 80
02_9781118554210-ftoc.indd xii
xiii
Table of Contents
Understanding the Long Listing Format and Permissions ... 83
Slowing Down the Listing and Reading Files with the Less Command ... 85
Speeding Up Entering Commands ... 86
Using Redirection to Create Files in Linux ... 87
Top Tips for Naming Your Files in Linux ... 88
Creating Directories ... 89
Deleting Files in Linux ... 90
Using Wildcards to Select Multiple Files in Linux ... 91
Removing Directories ... 93
Copying and Renaming Files ... 94
Installing and Managing Software on Your Raspberry Pi ... 96
Updating the cache ... 96
Finding the package name ... 97
Installing software... 97
Running software ... 98
Upgrading the software on your Raspberry Pi ... 98
Removing software and freeing up space ... 99
Finding out what’s installed on your Raspberry Pi ... 100
Managing User Accounts on Your Raspberry Pi ... 100
Learning More About Linux Commands ... 102
Customizing Your Shell with Your Own Linux Commands ... 104
Part III: Using the Raspberry Pi
for Both Work and Play ... 107
Chapter 6: Being Productive with the Raspberry Pi . . . .109
Installing LibreOffi ce on Your Raspberry Pi ... 110
Starting LibreOffi ce on the Raspberry Pi ... 110
Saving Your Work ... 111
Writing Letters in LibreOffi ce Writer ... 111
Managing Your Budget in LibreOffi ce Calc ... 113
Creating Presentations in LibreOffi ce Impress ... 116
Creating a Party Invitation with LibreOffi ce Draw ... 118
Chapter 7: Editing Photos on the Raspberry Pi with GIMP. . . .121
Installing and Starting GIMP ... 122
Understanding the GIMP Screen Layout ... 122
Resizing an Image in GIMP ... 124
Cropping Your Photo ... 125
Rotating and Flipping Your Photo ... 126
Adjusting the Colors ... 127
Fixing Imperfections ... 127
Converting Images Between Different Formats ... 128
Finding Out More about GIMP ... 129
02_9781118554210-ftoc.indd xiii
Raspberry Pi For Dummies
xiv
Chapter 8: Building Your First Website with the Raspberry Pi . . . . .131
Understanding What a Website Is ... 132
Discovering How to Write a Web Page ... 132
Organizing Your Files ... 133
Creating Your First Web Page ... 133
Your fi rst HTML code snippet ... 134
Structuring an HTML document ... 136
Formatting Your HTML Content ... 138
Adding additional headings ... 139
Adding images to your web page ... 139
Adding links in your web content ... 141
Formatting lists ... 142
Additional formatting tags you can use ... 144
Validating Your HTML ... 145
Using CSS to Change Your Page’s Appearance ... 145
Adding a style sheet to your web page ... 145
Adding a touch of color... 147
Formatting your text... 149
Styling lists ... 150
Adding borders to your content ... 151
Adding spacing around and between page elements ... 152
Applying Styles to More Specifi c Parts of the Page ... 152
Creating a Navigation Bar from a List ... 155
Adding the Finishing Touches ... 156
Publishing Your Web Page on the Internet ... 157
Taking It Further ... 158
Chapter 9: Playing Audio and Video on the Raspberry Pi. . . .159
Setting Up Raspbmc ... 160
Navigating Raspbmc ... 161
Adding Media ... 163
Adding a USB device ... 163
Adding networked media ... 164
Using streaming media ... 164
Playing Music ... 165
Playing Videos ... 166
Viewing Photos ... 167
Changing the Settings in Raspbmc ... 167
Using a Remote Control ... 168
Playing Music in the Desktop Environment ... 169
02_9781118554210-ftoc.indd xiv
xv
Table of Contents
Part IV: Programming the Raspberry Pi ... 171
Chapter 10: Introducing Programming with Scratch . . . .173
Understanding What Programming Is ... 174
Starting Scratch ... 174
Understanding the Scratch Screen Layout ... 174
Positioning and Resizing Your Sprite ... 176
Making Your Sprite Move ... 176
Using directions to move your sprite... 177
Using grid coordinates to move and position your sprite ... 178
Showing sprite information on the Stage ... 180
Changing Your Sprite’s Appearance ... 181
Using costumes ... 181
Using speech and thought bubbles ... 182
Using graphic effects ... 183
Resizing your sprite ... 184
Changing your sprite’s visibility ... 184
Adding Sounds and Music ... 185
Creating Scripts ... 186
Using the Wait Block to Slow Down Your Sprite ... 187
Saving Your Work ... 188
Chapter 11: Programming an Arcade Game Using Scratch . . . .189
Starting a New Scratch Project and Deleting Sprites ... 190
Changing the Background ... 191
Adding Sprites to Your Game ... 191
Drawing Sprites in Scratch ... 192
Naming Your Sprites ... 195
Controlling When Scripts Run ... 195
Using the green fl ag to start scripts ... 195
Using the Forever Control block ... 196
Enabling keyboard control of a sprite ... 197
Enabling a sprite to control another sprite ... 198
Using Random Numbers ... 201
Detecting When a Sprite Hits Another Sprite ... 201
Introducing Variables ... 203
Making Sprites Move Automatically ... 204
Fixing the Final Bug ... 205
Adding Scripts to the Stage ... 208
Duplicating Sprites ... 208
Playing Your Game ... 208
Adapting the Game’s Speed ... 209
Taking It Further with Scratch ... 209
02_9781118554210-ftoc.indd xv
Raspberry Pi For Dummies
xvi
Chapter 12: Writing Programs in Python . . . .211
Starting Python ... 212
Entering Your First Python Commands ... 212
Using the Shell to Calculate Sums ... 214
Creating the Times Tables Program ... 215
Creating and running your fi rst Python program ... 216
Using variables ... 218
Accepting user input ... 219
Printing words, variables, and numbers together ... 219
Using for loops to repeat ... 221
Creating the Chatbot Program ... 223
Introducing lists ... 224
Using lists to make a random chat program ... 227
Adding a while loop ... 229
Using a loop to force a reply from the player ... 230
Using dictionaries ... 231
Creating your own functions ... 233
Creating the dictionary look-up function ... 235
Creating the main conversation loop ... 237
Final thoughts on Chatbot ... 238
The fi nal Chatbot program ... 239
Chapter 13: Creating a Game with Python and Pygame . . . .241
Installing and Updating Pygame ... 242
Importing Pygame ... 242
Setting Up the Game Window ... 243
Using Colors in Pygame ... 243
Drawing with Pygame ... 244
Creating the Game Map ... 245
Drawing the Bricks ... 247
Positioning the Bat ... 248
Positioning the Ball ... 250
Displaying the End Game Messages ... 251
Checking for a Win ... 252
Setting Up the Timings ... 252
Making the Bat Move ... 253
Making the Ball Move ... 254
Adapting the Game ... 257
02_9781118554210-ftoc.indd xvi
xvii
Table of Contents
Part V: Exploring Electronics with the Raspberry Pi ... 259
Chapter 14: Understanding Circuits and Soldering . . . .261
Discovering What a Circuit Is ... 262
Understanding the nature of electricity ... 262
Determining how a component needs to be treated ... 269
Testing circuits with simulators ... 269
Getting Familiar with the GPIO ... 270
Putting the general purpose in GPIO ... 271
Understanding what GPIOs do ... 271
Putting an output pin to practical use ... 272
Using GPIOs as inputs ... 274
Learning which end is hot: Getting to grips with a soldering iron ... 276
Making a soldered joint ... 277
Looking at Ready-Made Add-On Boards ... 278
The Gert board ... 278
Pi Face ... 279
Other boards ... 280
Chapter 15: Making Your First Project with the Raspberry Pi . . . .281
Getting Started with the Blastoff Project ... 281
Getting at the GPIO Pins ... 283
Being aware of Raspberry Pi board revisions ... 283
Making the connection ... 285
Making a Breakout Board ... 286
Creating the cable ... 287
Wiring the cable ... 289
Testing the breakout board ... 293
Controlling the GPIO pins ... 294
Floating GPIO pins ... 296
Getting a better display ... 297
Creating the Blastoff Game ... 298
Making the box ... 298
Making the ball traps ... 300
Wiring up the Blastoff game ... 301
Testing the hardware ... 306
Writing the software ... 307
The game logic ... 310
Creating the sounds... 310
Customizing the Blastoff game ... 311
02_9781118554210-ftoc.indd xvii
Raspberry Pi For Dummies
xviii
Chapter 16: Putting the Raspberry Pi in Control . . . .313
Using GPIO Pins as Outputs ... 313
Preparing to Build the Copycat Game ... 315
Choosing an LED ... 316
Creating the Copycat Game ... 318
Customizing the Game ... 326
Making a Better Game ... 327
Putting It All Together ... 332
Chapter 17: The Raspberry Pi in an Analog World. . . .337
Exploring the Difference: Analog versus Digital ... 338
Taking small steps ... 338
Reading small steps ... 340
Investigating Converter Chips ... 341
Building the Raspberry Ripple ... 342
The chip at the heart of the Ripple... 343
Putting the chip into a circuit ... 343
Wiring it up ... 345
Installing the drivers ... 346
Using the Raspberry Ripple ... 347
Testing the analog inputs ... 348
Testing the analog output ... 350
Making a Curve Tracer ... 351
Making a Pot-a-Sketch ... 354
Making Real Meters ... 356
Making a Steve Reich Machine ... 356
Taking the Temperature ... 357
Part VI: The Part of Tens ... 359
Chapter 18: Ten Great Software Packages for the Raspberry Pi . . .361
Penguins Puzzle ... 361 FocusWriter ... 362 Chromium ... 363 XInvaders 3D ... 364 Fraqtive ... 364 Evolution ... 365 Tux Paint ... 366 Grisbi ... 367
Beneath a Steel Sky ... 367
LXMusic ... 368
02_9781118554210-ftoc.indd xviii
xix
Table of Contents
Chapter 19: Ten Inspiring Projects for the Raspberry Pi. . . .371
One-Button Audiobook Player ... 371
Raspberry Pi Synthesizer ... 372
Bird Feeder Webcam ... 372
Scratch Games ... 373 Weather Station ... 373 Jukebox ... 373 Baby Monitor ... 374 Remote-Controlled Cars ... 374 A Talking Boat ... 375 Home Automation ... 376
Appendix A: Troubleshooting and Configuring
the Raspberry Pi ... 377
Troubleshooting the Raspberry Pi ... 377
Making More Space on the SD Card ... 380
Adjusting the Settings on Your Raspberry Pi ... 380
Using Nano to edit confi g.txt ... 381
Troubleshooting screen display issues ... 383
Adjusting the screen display ... 386
Exploring more advanced settings ... 386
Mounting External Storage Devices ... 386
Fixing Software Installation Issues ... 388
Troubleshooting Your Network Connection ... 388
Appendix B: The GPIO on the Raspberry Pi ... 391
Index ... 393
02_9781118554210-ftoc.indd xix
Raspberry Pi For Dummies
xx
02_9781118554210-ftoc.indd xx
Introduction
I
n recent years, computer education has focused largely on office skills, and not on understanding how computers work, or how you can use them to create new programs and inventions. The Raspberry Pi redresses the bal-ance. It can be used for games, music, photo editing, and word processing, like any computer. But it can do so much more, providing a gateway into programming, electronics, and the mysterious world of Linux, the technically powerful (and free) rival to Windows and Mac OS.Although the Raspberry Pi presents new opportunities to everyone, it can also be a daunting prospect. It comes as a bare circuit board, so to do anything with it, you’ll need to add an operating system on an SD card and connect it up to a screen, mouse, and keyboard. To get started, you need to learn a few basics of Linux, or at least get acquainted with LXDE, the graphical desktop. You might be a geek who relishes learning new technologies, or you might be someone who wants a new family computer to use with the children. In either case, Raspberry Pi For Dummies helps you to get started with your Raspberry Pi and teaches you about some of the many fun and inspiring things you can do with it.
About Raspberry Pi For Dummies
Raspberry Pi For Dummies provides a concise and clear introduction to the
terminology, technology, and techniques that you need to get the most from your Pi. With the book as your guide, you’ll learn how to
✓ Connect up your Raspberry Pi.
✓ Change its settings so it works optimally for you.
✓ Discover and install great free software you can use on your Raspberry Pi.
✓ Use the desktop environment to run programs, manage your files, surf
the web, and view your photos.
✓ Use the Linux command line to manage your Raspberry Pi and its files.
✓ Use the Raspberry Pi as a productivity tool.
✓ Edit photos.
03_9781118554210-intro.indd 1
2
Raspberry Pi For Dummies
✓ Play music and video.
✓ Build and publish your first website using the tools on the Raspberry Pi and free tools you can download.
✓ Create animations and arcade games with the child-friendly Scratch
programming language.
✓ Write your own games and other programs using the Python programming
language.
✓ Get started with electronics, from an introduction to soldering, to the design and creation of sophisticated electronic games, controlled by the Raspberry Pi.
Why You Need This Book
After you shake the Raspberry Pi out of the little electrostatic bag it comes in, what next?
This book answers that question. It enables you to get your Raspberry Pi up and running and also introduces you to some of the great things you can do with it, through satisfying practical projects. With this book as your compan-ion, you can build websites, write games, and create your own electronic gadgets, all without any prior knowledge.
The Raspberry Pi is most likely a bit different compared to other computers you’ve used, so this book also helps you to do some of the things on your Pi that you expect of every computer, such as playing music and editing documents.
You can learn a lot of this through trial and error, of course, but that can be a frustrating way to spend your time. Using this book as a reference, you can more quickly start using your Raspberry Pi, whatever you plan to do with it.
Foolish Assumptions
Raspberry Pi For Dummies is written for beginners, by which we mean people
who have never used a similar computer before. However, we do have to make a few assumptions in writing this book because we wouldn’t have enough space for all the cool projects if we had to start by explaining what a mouse is! Here are our assumptions:
03_9781118554210-intro.indd 2
3
Introduction
✓ You are familiar with other computers, such as Windows or Apple
com-puters. In particular, we assume that you’re familiar with using windows, icons, and the keyboard and mouse, and that you know the basics of using your computer for things like the Internet or writing letters.
✓ The Raspberry Pi is not your only computer. At times, you’ll need to
have access to another computer, for example to create your SD card for the Pi (see Chapter 2). When it comes to networking, we assume you already have a router set up with an Internet connection and a spare port that you can plug the Raspberry Pi into.
✓ The Raspberry Pi is your first Linux-based computer. If you’re a Linux ninja, this book still gives you a solid reference on the Raspberry Pi and the version of Linux it uses, but no prior Linux knowledge is required.
✓ You share our excitement at the world of possibilities that the
Raspberry Pi can open up to you!
Other than those assumptions, we hope this book is approachable for every-one. The Raspberry Pi is being adopted in classrooms and youth groups, and this book is a useful resource for teachers and students. The Raspberry Pi is also finding its way into many homes, where people of all ages (from children to adult) are using it for education and entertainment.
How This Book Is Organized
This book is organized into six parts:✓ Part I shows you how to set up your Raspberry Pi, including guidance
on what else you need; how you download the Raspberry Pi’s operating system software and copy it to an SD card; and how you connect every-thing up. You’ll learn how to use the configuration software and log in to your Raspberry Pi.
✓ Part II gets you up and running with Linux, the operating system that
runs on the Raspberry Pi. You’ll learn about the desktop environment, which you can use to run programs, manage your files, browse the web, and view your images. Many Raspberry Pi users spend most of their time in the desktop environment, but others want to dig deeper into Linux, learning how to enter text commands to manage the computer and its files. The book also shows you how to do this, so you can exploit the full power of Linux.
✓ Part III is all about using your Raspberry Pi for work and play. You can’t use Windows or Mac OS software on your Raspberry Pi, so you need to find and install some new programs for work, photo-editing, and playing
03_9781118554210-intro.indd 3
4
Raspberry Pi For Dummies
music and video. You also learn how to build your first website, using HTML and CSS, the languages that underpin every website in the world.
✓ Part IV teaches you how to write your own programs for the Raspberry
Pi, using the two programming languages that come with the operating system. Scratch is highly visual and ideal for making games and anima-tions. After we introduce you to the concepts of Scratch, we show you how you can bring them together to make a shoot-‘em-up game. After that, you learn Python, a more powerful programing language that comes with the Raspberry Pi. We’ll show you how to create a basic Chatbot that analyzes what you type in and gives intelligent responses (sometimes, at least). After you’ve mastered the basics of Python, we show you how to write an arcade game using Pygame.
✓ Part V introduces you to some electronics projects you can undertake
with your Raspberry Pi. You learn the basics of electronics theory, how to use a soldering iron, and how the Raspberry Pi can be connected to your own electronics circuits. This section builds on your knowledge of Python to show you how to make two electronic games controlled by the Raspberry Pi, Marble Slalom, and Copycat. The last chapter in this part shows you how to make an analog-to-digital converter that you can use for a wide range of your own electronics projects.
✓ Part VI is the Part of Tens, a unique feature of the For Dummies series. This part contains concise guides to great software you can install on your Raspberry Pi and inspiring projects you can make with it.
✓ Finally, Appendix A covers troubleshooting and more advanced
con-figuration options of your Raspberry Pi. This gives you solutions for the most common problems people experience, and some guidance on directly editing the configuration files. You might not need this chapter, but it’s good to know it’s there if things go wrong! Appendix B provides a reference to the GPIO that you can consult when connecting your own electronics projects to the Raspberry Pi.
It’s up to you how you read this book. It’s been organized to take you on a journey from acquiring and setting up your Raspberry Pi, through learning the software that comes with it, to writing your own programs, and finally creating your own electronics projects. Some chapters build on knowledge gained in earlier chapters, especially the sections on Scratch, Python, and all of Part V.
We understand, though, that some projects or topics might interest you more than others, and you might need help in some areas right now. When a chap-ter assumes knowledge from elsewhere, we’ve included cross-references to help you quickly find what you might have missed. We’ve also included some signposts to future chapters too, so you can skip ahead to a later chapter if it provides the quickest answer for you.
03_9781118554210-intro.indd 4
5
Introduction
Icons Used in This Book
If you’ve read other For Dummies books, you know that they use icons in the margin to call attention to particularly important or useful ideas in the text. In this book, we use four such icons:
The Tip icon highlights expert shortcuts or simple ideas that can make life easier for you.
Arguably, the whole book is technical stuff, but this icon highlights something that’s particularly technical. We’ve tried to avoid unnecessary jargon and complexity, but some background information can give you a better under-standing of what you’re doing, and sometimes we do need to get quite techy, given the sophistication of the projects we’re doing. Sections highlighted with this icon might be worth re-reading to make sure you understand, or you might decide that you don’t need to know that much detail. It’s up to you! Although we’d like to think that reading this book is an unforgettable experience, we’ve highlighted some points that you might want to particularly commit to memory. They’re either important take-aways, or they are fundamental to the project you’re working on.
As you would on the road, slow down when you see a warning sign. It high-lights an area where things could go wrong.
Visit the Book’s Website
You can find the dedicated website for this book at www.dummies.com/go/ raspberrypifd. You can download the files used in the website design, programming, and electronics projects there. That saves you having to retype them, and also gives you a sound base you can build on for your own projects. Occasionally, we have updates to our technology books. If this book does have technical updates, they will be posted at www.dummies.com/go/ raspberrypifdupdates.
Both of us maintain our own personal websites too, which contain some additional information on the Raspberry Pi. Mike’s is at www.thebox. myzen.co.uk and Sean’s is at www.sean.co.uk.
03_9781118554210-intro.indd 5
6
Raspberry Pi For Dummies
03_9781118554210-intro.indd 6
Chapter 1
Introducing the Raspberry Pi
In This Chapter
▶ Getting familiar with the Raspberry Pi
▶ Figuring out what you can do with a Raspberry Pi
▶ Determining its limitations
▶ Getting your hands on a Raspberry Pi
▶ Deciding what else you need
T
he Raspberry Pi is perhaps the most inspiring computer available today. Although most of the computing devices we use (including phones, tablets, and games consoles) are designed to stop us from tinkering with them, the Raspberry Pi is exactly the opposite. From the moment you see its shiny green circuit board, it invites you to prod it, play with it, and create with it. It comes with the tools you need to start making your own software (orprogramming), and you can connect your own electronic inventions to it. It’s
cheap enough that if you break it, it’s not going to break the bank, so you can experiment with confidence.
Lots of people are fired up about its potential, and they’re discovering exciting new ways to use it together. Dave Akerman (www.daveakerman.com) and friends attached one to a weather balloon and sent it nearly 40 kilometers above the earth to take pictures of earth from near space using a webcam. Professor Simon Cox and his team at the University of Southampton connected 64 Raspberry Pi boards to build an experimental supercomputer, held together with Lego bricks. In the supercomputer (see Figure 1-1), the Raspberry Pis work together to solve a single problem. The project has been able to cut the cost of a supercomputer from millions of dollars to thousands or even hundreds of dollars, making supercomputing much more accessible to schools and students.
The Pi is also being used at the frontier of exploration. The FishPi project (www.fishpi.org) aims to create a vessel that can navigate across the Atlantic unmanned and take environmental measurements along the way, communicating with base by satellite. London Zoo is looking at using the Raspberry Pi in a device to detect and photograph animals in their natural habitats, called EyesPi.
05_9781118554210-ch01.indd 9
10
Part I: Getting Started with Raspberry Pi
Figure 1-1: Two of the Raspberry Pi boards used in the University of South-ampton’s supercom-puter, with the rest of the super-computer in the background.Courtesy of Simon Cox and Glenn Harris, University of Southampton
Although those projects are grabbing headlines, another story is less visible but more important: the thousands of people of all ages who are taking their first steps in computer science thanks to the Raspberry Pi.
Both of the authors of this book used computers in the 1980s, when the notion of a home computer first became a reality. Back then, computers were less friendly than they are today. When you switched them on, you were faced with a flashing cursor and had to type something in to get it to do any-thing. As a result, though, a whole generation grew up knowing at least a little bit about how to give the computer commands, and how to create programs for it. As computers became friendlier, and we started to use mice and win-dows, we didn’t need those skills any more, and we lost touch with them. Eben Upton, designer of the Raspberry Pi, noticed the slide in skill levels when he was working at Cambridge University’s Computer Laboratory in 2006. Students applying to study computer science started to have less expe-rience of programming than students of the past did. Upton and his univer-sity colleagues hatched the idea of creating a computer that would come with all the tools needed to program it, and would sell for a target price of $25. It had to be able to do other interesting things too so that people were drawn to use it, and had to be robust enough to survive being pushed in and out of school bags hundreds of times.
05_9781118554210-ch01.indd 10
11
Chapter 1: Introducing the Raspberry Pi
That idea started a six-year journey that led to the Raspberry Pi you probably have on your desk you as you read this book. It was released in February 2012, and sold half a million units by the end of the quarter. Early in 2013, it reached the milestone of one million sales.
Getting Familiar with the Raspberry Pi
When your Raspberry Pi arrives, you’ll see it’s a circuit board, about the size of a credit card, with components and sockets stuck on it, as shown in Figure 1-2. In an age when most computing devices are sleek and shiny boxes, the spiky Pi, with tiny codes printed in white all over it, seems alien. It’s a big part of its appeal, though: most of the cases you can buy for the Raspberry Pi are transparent because people love the look of it.Figure 1-2:
Up close with the Raspberry Pi.
There are two versions of the Raspberry Pi: the Model B (which was released first) and the Model A. The differences between the two are that the Model B has two USB sockets (whereas the Model A only has one), the Model B has an Ethernet socket, and editions of the Model B released after October 2012 con-tain twice the memory (512MB, compared to 256MB on the Model A and the first batches of the Model B). The Model A sells for $25, whereas the Model B sells for around $35.
05_9781118554210-ch01.indd 11
12
Part I: Getting Started with Raspberry Pi
The Raspberry Pi was made possible in part by the advances in mobile com-puter chips that have happened in recent years. At its heart is a Broadcom BCM2835 chip that contains an ARM central processing unit (CPU) and a Videocore 4 graphics processing unit (GPU). The CPU and GPU share the memory between them. The GPU is powerful enough to be able to handle Blu-ray quality video playback.
Instead of running Windows or Mac OS, the Raspberry Pi uses an operating system called Linux. It’s a leading example of open source, a completely dif-ferent philosophy to the commercial software industry. Instead of being cre-ated within the heavily guarded walls of a company, with its design trecre-ated as a trade secret, Linux is built by companies and expert volunteers working together. Anyone is free to inspect and modify the source code (a bit like the recipe) that makes it work. You don’t have to pay to use Linux, and you’re allowed to share it with other people too.
Unless you already use Linux, you won’t be able to run the software you have on your other computers on your Raspberry Pi, but a lot of software for Linux is free of charge.
Figuring Out What You Can
Do with a Raspberry Pi
The Raspberry Pi is a fully featured computer, and you can do almost any-thing with it that you can do with a desktop computer.
When you switch it on, it has a text prompt (see Chapter 5), but you can use a graphical windows desktop to start and manage programs. You can use it for browsing the Internet (see Chapter 4), word processing and spreadsheets (see Chapter 6), or for editing photos (see Chapter 7). You can use it for play-ing back music or video (see Chapter 9), or for playplay-ing games. You can use the built-in software to build a website (see Chapter 8). It’s the perfect tool for homework, but it’s also a useful computer for writing letters, managing your accounts, and paying bills online.
The Raspberry Pi is at its best, however, when it’s being used to learn how computers work, and how you can create your own programs or electronics projects using them. It comes with Scratch (see Chapter 10), which enables people of all ages to create their own animations and games, while learning some of the core concepts of computer programming along the way. It also comes with Python (see Chapter 12), a professional programming language used by YouTube, Google, and Industrial Light & Magic (the special effects gurus for the Star Wars films), among many others.
05_9781118554210-ch01.indd 12
13
Chapter 1: Introducing the Raspberry Pi
It has a General Purpose Input/Output (GPIO) port on it that you can use to connect up your own circuits to the Raspberry Pi, so you can use your Raspberry Pi to control other devices and to receive and interpret signals from them. In Part V, we show you how to build some electronic games con-trolled by the Raspberry Pi.
Determining Its Limitations
For something that costs so little, the Raspberry Pi is amazingly powerful, but it does have some limitations. Although you probably use it as a desktop computer, its power is closer to a mobile device (like a tablet) than a modern desktop PC.
By way of example, the Raspberry Pi Foundation says the Pi’s overall perfor-mance is comparable with a PC using a 300 MHz Pentium 2 processor, which you might have bought in the mid to late nineties, except that the Raspberry Pi has much better graphics. The memory of the Raspberry Pi is more limited than you’re probably used to, with just 512MB or 256MB available. You can’t expand that with extra memory in the way you can a desktop PC.
The graphics capabilities lag behind today’s market somewhat too: The Raspberry Pi Foundation says the Pi’s graphics are roughly the same as the original Xbox games console, which was released 10 years ago.
Both the Pentium 2 PC and the original Xbox were fine machines, of course, for their time. They’re just not as snappy as we’re used to, and that’s where you might experience some problems. You might find that the Pi can’t keep up with the demands of some modern software and that some programs don’t run fast enough to be useful on it. However, it’s easy to find programs, try them, and remove them if they’re no good (see Chapter 5), and plenty of programs for work and play run well on the Raspberry Pi (see Chapter 18). If you already have another computer, the Raspberry Pi is unlikely to usurp it as your main machine. But the Pi gives you the freedom to try lots of things you probably wouldn’t dare to try, or wouldn’t know how to try, with your main PC.
Getting Your Hands on a Raspberry Pi
The Raspberry Pi was created by the Raspberry Pi Foundation, a charity reg-istered in the UK. The charity’s six trustees funded the manufacture of the first large batch themselves, but it sold out rapidly so it quickly became clear that they needed something that would scale better.05_9781118554210-ch01.indd 13
14
Part I: Getting Started with Raspberry Pi
The Foundation now licenses the design of the Raspberry Pi to RS Components (www.rs-components.com) and Premier Farnell, which uses the brand name Element 14 (www.element14.com/community/groups/raspberry-pi). Both companies fund and manage the manufacture of the Raspberry Pi, market and sell it, and look after their customers. They accept orders through their websites and are able to offer a number of the accessories you might also need. It’s possible that more companies will license the design of the Pi in the future, so check the Raspberry Pi Foundation’s website at www.raspberrypi.org for current links to stores that sell the Pi.
Second-hand Raspberry Pis can be bought on eBay (www.ebay.com), but we would recommend getting a new one so you benefit from the customer support available, and have the peace of mind that it hasn’t been damaged by the previous owner.
Deciding What Else You Need
The creators of Raspberry Pi have stripped costs to the bone to enable you to own a fully featured computer for about $25–$35, so you’ll need to scavenge or buy a few other bits and pieces. I say “scavenge” because the things you need are exactly the kind of things many people have lying around their house or garage already, or can easily pick up from friends or neighbors. In particular, if you’re using a Raspberry Pi as your second computer, you probably have most of the peripherals you need. That said, you might find they’re not fully compatible with the Raspberry Pi and you need to buy replacements to use with the Pi.
Here’s a checklist of what else you might need:
✓ Monitor: The Raspberry Pi has a high definition video feed and uses
an HDMI (high definition multimedia interface) connection for it. If your monitor has an HDMI socket, you can connect the Raspberry Pi directly to it. If your monitor does not support HDMI, it probably has a DVI socket, and you can get a simple and cheap converter that enables you to connect an HDMI cable to it. Older VGA (video graphics array) monitors aren’t officially supported by the Raspberry Pi Foundation, but devices are available to convert the HDMI signal into a VGA one. If you’re thinking of buying a converter, check online to see whether it works with the Raspberry Pi first. A lot of cheap cables are just cables, when what you need is a device that converts the signal from HDMI format to VGA, not one that just fits into the sockets on the screen and your Raspberry Pi. If your monitor is connected using a blue plug, and the connector has three rows on five pins in it, it’s probably a VGA monitor. ✓ TV: You can connect your Raspberry Pi to a high definition TV using
the HDMI socket and should experience a crisp picture. If you have an
05_9781118554210-ch01.indd 14
15
Chapter 1: Introducing the Raspberry Pi
old television in the garage, you can also press it into service for your Raspberry Pi. The Pi can send a composite video signal through an RCA cable, so it can use a TV as its display. When we tried this, it worked but the text lacked definition, which made it difficult to read. If a TV is your only option, see Appendix A for advice on tweaking the settings to get the clearest possible picture. It’s better to use a computer monitor if you can, though.
✓ USB hub: The Raspberry Pi has one or two USB sockets (depending on
the model you get), but you should use a powered USB hub for two rea-sons. Firstly, you’re going to want to connect other devices to your Pi at the same time as your keyboard and mouse, which use two sockets. And secondly, you should use a USB hub because it provides external power to your devices and minimizes the likelihood of experiencing problems using your Raspberry Pi. Make sure your USB hub has its own power source independent of the Raspberry Pi.
✓ USB keyboard and mouse: The Raspberry Pi only supports USB
key-boards and mice, so if you’re still using ones with PS/2 connectors (round rather than flat), you need to replace them.
When the Raspberry Pi behaves unpredictably it’s often because the keyboard is drawing too much power, so avoid keyboards with too many flashing lights and features.
✓ SD card: The Raspberry Pi doesn’t have a hard disk built in to it, so it uses
an SD card as its main storage. You probably have some SD cards that you use for your digital camera, although you might need to get a higher capacity one. We would recommend a 4GB SD card as a minimum, and SD cards are cheap enough now that it’s worth getting an 8GB or 16GB one. Even that isn’t much space for your files and data compared to the hard drive on a modern computer, but you can use other storage devices such as external hard drives with your Raspberry Pi too. SD cards have differ-ent class numbers that indicate how fast you can copy information to and from them. Element14 sells a class 4 SD card with the operating system preloaded on it (see Figure 1-3), and RS Components recommends a class 6 SD card to use with the Raspberry Pi.
✓ SD card writer for your PC: Many PCs today have a slot for SD cards so
you can easily copy photos from your camera to your computer. If yours doesn’t, you might want to consider getting an SD card writer to con-nect to your computer. You’ll use it to copy Linux to an SD card for use with your Raspberry Pi, but you won’t be able to use it to copy files from your Raspberry Pi to a Windows computer. Alternatively, you can buy an SD card that has the recommended version of Linux already on it for use with the Raspberry Pi. That means you can avoid the expense of an SD card writer, but it doesn’t enable you to experiment with the different operating systems available for the Pi (see Chapter 2).
05_9781118554210-ch01.indd 15
16
Part I: Getting Started with Raspberry Pi
Figure 1-3: A SD card preloaded with the Raspberry Pi operating system.✓ USB keys: USB keys (also known as flash drives or memory sticks) are
fairly cheap and high capacity now (a 64GB USB key is readily afford-able), which makes them an ideal complement to your Raspberry Pi. You can transfer files between your PC and your Raspberry Pi using a USB key, too.
✓ External hard drive: If you want lots of storage, perhaps so you can use
your music or video collection with the Raspberry Pi, you can connect an external hard drive to it over USB. You’ll need to connect your hard drive through a powered USB hub, or use a hard drive that has its own external power source.
✓ Speakers: The Raspberry Pi has a standard audio out socket, compatible
with headphones and PC speakers that use a 3.5mm audio jack. You can plug your headphones directly into it, or use the audio jack to connect to speakers, a stereo, or a TV. If you’re using a TV or stereo for sound, you can get a cable that goes between the 3.5mm audio jack and the audio input(s) on your television or stereo. You won’t always need speakers: If you’re using an HDMI connection, the audio is sent to the screen with the video signal so you won’t need separate speakers, but note that this doesn’t work if you use a DVI monitor.
✓ Power supply: The Raspberry Pi uses a Micro USB connector for its
power supply, and is theoretically compatible with a lot of mobile phone and tablet chargers. In practice, many of these can’t deliver enough cur-rent (up to 700 milliamperes), which can make the Raspberry Pi perform unreliably. The resistance in the cables that connect the Pi to the power supply varies greatly too, and this can prevent peripherals like the
05_9781118554210-ch01.indd 16
17
Chapter 1: Introducing the Raspberry Pi
mouse from working. It’s worth checking whether you have a charger that might do the job (it should say how much current it provides on it), but for best results, we recommend buying a compatible charger from the same company you got your Raspberry Pi from. Don’t try to power the Pi by connecting its Micro USB port to the USB port on your PC with a cable, because your computer probably can’t provide enough power for your Pi.
✓ Case: It’s safe to operate your Raspberry Pi as-is, but many people prefer
to protect it from spills and precariously stacked desk clutter by getting a case for it. You can buy plastic cases on eBay (www.ebay.com), most of which are transparent so you can still admire the circuitry and see the Pi’s LED lights. These cases typically come as simple kits for you to assemble. The Pibow (www.pibow.com) is one of the most attractively designed cases, with layers of plastic giving it a rainbow look, side-on (see Figure 1-4). It’s designed by Paul Beech, who designed the Raspberry Pi logo. You don’t have to buy a case, though. You can go without or make your own (see Chapter 3). Whatever case you go with, make sure you can still access the GPIO pins so you can experiment with connecting your Pi to electronic circuits and try the projects in Part V of this book.
Figure 1-4:
The Pibow Raspberry Pi case.
Pibow™ Pimoroni Ltd (www.pibow.com)
05_9781118554210-ch01.indd 17
18
Part I: Getting Started with Raspberry Pi
✓ Cables: You’ll need cables to connect it all up, too. In particular, you
need an HDMI cable (if you’re using an HDMI or DVI monitor), an HDMI to DVI adapter (if you’re using a DVI monitor), an RCA cable (if you’re connecting to an older television), an audio cable (if connecting the audio jack to your TV or stereo), and an Ethernet cable (for networking). You can get these cables from an electrical components retailer and might be able to buy them at the same time as you buy your Raspberry Pi. Any other cables you need (for example to connect to PC speakers or a USB hub) should come with those devices.
The Raspberry Pi has been designed to be used with whatever accessories you having lying around to minimize the cost of getting started with it but, in practice, not all devices are compatible. In particular, incompatible USB hubs, keyboards, and mice can cause problems that are hard to diagnose.
A list of compatible and incompatible devices is maintained at http:// elinux.org/RPi_VerifiedPeripherals and you can check online reviews to see whether others have experienced difficulties using a particular device with the Raspberry Pi.
If you’re buying new devices, you can minimize the risk by buying recommended devices from Raspberry Pi retailers.
In any case, you should set a little bit of money aside to spend on accessories. The Raspberry Pi is a cheap device, but buying a keyboard, mouse, USB hub, SD cards, and cables can easily double or triple your costs, and you might have to resort to that if what you have on hand turns out not to be compatible.
05_9781118554210-ch01.indd 18
Chapter 10
Introducing Programming
with Scratch
In This Chapter
▶ Starting Scratch▶ Understanding the Scratch screen layout
▶ Positioning and resizing your sprite
▶ Making your sprite move
▶ Changing your sprite’s appearance
▶ Adding sounds and music
T
he Raspberry Pi was created partly to inspire the next generation of programmers, and Scratch is the perfect place to start. With it, you can make your own cartoons and games and discover some of the concepts that professional programmers use every day.Scratch is designed to be approachable for people of all ages. The visual interface makes it easy to see what you can do at any time without having to remember any strange codes, and you can rapidly achieve great results. Scratch comes with a library of images and sounds, so it only takes a few minutes to write your first Scratch program.
In this chapter, we introduce you to Scratch so you can start to experiment with it. In Chapter 11, we show you how to use Scratch to make a simple arcade game.
17_9781118554210-ch10.indd 173
174
Part IV: Programming the Raspberry Pi
Understanding What Programming Is
Before we dip into Scratch, we should clear up some of the jargon surrounding it. A program is a repeatable set of instructions to make a computer do
something, such as play a game. Those instructions can be extremely complicated because they have to describe what the computer should do in detail. Even a simple bouncing-ball game requires instructions for drawing the ball, moving it in different directions, detecting when it hits something, and then changing its direction to make it bounce.
Programming is the art and science of creating programs. You can create
programs in lots of different ways, and Scratch is just one of them. In Chapter 12, you’ll learn about Python, another one.
Scratch and Python are both programming languages, different ways of writing instructions for the computer. Different programming languages are best suited for different tasks. Scratch is ideal for making games, for example, but it’s not much use if you want to create a word processor or do some sophisticated mathematics. Using Python to create games takes longer, but it is more powerful than Scratch and gives you much more flexibility in the type of things you can get the computer to do.
Starting Scratch
You access Scratch from the desktop environment, so switch on your Raspberry Pi and then use startx to access it (see Chapter 4 for a guide to using the desktop environment).
To start Scratch, either double-click its icon on the desktop (which shows the head of a smiley orange cat), or select it from your Programs menu in the bottom left of the screen. You can find Scratch in the Programming folder.
Understanding the Scratch
Screen Layout
Scratch divides the screen into four main areas, as you can see in Figure 10-1. In the top right is the Stage, where you can see your game or animation take shape. There’s a cat on it already, so you can get started straight away by making him do things, as you’ll see in a minute.
17_9781118554210-ch10.indd 174
175
Chapter 10: Introducing Programming with Scratch
Figure 10-1: The screen layout when you first start Scratch. Enlarge Sprite
Shrink Sprite Small Stage Full Stage Maximize window
Scripts Area
Blocks Palette Sprite List Stage
Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu.
The bottom right area is your Sprite List. You can think of sprites as the characters in your game. They’re images that you can make do things, such as move around or change their appearance. For now, there’s just the cat, which has the name Sprite1.
You create a Scratch program by snapping together blocks, which are short instructions. On the left, you can see the Blocks Palette, which currently shows the Motion blocks, which include instructions to move 10 steps, rotate, go to a particular grid reference, and point in a particular direction. The tall middle panel is the Scripts Area. This is where the magic happens! You assemble your program in this space, by dragging blocks into it from the left.
17_9781118554210-ch10.indd 175
176
Part IV: Programming the Raspberry Pi
You can use two buttons in the top right (indicated in Figure 10-1) to toggle the size of the Stage between full and small. When the Stage is small, the Scripts Area is bigger, so you might find that useful when you’re writing scripts later in this chapter.
You’ll find it easier to use Scratch if you maximize it so it fills the screen. Click the button in the top right of its window, as indicated on Figure 10-1.
Positioning and Resizing Your Sprite
You can drag and drop your sprite (the cat) around the Stage to position it where you would like it to be at the start of your program.
You can also resize it. Two buttons above the Stage (indicated in Figure 10-1) are used to enlarge or shrink a sprite. Click one of them, and your mouse pointer changes to arrows pointing outwards (for enlarging) or inwards (for shrinking). Click your sprite on the Stage repeatedly to change its size to what you want.
When you’ve finished resizing, click something that isn’t a sprite to return the mouse pointer to normal and stop resizing.
Making Your Sprite Move
Experimenting with Scratch is easy. To try out different blocks, just click them in the Blocks Palette. For example, try clicking the block to move 10 steps, and you should see your cat move to the right. You can also turn her 15 degrees in either direction by clicking the appropriate blocks.
If your cat goes somewhere you don’t want it to (don’t they always?), you can click it on the Stage and drag it back to where you want it. You can fix rotation too by clicking the tiny cat at the top of the Scripts Area, holding down the mouse button, and rolling your mouse in a circle pattern on the desk. Not all of the blocks will work at the moment. Some of them need to be combined with other blocks, or only make sense at certain times. There’s no harm in experimenting, however. If you click something that doesn’t work, you might get an error message, but you won’t cause any harm to Scratch or your Raspberry Pi.
Next, we talk you through the different Motion blocks you can use.
17_9781118554210-ch10.indd 176
177
Chapter 10: Introducing Programming with Scratch
Using directions to move your sprite
You can use two different methods to position and move your sprites. The first is to make your sprite “walk,” and to change its direction when you want it to walk the other way.
Here are the five blocks you use to move your sprite in this way (see Figure 10-2):
Figure 10-2:
The directional movement blocks.
Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu.
✓ Move 10 Steps: This makes your sprite walk in the direction it is facing.
If your sprite has been rotated, the steps taken could move your sprite in a diagonal line across the Stage. You can click the number in this block and then type another number to increase or decrease the number of steps taken, but bigger numbers spoil the illusion of movement. ✓ Turn Right or Left 15 Degrees: This block rotates your sprite. As with
the number of steps, you can edit the number to change the degree by which your sprite is rotated. Your sprite walks in the direction it is facing when you use the Move 10 Steps block.
✓ Point in Direction 90: Whatever direction your sprite is facing, this
block points it in the direction you want it to face. Use this block as-is to reset your sprite to face right. You can change the number in this block to change the direction you want your sprite to face and the numbers are measured in degrees from the position of facing up (see Figure 10-3). It helps to think of it like the hands of a clock: When the hand is pointing right, it’s 90 degrees from the 12 o’clock position; when it’s pointing down, it’s 180 degrees from the top. To point left, you use –90. When you click the arrow in the right of the number box, it gives you a menu from which you can select the four main directions, but you can enter any number. You might be wondering whether you can enter 270 to point left, and the answer is that it works, but it can cause errors in your programs. If you turn your cat to direction 270 and then ask Scratch which way your cat is facing, it tells you –90. To avoid any inconsistencies like this, keep your direction numbers in the range –179 to 180.
17_9781118554210-ch10.indd 177
178
Part IV: Programming the Raspberry Pi
Figure 10-3: The number of degrees used to face in different directions. 180 0 90 –90 –135 –45 135 45✓ Point Towards: You can also tell the sprite to point towards the mouse
pointer or another sprite. Use the menu in this block to choose what you would like your sprite to point towards.
If you’re changing the number value in a block, you still need to click the block to run it.
Using grid coordinates to move
and position your sprite
You can also move and position your sprite using grid coordinates. That makes it easy to position your sprite at an exact place on the screen, irrespective of where it currently is.
Every point on the Stage has two coordinates, an X position (for where it is horizontally) and a Y position (indicating where it is vertically). The X positions are numbered from -240 at the far left, to 240 at the far right. The Y positions are numbered from -180 at the bottom edge of the Stage, to 180 at the top edge. That means the Stage is a total of 480 units wide and 360 units tall. The center point of the screen, where your cat begins his day, is where X equals 0 and Y equals 0. Figure 10-4 provides a quick visual reference of how the coordinates work.
17_9781118554210-ch10.indd 178
179
Chapter 10: Introducing Programming with Scratch
Figure 10-4: The grid coordinates on the Stage. 100 100 –100 –100 (X:0, Y:–180) (X:0, Y:180) Y X (X:0, Y:0) (X:–240, Y:0) (X:240, Y:0)
Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu.
When you move your mouse over the Stage, the grid reference of your mouse pointer is shown just underneath the Stage on the right.
Six Motion blocks use the X and Y coordinates (see Figure 10-5):
✓ Go to x:0 y:0: You can use this block to position your sprite at a specific
point on the Stage. By default, it returns a sprite to the center of the screen (x=0, y=0). Edit the numbers for X and Y to position your sprite somewhere else.
✓ Go to: Use this block to move your sprite to the mouse pointer’s
location, or to the location of another sprite if you have more than one. ✓ Glide 1 secs to x:0 y:0: When you use the Go To block, your sprite just
jumps to its new position. The Glide block makes your sprite float there smoothly instead. You can change the number of seconds the glide takes, including using decimals for part of a second (for example, 0.5 for half a second).
✓ Change X by 10: This moves your sprite 10 units right. You can change
the number of units and use a negative number if you want to move left instead. Note that this doesn’t affect your sprite’s vertical position and is independent of which way around your sprite is facing.
✓ Set X to 0: This changes the horizontal position of your sprite on the
Stage, without affecting its vertical position. The value 0 returns it to the center of the screen horizontally, and you can edit the number to position it left or right of that. Use a negative number for the left half of the screen and a positive number for the right half.
17_9781118554210-ch10.indd 179