Schweitzer Fachinformationen
Wenn es um professionelles Wissen geht, ist Schweitzer Fachinformationen wegweisend. Kunden aus Recht und Beratung sowie Unternehmen, öffentliche Verwaltungen und Bibliotheken erhalten komplette Lösungen zum Beschaffen, Verwalten und Nutzen von digitalen und gedruckten Medien.
Alex Bradbury (Cambridge, UK) is the Lead Software Developer on the Raspberry Pi.
Russel Winder (London, UK) was Professor of Computer Science at Kings College London and is the co-author of several tech books, including Developing Java Software and Python for Rookies. He lectures on Python at Skills Matter.
Introduction 1
What Is Programming? 1
Why the Raspberry Pi? 2
How Does this Book Work? 2
Chapter 1 Getting Up and Running 5
Setting Up Your Raspberry Pi 5
Solving Problems 6
A Quick Tour of Raspbian 7
Using LXDE (Lightweight X11 Desktop Environment) 7
Using the Terminal 8
Changing Configurations with Raspi-Config 10
Installing Software 10
Python 3 11
The Python Interpreter 11
Running Python Programs 11
Summary 12
Chapter 2 A Really Quick Introduction to Python 13
Drawing Picture with Turtles 13
Using Loops 16
Conditionals: if, elif, and else 18
Using Functions and Methods to Structure Code 20
A Python Game of Cat and Mouse 21
Understanding Variables 24
Defining Functions 24
Looping Through the Game 25
Summary 26
Chapter 3 Python Basics 27
Variables, Values, and Types 27
Values Have Types 28
Storing Numbers 29
Keeping Text in Strings 30
Boolean: True or False 31
Converting Between Data Types 32
Test Your Knowledge 32
Exercise 1 33
Storing Values in Structures 33
Non-Sequential Values in Dictionaries and Sets 37
Test Your Knowledge 38
Controlling the Way the Program Flows 38
Moving Through Data with for Loops 39
Going Deeper with Nested Loops 40
Branching Execution with if Statements 41
Catching Exceptions 42
Exercise 2 43
Making Code Reusable with Functions 43
Optional Parameters 46
Bringing Everything Together 46
Exercise 3 48
Building Objects with Classes 49
Getting Extra Features from Modules 54
Summary 55
Solutions to Exercises 56
Exercise 1 56
Exercise 2 56
Exercise 3 56
Chapter 4 Graphical Programming 57
Graphical User Interface (GUI) Programming 58
Adding Controls 60
Test Your Knowledge 62
Exercise 1 62
Creating a Web Browser 62
Adding Window Menus 71
Test Your Knowledge 73
Exercise 2 73
Summary 74
Solutions to Exercises 74
Exercise 1 74
Exercise 2 76
Chapter 5 Creating Games 77
Building a Game 79
Initialising PyGame 82
Creating a World 86
Detecting Collisions 88
Moving Left and Right 90
Reaching the Goal 92
Making a Challenge 93
Making It Your Own 97
Adding Sound 98
Adding Scenery 99
Adding the Finishing Touches 101
Taking the Game to the Next Level 102
Realistic Game Physics 103
Summary 108
Chapter 6 Creating Graphics with OpenGL 109
Getting Modules 110
Creating a Spinning Cube 110
Vectors and Matrices 112
Bringing It All Together 116
Let There Be Light 120
Calculating the Distance of the Point from the Light Source 120
Calculating Reflecting Angles 121
Making the Screen Dance 126
Building the 3D Model 128
Calculating the Sound Level 129
Taking Things Further 135
Adding Some Texture 136
Summary 136
Chapter 7 Networked Python 139
Understanding Hosts, Ports, and Sockets 139
Locating Computers with IP Addresses 140
Building a Chat Server 141
Tweeting to the World 144
Weather Forecasts with JSON 147
Testing Your Knowledge 149
Exercise 1 149
Getting On the Web 149
Making Your Website Dynamic 151
Using Templates 153
Sending Data Back with Forms 153
Exercise 2 155
Keeping Things Secure 155
Summary 159
Solutions to Exercises 160
Exercise 1 160
Exercise 2 161
Chapter 8 Minecraft 163
Exploring Minecraft 164
Controlling Your Minecraft World 164
Creating Minecraft Worlds in Python 165
Building Worlds 166
Drawing Pictures 166
Taking Things Further 169
Making the Game Snake 169
Moving the Snake 173
Growing the Snake 173
Adding the Apples 174
Taking Things Further 175
Summary 175
Chapter 9 Multimedia 177
Using PyAudio to Get Sound into Your Computer 177
Recording the Sound 179
Speaking to Your Pi 180
Asking the Program Questions 181
Putting It All Together 182
Taking Things Further 184
Making Movies 184
Using USB Webcams 185
Adding Computer Vision Features with OpenCV 187
Taking Things Further 190
Using the Raspberry Pi Camera Module 190
Creating Live Streams 193
Taking Things Further 196
Summary 196
Chapter 10 Scripting 197
Getting Started with the Linux Command Line 197
Using the Subprocess Module 200
Command-Line Flags 202
Regular Expressions 203
Testing Your Knowledge 206
Scripting with Networking 207
Bringing It All Together 209
Working with Files in Python 216
Summary 217
Chapter 11 Interfacing with Hardware 219
Setting Up Your Hardware Options 219
Female to Male Jumper Wires 219
Pi Cobbler 220
Solderless Breadboard 221
Stripboards and Prototyping Boards 221
PCB Manufacturing 222
Getting the Best Tools 222
Wire Cutters/Strippers 222
Multimeters 222
Soldering Irons 222
Hardware Needed for this Chapter 223
The First Circuit 224
Protecting Your Pi 228
Power Limits 229
Getting Input 229
Expanding the GPIO Options with I2C, SPI, and Serial 231
The SPI Communications Protocol 231
The I2C Communications Protocol 235
The Serial Communications Protocol 236
Taking the Example Further 236
Arduino 236
PiFace 237
Gertboard 237
Wireless Inventor's Kit 238
Trying Some Popular Projects 238
Robots 238
Home Automation 239
Burglar Alarms 239
Digital Art 239
Summary 239
Chapter 12 Testing and Debugging 241
Investigating Bugs by Printing Out the Values 241
Finding Bugs by Testing 245
Checking Bits of Code with Unit Tests 245
Getting More Assertive 250
Using Test Suites for Regression Testing 252
Testing the Whole Package 253
Making Sure Your Software's Usable 254
How Much Should You Test? 254
Summary 255
Index 257
Chapter 1
WELCOME TO Learning Python with Raspberry Pi. In this book, you'll learn how to unlock the full power of the tiny computer, from 3D graphics to games programming to controlling electronics to tweeting. You'll see what's going on under the hood and learn how to create programs that take advantage of every feature of this minuscule computer.
To follow this book, you'll need a few bits of equipment:
There are also a few optional bits of kit that may help:
It is possible to do everything in this book with a model A Raspberry Pi. The real advantage of a model B as far as programming is concerned is the network port. This port will make it easier to connect to the Internet, which you'll need to do to install some software.
Any USB keyboard and mouse should work fine. Most SD cards should work, although there are a few that will cause problems. If you're unsure, buy one from a Raspberry Pi online shop (there are links to a few on http://raspberrypi.org).
The Raspberry Pi has a HDMI (high-definition multimedia interface) video output, but most monitors have VGA or DVI input. If at all possible, use a monitor that has DVI or HDMI input. A HDMI-to-DVI converter should cost only a few pounds/dollars and shouldn't detract from the image quality. HDMI-to-VGA converters are available, but they're more expensive and can cause problems, so use them only if you have no other option.
Most micro USB power supplies from reputable manufacturers should work; however, some cheap ones from no-name companies have caused problems, so if possible, don't skimp too much on this. You could use a USB cable from a normal computer to power your Pi.
Powered USB hubs are recommended for the power-related problems described later in this chapter. Not all USB hubs are powered, so make sure that whatever one you get plugs into the mains electricity to get extra power.
We talk more about camera options in Chapter 9 on multimedia. The only thing to say here is that if you do choose to get a USB webcam, make sure it's compatible with the Raspberry Pi. There's a partial list of working web cams at http://elinux.org/RPi_USB_Webcams.
You'll need to connect your Pi to the Internet to install the software you need in this book. You can do this either by plugging your Pi into your router with a network cable or by using a USB wireless dongle, which will add WiFi connectivity.
The most common problems with the Raspberry Pi are power-related issues. Not all micro USB power sources can provide enough power, and it becomes more of a problem as you connect peripherals to your Pi, or when you overclock it (see Chapter 5 for more details). Power-related problems will usually manifest themselves as the computer crashing, so if you find that your Pi becomes unstable, this is the best place to start. A good way to get around such issues is to connect your Pi to one power source and connect all the peripherals (keyboard, mouse, and so on) via a powered USB hub.
The second most common cause of problems with Pis is the SD card. These issues can be caused by power supply problems, or they can be problems with the cards themselves. It's important to take preventative measures here to ensure that your data is safe, and that means backups! You can use a service such as Google Drive (although this runs slowly on the Pi), or you can simply keep extra copies of any work on a USB memory stick. SD card issues will usually manifest themselves by the Pi displaying error messages when you try to start it. Most of the time you can solve the problem by reinstalling Raspbian, but if this doesn't work, you'll need to get a new SD card.
If neither of these help, then you'll need to dig a little deeper. The most useful places to look are the kernel buffer and the system log file. The kernel buffer is usually best if you're having problems with hardware, such as a USB device not working. If you open LXTerminal and type:
dmesg
It will output all the messages from the Linux Kernel. The last ones are the most recent and should show any problems.
The system log file (often called syslog) can be displayed with:
cat /var/log/syslog
Again, the most recent messages will be at the end. The information in both of these can be somewhat cryptic. If you still can't work out the problem after reading these, the best place to go is the Raspberry Pi forums at www.raspberrypi.org/phpBB3/. There's a community of helpful people who should be able to point you in the right direction.
This is a book about programming, not about generally using Raspbian, so we won't dwell on it too much, but you'll find it useful to know a bit about what's going on.
There are a few operating systems available for the Raspberry Pi, but the instructions in this book are all based on Raspbian, which is the default operating system, and the best choice for a new user. If you have some experience with Linux, you could use Arch or Fedora if you like, but you'll have to change the apt-get commands to ones suitable for your package manager.
The easiest way to install Raspbian on your Pi is using NOOBS, which is available from www.raspberrypi.org/downloads. You'll also find a quick start guide at that website that will tell you everything you need to know to get up and running.
There are two different ways of interacting with Raspbian—from the terminal and using the graphical system (LXDE).
The Lightweight X11 Desktop Environment is the standard windowing system for Raspbian. Its basic setup is the same as most versions of Windows pre-Windows 8. There's a button in the bottom-left side of the screen that opens an applications menu, and currently running applications are displayed in the bar along the bottom (see Figure 1-1).
Figure 1-1: The LXDE desktop with the menu open.
If you get a black screen with white text asking you to log in when you boot up your Pi, it means that you haven't set it up to start LXDE automatically. Don't worry; just log in with the username pi and the password raspberry, and then type the following:
startx
You can set it up to boot into LXDE automatically using raspi-config (see the next section).
LXDE is great for many tasks, but sometimes you'll need to use the command line. This is an incredibly powerful interface that's accessed through the terminal. In LXDE, that means opening the LXTerminal application.
When you open LXTerminal, you should see the following line:
pi@raspberrypi~$
This signifies that you are using the username pi on a computer called raspberrypi, and you are in a directory called ~.
In Linux, all directories start from / or root. This is the base of the directory tree and every directory is located in some subdirectory of this. You can move between directories using the cd (change directory) command. Start by moving to this root directory with:
cd /
You should now seen that the command prompt has changed to
pi@raspberrypi/$
You can list the contents of this directory with the command ls. One of the subdirectories is called home. This is where every user on the system has his home directory. Move into it and view its contents with:
cd home ls
There should only be one directory called pi. The command prompt should now have changed to show that you're in the directory /home. Move into the only subdirectory with:
cd pi
Now the command prompt will have reverted to:
This is because the character ~ is a shorthand for the current user's home directory. When you type ~ in the terminal, the computer converts it to /home/pi.
There is much more to learn about the command line. So much so that it would take another book this size to cover it with any semblance of completeness. However, you don't need to know everything to start using it, and whenever we tell you to use LXTerminal, we tell you exactly what to type.
Tip
If you are interested in learning more about the Raspberry Pi, or Linux in general, the command line is an excellent place to start, and there's loads of information about it both online and in print. The Linux command-line book, which you can browse for free online, is an excellent place to start. See http://linuxcommand.org/tlcl.php.
We'll leave you with two pieces of advice. Firstly, don't be afraid of the terminal. It can be a bit daunting at first, but the only way to learn how to use it is to use it. Secondly, almost all commands have built-in help that...
Dateiformat: ePUBKopierschutz: Adobe-DRM (Digital Rights Management)
Systemvoraussetzungen:
Das Dateiformat ePUB ist sehr gut für Romane und Sachbücher geeignet – also für „fließenden” Text ohne komplexes Layout. Bei E-Readern oder Smartphones passt sich der Zeilen- und Seitenumbruch automatisch den kleinen Displays an. Mit Adobe-DRM wird hier ein „harter” Kopierschutz verwendet. Wenn die notwendigen Voraussetzungen nicht vorliegen, können Sie das E-Book leider nicht öffnen. Daher müssen Sie bereits vor dem Download Ihre Lese-Hardware vorbereiten.Bitte beachten Sie: Wir empfehlen Ihnen unbedingt nach Installation der Lese-Software diese mit Ihrer persönlichen Adobe-ID zu autorisieren!
Weitere Informationen finden Sie in unserer E-Book Hilfe.
Dateiformat: PDFKopierschutz: Adobe-DRM (Digital Rights Management)
Das Dateiformat PDF zeigt auf jeder Hardware eine Buchseite stets identisch an. Daher ist eine PDF auch für ein komplexes Layout geeignet, wie es bei Lehr- und Fachbüchern verwendet wird (Bilder, Tabellen, Spalten, Fußnoten). Bei kleinen Displays von E-Readern oder Smartphones sind PDF leider eher nervig, weil zu viel Scrollen notwendig ist. Mit Adobe-DRM wird hier ein „harter” Kopierschutz verwendet. Wenn die notwendigen Voraussetzungen nicht vorliegen, können Sie das E-Book leider nicht öffnen. Daher müssen Sie bereits vor dem Download Ihre Lese-Hardware vorbereiten.
Bitte beachten Sie: Wir empfehlen Ihnen unbedingt nach Installation der Lese-Software diese mit Ihrer persönlichen Adobe-ID zu autorisieren!