Notes: ® ® ® ® The Raspberry Pi Education Manual Introduction 1
The Raspberry Pi Education Manual Version 1.0 December 2012 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
The Raspberry Pi Education Manual Contents 000 001 000 0. Introduction.............................................................................. 5 001 1. A beginner’s guide to Scratch............................................. 7 1.1 Scratch basics................................................................ 9 1.2 Moving sprites...............................................................15 1.3 Animation (loops)...........................................................18 1.4 Maths cat.........
100 100 4. Human-computer interfacing.......................................... 113 4.1 Twitter........................................................................ 115 4.2 Email application........................................................ 116 4.3 Remote Procedure Call.............................................. 118 4.4 Web applications........................................................ 120 4.5 General Purpose Input/Output (GPIO)........................ 125 101 101 5.
This manual was brought to you by... This manual is a bit different. It was written entirely by unpaid volunteers, all of whom are keen to share their expertise and enthusiasm for computing with as many people as possible. What all of these contributors have in common, apart from a youth spent mainly indoors in front of ZX Spectrums and Commodore 64s, is that they’re all members of the organisation Computing at School (CAS).
Hello, Raspberry Pi users Chapter 0 Congratulations! You have in your possession a Raspberry Pi. A small but powerful computer designed to help you understand and explore the almost-magical world of computing. Use it wisely; it’s an object of great power. Notes: What is the Raspberry Pi? The Raspberry Pi is a computer, very like the computers with which you’re already familiar. It uses a different kind of processor, so you can’t install Microsoft Windows on it.
Notes: What am I going to learn? This user manual is different. Don’t expect a dry-as-dust description of how to plug things in or where to find your serial number. And you certainly won’t learn how to create a spreadsheet or a presentation. That’s really not computer science, it’s something else entirely. Instead, think of this manual, along with your Raspberry Pi, as a “computer science set”.
A beginner’s guide to Scratch Chapter 1 Scratch is visual programming environment. With it, you can create your own animations, games and interactive art works. And, while you’re doing that, you’ll learn some important principles and techniques of programming without actually having to write your own code. It’s a great way to get started. To find out more about Scratch, visit the web address scratch.mit.edu How to use this guide We have tried to make this guide as straightforward to use as possible.
The Scratch interface PRESENTATION MODE Go fullscreen to show off your projects sprite rotation style current sprite info Share save language toolbar TABS This is where you edit scripts, costumes or sounds VIEW MODE Change the size of the Stage STOP SIGN Stops your scripts Green flag A way to start scripts BLOCKS PALETTE The blocks of code you’ll use to program your sprites STAGE Where your Scratch projects do their thing MOUSE X-Y DISPLAY Shows the location of the mouse cursor NEW SPRITE BUTTONS
Notes: Lesson 1.1: Scratch basics Learning objective: In this exercise, you will learn how to use the Scratch graphical user interface (GUI), how to create characters (sprites and costumes) and stages (backgrounds) for your projects, and how to add scripts. Resources: The sprites “cat” and “roman_cat”, and the background “roman_stage”. Have you ever been in a school play? If you have, you’ll know that to put on a play you need a stage, actors, costumes and a script.
Notes: Let’s have some fun with the cat First, let’s give the cat something to say. We’ll start with “Hello, World”. This is generally the first thing a computer programmer learns to do (don’t ask me why). As you are now learning a programming language, you’d better start with “Hello, World”, too. Making the cat talk To make the cat say “Hello, World”, we’re going to be working with “blocks”. These are handy pieces of code, each containing an instruction for your sprite to follow.
We have to run a program to make it work. You can do this by just double-clicking your script, if you only have one script. But if we have more than one script, we might want to start them at the same time. We can use a “green-flag event” for this. To find the block for green-flag events: 1. Click on the Control button in the Blocks Palette. 2. F ind the block labelled “when [picture of a green flag] clicked”. 3.
Notes: Changing the way the sprite looks 1 C lick on your sprite to select it. In the Scripts area, click on the Costumes tab. 2 We are going to make a third costume for the cat, so click on Copy. A new cat costume 3 should appear. S elect “costume3” and click on Edit. This will open the Paint Editor. Experiment with all the buttons and tools to find out what they do. 4 O nce you feel at home, draw some clothes on the costume and click on OK.
Notes: The stage It’s time to give that cat a stage. We could be lazy and just import a picture to use as a background, but let’s say that we’re feeling energetic and want to draw our own. 1 C lick on the stage in the Sprite List (bottom-right of the screen). Now click on the Backgrounds tab for the stage and click on the Edit button. 2 A s before, the Paint Editor will open. Draw a stage for your sprite. When you have finished, click on OK.
Notes: Saving your work This is a good time to save your project. You would be wise to do this every 10 minutes or so, then you can be sure that you won’t lose any of your hard work. When working on a big project, save it in two places, then you have a backup. To save your project, click File, then Save – the Save Project window will open. Tip... By default, it will save your work to the Scratch Projects folder. This is a sensible place to store your work, so type in a new filename, at the bottom.
Notes: Lesson 1.2: Moving sprites Learning objective: In this exercise, you will learn how to move sprites around the Scratch screen in a controlled way and how to tell a joke. Resources: The sprite “roman_cat” and the background “roman_stage”. The cat is feeling a bit lonely, so we’d better create some characters for it to play with. You can either paint your own sprites or import sprites from the Scratch Costumes folder. Use the New Sprites buttons to do this.
Notes: Use the Import Sprite button to find and import the sprite “boy4-walking-c”. From the Costumes tab, click Edit and use the Flip Horizontally tool. There are also buttons to make your sprite bigger, smaller, rotate counterclockwise, rotate clockwise, as well as flip horizontally and flip vertically. Try them out. I have also used the shrink button to make my boy smaller. Make your sprites tell a joke Let’s make the sprites tell each other a joke.
Notes: Positioning your sprite Ok, we’ve told a joke. But this play is looking a bit static, so let’s make our characters move. The first job is to move our two characters to their start points. In my play, the cat will come in from the left and the boy from the right. You may have come across x and y axes when creating graphs. the Y coordinate the x coordinate The coordinates of any point on the stage are shown at its bottom-right-hand corner.
Notes: Over to you Task: Now add some code to your other character to move it to the right of the stage and then after a short delay move it into the centre stage. Well done! You have certainly got the hang of moving sprites about the screen. Why not add some more characters to your stage and get them to tell jokes? If you are having problems, you can load the sample code, “roman_play.sb”, to see how the program is put together. Feel free to change things and to experiment, as this is a great way to learn.
We need some script to make the bee look as if it is flying. We do this by switching from one costume to another and back again, making the bee appear to flap its wings. As we do this we will also make the bee move forwards. Now, build your own script to make the bee fly. You will need blocks from Control, Looks and Motion. If you get stuck, have a look at the screenshot of our code. You’ll find it further on in the lesson. This is the code to make your bee fly.
It looks a bit different because it has a gap so that we can put code you want to repeat inside it. Just drag the “repeat [10]” block to sit directly under the Notes: “when Sprite1 clicked” block. It will automatically fit around your block of code, causing it to repeat itself. Here is the code we need to animate the bee so that it flies all the way from one side of the screen to the other. Using the repeat loop, you can make the sprite do the same actions over and over again.
Notes: Hands on: the Pollination Project This is the storyboard of my pollination project. I added two more costumes to my bee sprite to show it carrying pollen and I have drawn a flower sprite with some stamens in blue. But I didn’t want to stop there. I wanted the bee to visit the second flower – a female – from the other side of the screen, so I copied all four costumes for the bee sprite and flipped them horizontally. I also copied, flipped and edited the male flower to create a female flower sprite.
Here’s the code for all three sprites in the pollination project. Code for the bee Notes: Code for the male flower Code for the female flower Because I had three different sprites with their own scripts, I used the “when [green flag] clicked” event to run them all together. Wow! That is quite a complicated project, but if you break up your animation into lots of little scenes it makes it easier to plan and to program.
Notes: Lesson 1.4: Maths Cat Learning objective: You will learn how to use variables to store data for using in a program. You will also learn how to use operators to do simple sums. Resources: The default sprite “cat” on the default white background. Do you find maths difficult? Can you imagine what it would be like to be able to do millions of sums in seconds and always get them right? Even the most complicated sums you can think of? Computers are fantastic at maths. In fact, maths is what they do best.
Notes: Tip... Give each variable a name that reminds you what is stored in it. For example, if you are creating a game and you use a variable to store the score, then a good name for the variable would be “game_score”. If you wanted to use a two-word name for your variable, you would separate the words with an underscore (the “_” character), not a blank space. Using variables in Scratch Ok, now we’re going to create and use variables.
In this example, we set the cat’s score to 100 points by clicking on the cat sprite. But there are plenty of other ways to put a number into a variable. The method you choose will depend on how you want to use the variable. Inputting the numbers Your teacher has set you four sums. The sums are: 56 + 39 = 87 - 42 = 16 x 9 = 240 ÷ 6 = We’re going to show you how to get Maths Cat to do this homework for you. Let’s start with the first question, 56 + 39.
Notes: Click on Sensing, select the block labelled “answer” and drag it onto the number ”0” in the previous block. Your script should look like the one in the screenshot above. Now the program knows the first number in your sum. To tell it the second number, repeat the process above but remember to change “first_number” to “second_number” in the drop-down box of the variable block. Now for the really clever bit To do sums in Scratch, you need something called an “operator”.
Notes: We’re not finished yet. We’ve told the program to add our numbers, but we need to store that answer in one of our variables. From Variables in the Blocks Palette, drag “set [first_number] to [0]” to the Scripts tab. Change “first_number” to “result” and drag your “add” operator onto the number “0”. Your block should look like this: Finally, we also need to tell Scratch to display the answer to the sum. Otherwise, it will keep it to itself (and that’s no good to us).
Click on Operators once more in the Script block and you’ll see that there are other operator blocks there too: for subtraction, multiplication and division. add subtract multiply divide If you want the cat to take away then simply swap the “add” block in the script above for a “subtract” block, and so on until the cat has done all you homework for you.
Notes: Lesson 1.5: Artificial intelligence Learning objective: In this exercise, you will learn how to put data into a program and get your program to make a decision based on that data. Resources: The sprites “cat” and “bluedog”; the backgrounds “brick-wall1”, “sydney”, “paris” and “new_york”. Artificial intelligence is an area of computer science where people try to make computer programs that are smart in some way or another. The idea is to make computers seem like they are thinking like humans.
Each time we use this program the country variable will be set to a letter. But the next time we use the program, we want the country variable to be empty. So we “empty” it by setting it to “0”, ready for the next user. Question: Study the script. Can you work out what it will do when the program is run? As the cat asks questions, the dog’s answers are stored in the two variables “holiday” and “age”. The script will use these later. Now for the intelligent part: the conditional statement.
Notes: The “if/else” block. Take the little script that was in your “if” block and put it into the “if” bracket of an “if/else” block. The result should look like the screenshot below. Is the dog old enough to go on holiday? We also need to find out if the dog is old enough to go on holiday by herself. We will need to use a second “if/else” block. Drag it onto the Scripts tab, but don’t attach it to your script just yet – leave it floating by itself. We’re going to ask the dog how old she is.
Notes: Before we move on to the next step, take your second “if/else” block and place it inside the “else” bracket of your first “if/else” block: the one you used to find out if the dog wanted to go on holiday. Your script should now look like the block of code in the screenshot above.
Finally, complete your script with a “wait [ ] secs” block and “stop all” block from Control. Set the value of the “wait [ ] secs” to “4” and place both blocks at the very Notes: end of your script, outside both “if/else” blocks. The cat has chosen A. A A country country So A is stored in the variable “country”. The destination the dog chooses will be stored in the variable “country”. This is important, because this variable will be used by the script for the stage to determine the script’s output.
The full script Phew, that was complicated. But hopefully you managed it all in the end. Just to make things a bit easier, here are the full scripts for both the cat sprite and the stage. The code for the cat The code for the stage Notes: To see a sample of the code for this lesson, open RPiScratch/Projects/holiday_dog.
Notes: Over to you Question: Study the code shown above for the cat sprite and the stage. Do you understand it? Task: Experiment with the code. See if you can add some extra questions. A final word In fact, the cat is not intelligent at all. Computers have no intelligence – it is the programs that run on them that make them appear intelligent. This is why we use the term “artificial intelligence”.
Notes: This script will make our robot move on our command, but only in one direction. Have a look at the screenshot above. We have used the “when [space] key pressed” event from Control to run the program. The robot sprite is moved to the centre of the screen using a “go to x: [0] y: [0]” block from Motion (see “Positioning your sprite”, in Lesson 1.3). The rest of the code is placed inside a “repeat until” loop (from Control).
Notes: Robot project Resources: The sprite “robot_control” and the background “robot_maze”. We have included the code of a more complete version of the robot program, “Robot_2” (see the screenshot above). In this version, the robot can be moved up, down, left and right. Task: Now it’s your turn to do some programming. Program the robot and then use your program to make the robot follow the yellow path on the “robot_maze” background.
Notes: Line-following vehicle (LFV) Resources: The sprite “yellow_car” and the background “line_background”. That robot is like something out of a corny science-fiction film. Let’s look at a more modern example. Scientists are experimenting with vehicles that can drive themselves. One way of doing this is by programming the vehicle to follow a line painted on the road surface. These vehicles are known as “line-following vehicles”, or LFVs.
Once the program can detect two colours touching, then we can tell it how to respond when this happens. The colour event becomes a trigger, causing the Notes: program to do something. To set the colours in your block, click on one of the little coloured squares. Your mouse-pointer will turn into an “eye-dropper”. Use the eye-dropper to click on the colours you want to use in your block.
Now, we need to use the red patch on the car’s bumper as a red sensor. The program will then be able to detect when the line turns left and tell the car to turn to the left too. Here’s the code you need to finish your LFV program: Tip... If your car stops at an odd angle, and you can’t straighten it out, you can import the “yellow_car” sprite again, drag and drop your finished script onto the new sprite and then delete the old one. Tip... As you can see, the program is run with a green flag event.
Notes: Barrier support Traffic-light box Now we need our sprites. Import “lights” and “barrier” from the RPiScratch/Resources/Costumes folder. Look at the image above, and you’ll see that the “lights” sprite has four different costumes. By switching costumes quickly, we can make it look as if the lights are flashing. The last thing we need to do before we start building our script is to import the sound of the level-crossing alarm.
Notes: Import your sound effect from the Sounds tab. You’ll find it right next to the Scripts and Costumes tabs. Now, let’s build our script. Before you start, select the “lights” sprite in the Sprites List. First things first: we want to start with the lights out. So we use a green flag event to switch our lights sprite to “costume1”, which shows three black lights.
To make the red lights appear to flash we must switch the two red light costumes repeatedly. We use a “repeat” loop for this. Build the script on the previous page. You’ll need to experiment with the number of repeats until you get the timing right. This is the finished program for the lights, with all the blocks in place. Notice that you have three separate scripts, not touching each other.
In the script for the barrier, I have used a “when [ ] key pressed” block from Notes: Control, with its value set to “t”. Think back – the script for the lights also starts when you press the “t” key. In this way, lights and barrier are synchronised: that means they both start at the same time. To lower the barrier, we will rotate the pole in stages by using a “repeat” block. Experiment with the number of repeats and the angle of turn to move the barrier just the right amount.
Notes: Prancing Pony game Resources: The sprites: “pony” and “girl” and the background “field”. The aim of the game: A pony moves around a field, making random changes of direction. Using the mouse, the player controls the girl sprite. To score points, you must put the girl on the pony. There are four tasks for you to program: 1. Move the pony round the field. 2. Make random changes in direction of the pony. 3. Move the girl with the mouse pointer. 4.
Notes: 2. Random changes in direction If the pony never changes direction except when it hits an edge, the game will get a bit dull. So we’ll use another “forever” loop to make the pony randomly change direction from time to time. The “pick random [ ] to [ ]” Operator block has been set to pick a random number from 1 to 4. If the number picked is 1, the pony will turn 180 degrees. This is set to happen every 0.5 seconds by the “wait” block. 3.
Hang on a second! Every time the red touches the blue dot, “score” is changed to “score + 1”. If you are good at maths that should set the alarm bells ringing! How can something be itself plus one? Don’t worry; programmers often do this. Remember that a variable is not a number; it is a container that can store numbers. We can do a sum with the number and put the result back into the same container. To see a working example of the Prancing Pony game, open RPiScratch/Projects/prancing_pony.
To do all this, you’ll need, along with the green flag, blocks from Looks and Motion. To move the car, we use our old friend the “forever” loop. The car moves one step each cycle. If the car leaves the track, it will touch the green grass. This event will cause the first “if” block to crash the car and stop the script for the car. As the car crosses the finish line, it will touch the white line. This event will cause the second “if” block to say “I win!” and stop all the script running for both cars. 2.
The changes you need to make to your code for the purple car are: Notes: The purple car should line up next to the red car at x: 30 y: 115. You should also use the “x” key to turn the car to the right and the “z” key to turn Tip... the car to the left. To see a finished example of this game, open RPiScratch/Projects/racing_game_v1. Over to you Task: Add the sound of racing cars to enhance the game. You’ll need to record or create your own sound file.
What next? Congratulations! You are now a Scratch programmer. Hopefully, this is just the beginning for you, and you will be inspired to create your own programs using the Scratch language. There are many other skills and programming techniques to learn. Happily, one of the great things about Scratch is the wealth of support and advice on the internet. I have included a few links to some online tutorials for you to explore: http://learnscratch.org http://www.scratch.ie http://scratch.redware.com/index.
Notes: Build your own blocks When you become an advanced user of Scratch, you may find that there isn’t a script block for a particular job you want to do. Or you might want to improve your program by creating better blocks. Help is at hand with BYOB at http://byob.berkeley.edu Thank you for reading this guide. I hope it helps you to have hours of fun with your Raspberry Pi. Now it’s time to move on to the next chapter, in which you will learn how to program in the Python language as well.
Experiments in Python Chapter 3 In the previous sections you have seen how to develop programs using Scratch and Greenfoot. These are a great environments for learning how to construct a program from component parts. They take data from the program and the user, manipulate it and then change what you see on screen by following the instructions in your program. However, this style of programming has limitations when it comes to constructing solutions to much larger and more complex problems.
Notes: Lesson 3.1: Getting to grips with Python From the menu on your desktop, you should be able to find “Programming” and then “Idle3”. Select this to open up a special Python editor for creating Python programs, called “IDLE”. If you cannot find it, press ALT-F2 and then type “Idle3” in the box that appears. The first thing IDLE gives you is a “Python Shell”. Snakes don’t have shells but if Python were a nut, this would be its shell.
Then you can use your arrow keys to move the cursor up to the line beginning with “for” and then press Return, twice. If you are wondering why you need to press Return twice; the first time is to complete the “for” command. When you press the second time, Python recognises you have finished that command and executes what you have typed. Now let’s get some real computer graphics going. Enter this: >>> import pygame After a couple of seconds you’ll see the prompt reappear.
You should now have a display on the screen, which has a surface of 500 x 500 tiny dots, or “pixels”. That’s a grand total of 250,000 pixels. Let’s change all 250,000 pixels to a deep blue colour using that “deepblue” tuple we created. >>> surface.fill(deepblue) You have filled the surface with the blue colour, but nothing will happen on screen. The computer does not know you have finished drawing things to the surface, so it doesn’t do anything just yet.
Notes: Try making up your own colours. >>> PiColour = (123,456,789) >>> surface.fill(PiColour) >>> pygame.display.update() Argh! Now that wasn’t fun. You created a bad colour and Python has told you (in American). TypeError: invalid color argument You will have to watch for American spellings like these when writing commands to computers, as a lot of computing standards are developed in the USA. Python is telling you that the colour tuple is not valid.
Going round in circles Notes: Notes: Now you have filled the background, let’s add a circle to the surface. >>> surface.fill(deepblue) >>> position = (250,250) >>> radius = 50 >>> linewidth = 2 >>> pygame.draw.circle(surface, mintcream, position, radius, linewidth) Update again to see the circle added. >>> pygame.display.update() Try changing some of the numbers for drawing the circle and see what happens. Remember to update after each circle you add to the surface.
>>> position = (280,300) >>> radius = 80 >>> pygame.draw.circle(surface, mintcream, position, radius, linewidth) >>> pygame.display.update() If you want to start again, just fill the surface with blue, and update again. >>> surface.fill(deepblue) >>> pygame.display.update() Not responding When you use PyGame interactively, like this, it can get stuck sometimes. This is because PyGame is trying to send events back to you – information about things it wants you to know about.
Notes: Maths homework What a nightmare. Only just getting started and already there is homework. Computers and computer science share a great deal with mathematics. We’ve drawn a colourful circle or two, but now it is time to look at some number crunching.
Notes: Just add Raspberry Pi So, the same question. What are the factors of all the numbers from 1 to 50? Before you can start programming, you will need to start up an editor so that you can type in instructions to the Raspberry Pi. Open a new editing window from the File menu in IDLE. This will allow you to work in the IDLE text editor. Open up the IDLE editor as before, but this time use the File menu to select a new editing window. This is no longer the Python shell, but a text editor.
To make this program run, you can select “Run Module” from the editor’s Debug menu or simply press F5 and it will ask you to save before you can run. Press “OK” and then give your first program a name – we will call it “Factors.py”. Note: I t is important to include the “.py” part of this name, so that Python can easily recognise this as a program it can interpret. After you press “Save”, the program will run and you will see a lot of numbers display in the python shell.
Notes: The Fibonacci Sequence Let’s write another program to work out a famous mathematical sequence. Each number in the Fibonacci Sequence is simply the previous two numbers added together; starting with 0 and 1. Create a new file using IDLE and name it “Fibonacci.py”. The following will calculate the numbers in the sequence up to the first value that is larger than 100.
Notes: Bits and bytes If you don’t already know, computers work in “binary”. Rather than counting from 0 to 9 for each unit as we do every day, they count from 0 to 1 for each unit. In decimal numbers, from the right, the numbers are units, then 10s, 100s, 1000s and so on. Each one is 10 times the previous one. In binary, the right-most numbers is a unit, then 2s, 4s, 8s, and so on. Each one is 2 times (double) the previous one.
So what has this to do with live Pythons? When you were typing lines of Python code to draw circles in PyGame at the start of this chapter, you were controlling Notes: the Raspberry Pi’s graphical display much like web servers are controlled by their masters. Each command is interpreted line by line, and the computer is waiting for you to tell it what to do. Interpreting Python Computers use instructions on the microprocessor to control them, and these are very fast but very complicated.
It is not good practice to put all your code for a block into one line like this. You can press Return after each instruction here and Python will show you “...” to indicate that it is expecting more instructions but remember to indent each line in the block with spaces. Notes: Tip... When you see ellipsis (…) it means that Python is expecting more instructions to follow your “while” instruction. Just press Return again to clear it. >>> a = 0 >>> while (a < 10000): ... a+=1 ...
Notes: Lesson 3.2: MasterPy We’ve had a warm up, so let’s see if we can create a game using Python. Have you ever played the Mastermind game, where you have to guess the hidden colours? We can do the same here, but with letters rather than coloured pegs. It will also give us the chance to work with some text in and text out commands. Here’s the code that we’re going to use: import string import random Tip... # create a list of 4 characters secret = [random.
This is a much longer program, which keeps asking for a new guess while the guess doesn’t match the secret. The first thing it does is to randomly select a sequence of four letters from a choice of six. It builds this list sequence, which is denoted by “[” and “]”, by looping four times and randomly choosing a letter from the options each time. The computer gets the user to guess by waiting for input from them. Until the user types in something and presses enter the program will stop.
The next bit of information that the player needs is how many letters were in their guess but not in the correct places. Since we don’t care about the position, we are just counting letters. For each possible letter, we count how many are in the secret and how many are in the guess. This will include those that are in the correct position too, but we’ll get rid of those counts in a minute. We also only want the minimum number since we are only counting those in the guess that are also in the secret.
Notes: Lesson 3.
The main part of the Roman Numerals program also introduces the idea of “exceptions”. When a function you write detects something wrong, you need to let the callers of your code know. You can do this by raising an error. if number < 1 or number > 4999: raise ValueError “ValueError” is raised by other parts of Python when you attempt an operation on a variable that cannot be done, so we’ve used it here. The program catches the exception and prints a message.
Notes: Sorting and searching Let’s try something a little more practical, such as manipulating data and using files. For this experiment, you need to use a text window in IDLE to create a list of film names. Type the film names as shown here into the editor and save it as “filmlist”.
Notes: # sort a file full of film names # define a function that will return the year a film was made # split the right side of the line at the first ”(” def filmYear(film): return film.rsplit('(',1)[1] # load the file into a list in Python memory # and then close the file because the content is now in memory with open("filmlist", "r") as file: filmlist = file.read().splitlines() # sort by name using library function filmlist.
Notes: Film search # sort a file full of film names # function to compare the lowercase item with the searchfor def compare(item): return searchfor in item.lower() # load the file into a list and # close the file because the content is now in memory with open("filmlist", "r") as film: filmlist = film.read().splitlines() searchfor = input("Enter part of the film \ name you are searching for: ").lower().
Notes: Lesson 3.4: Getting artistic Now we’ve learned to use functions, as well as manipulating data, let’s get back to something a bit more visual. This time we’re going to get on with displaying graphics, controlling widgets and using classes. # Include the system and graphical user interface modules import sys from PySide.QtGui import * class MyWindow(QWidget): def __init__(self): super(MyWindow,self).__init__() # name the widget self.
Up to this point, the data being processed has been printed to the screen; but it could have easily been printed on paper or written out to a file. We’ve been putting text directly onto the console output. If you want to draw onto a window you will need to use a graphical window library. In this section we are using the “PySide” library (a version of the “Qt4” library), although another – called “Tk” – comes included with every version of Python.
Notes: Line drawing # Include the system, maths and graphical user interface modules import sys, math from PySide.QtGui import * from PySide.QtCore import * class SketchWindow(QWidget): def __init__(self, title, draw, size): super(SketchWindow, self).__init__() self.setWindowTitle(title) width, height = size self.setGeometry(60, 60, width, height) self.windowSize = size self.draw = draw def paintEvent(self, event): qp = QPainter() qp.begin(self) pen = QPen(Qt.yellow, 4) qp.setPen(pen) self.draw(qp, self.
To draw a line, or a group of lines, first requires binding the paint event to a function. Hence, when the windowing system is ready to draw to the window it will call your function. Before going to the main loop, we need to set up a QWidget within the app. This experiment and the last introduced the concept of a “class”. Understanding a class is quite complicated but think of it as a block of data that also defines the functions that can manipulate that data.
Notes: Making a noise Graphics are all well and good, but if we are going to create true multimedia software then we’re going to need to master audio output as well. Let’s see if we can add some sounds to our programs. import numpy import wave import pygame # sample rate of a WAV file SAMPLERATE = 44100 # Hz def createSignal(frequency, duration): samples = int(duration*SAMPLERATE) period = SAMPLERATE / frequency # in sample points omega = numpy.pi * 2 / period xaxis = numpy.arange(samples, dtype=numpy.
That “action” is stored in a computer as numbers ranging from some large negative number to the same positive number, say 16,384 (214 – remember your binary!), for a particular duration of time, say 4 seconds. If we move up and down that range evenly, say, 440 times each second, and pass those numbers to the sound hardware in the Raspberry Pi, we should hear the musical note “A”, above middle C.
Notes: Lesson 3.5: Simulations and games Now we can handle graphics and sounds, as well as manipulating data and using functions and classes. We can put all of this together to create something really worth seeing - it’s time to write games! Let’s go skiing! For this experiment, you will need some little pictures (“sprites”), which will be moved around the display. You can use any “paint” software to create a picture of a skier, which is 20 pixels high and 20 pixels wide.
Notes: Create these two sprites using some paint software. Save them as “skier.png” and “block.png” (the tree). Games are essentially real-time simulations of a system of rules that have a starting condition that is modified over time due to external input. Other than the external influences, the simulation is entirely predictable and deterministic. Here is a simulation of ski slalom, where a skier makes his or her way through gaps in rows of trees.
def keyEvent(self, event): # event should be key event but we only move # if the key is pressed down and not released up self.keydir = (0 if event.type == pygame.KEYUP else -1 if event.key == pygame.K_LEFT else +1 if event.key == pygame.K_RIGHT else 0) # pygame library wants to do a few things before we can use it pygame.init() pygame.display.set_caption("Ski Slalom") pygame.key.set_repeat(100, 5) # create something to draw on with a size of 400 wide canvas = pygame.display.
Notes: Adding trees import random class worldTreeGroup(pygame.sprite.Group): speed = 5 def __init__(self, picture): pygame.sprite.Group.__init__(self) treePicture = picture treeRow = pygame.sprite.Group() # in rows with a gap somewhere in the middle # only have a line of trees every 5th row or the # game is too difficult for y in range(0, 400): if (y % 5 == 0): # every 5th, add tree row with a gap gapsize = 3 + random.randint(0,6) # size of gap # starting position of gap gapstart = random.
This world tree group does nothing yet because it has not been used by the main game. The next listing changes the main game to use the new class. skiWorld Make these changes to the class “skiWorld”, don’t add them to the end of your program. See if you understand how to extend the skiWorld so that it will create trees, update them, draw them and check if the skier collides with the group of trees. def __init__(self): self.running = True self.skier = worldSkier([190, 50], pygame.image.load("skier.
Notes: We now have our skier, our trees and our game.
Lesson 3.6: Limited resources – memory & storage import tempfile, heapq # this is a generator (notice the yield) def linesFromFile(sortedFile): while True: element = sortedFile.readline().strip() if not element: # no element, so file is empty break yield element # open the filmlist (this doesn't read anything yet) films = open('filmlist', 'r') generatorList = [] while True: # read up-to 10 lines into an array elementsToSort = [] for i in range(10): film = films.
The permanent storage on a computer (where all the data is kept when the machine is turned off) will usually be larger than the temporary storage (internal computer memory, which is lost when power goes off). On the Raspberry PI, your SD card (permanent storage) is likely to be much larger than the 256Mb of RAM (temporary storage). Look back at the previous experiment that loaded a text file, sorted the entries and then displayed the sorted list.
Lesson 3.7: Accessing the web – providing a weather forecast from urllib.request import urlopen from xml.dom import minidom import time # extract weather details by grabbing tags from the RSS feed # 'channel' contains all titles that contain weather heading text def ExtractWeather(doc): for node in doc.getElementsByTagName('channel'): for title in node.getElementsByTagName('title'): print(title.firstChild.data) results = [] bbc_weather = "http://open.live.bbc.co.
Notes: Threading – why wait for responses? import threading from urllib.request import urlopen from xml.dom import minidom import time # extract weather details by grabbing tags from the RSS feed # 'channel' contains all titles that contain weather heading text def ExtractWeather(doc): for node in doc.getElementsByTagName('channel'): for title in node.getElementsByTagName('title'): print(title.firstChild.data) class urlOpenThread(threading.Thread): def __init__(self, host): threading.Thread.
When accessing the web, you will not get an immediate response to your requests. When you ran the previous Python experiment you may have been lucky and had it take little time to get your weather reports. Computers can do many things very quickly and it is a shame to leave a computer waiting. This experiment shows how your computer can weave threads of instructions together so they appear to run at the same time.
This is only the beginning – where do we go from here? These experiments may have left you exhausted and slightly confused, but I hope that they have also whetted your appetite to learn more about computer programming, computer science and computing in general. This is only the beginning. This isn’t a reference manual or a tutorial but the Python language comes with a comprehensive reference guide.
Notes: XKCD #353 “Python” http://xkcd.
Human-computer interfacing Chapter 4 Hear the word “computer” and you probably think of a box with a monitor attached, like a desktop PC. But these days, almost every electronic device, from your TV or your parents’ satnav, right up to the auto-pilot in a jumbo jet, is controlled by a computer. Computers are everywhere. In order to do the job they’re programmed for, computers need to receive information from the real world telling them what to do; these are called “inputs”.
Other common ports include TCP port 25, which is used for the SMTP email protocol; ports 20 and 21, which are used for the file transfer protocol (FTP); and port 161, for the SNMP network management protocol. There are thousands of different ports available to use and hence thousands of different ways to communicate on the internet! In this chapter, we are going to use your Raspberry Pi to interface with a range of internet applications, including Twitter and email.
Notes: Lesson 4.1: Twitter To complete this exercise you will need to install the Python Twitter Tools. You can either download these from http://pypi.python.org/pypi/twitter/ or install them from the SD card that came with your Raspberry Pi. The following Python script will tweet the message “Hello, World!” from your Raspberry Pi. It then displays a list of all your personal tweets. No web browser in sight! This example shows how simple this type of application can be, using Python.
Notes: Lesson 4.2: Email application Email is transferred across the internet using something called SMTP – Simple Mail Transfer Protocol. SMTP uses port 25. Don’t worry; you don’t need to understand how SMTP works to be able to send an email. There is a Python module that does all the hard work for you. Use the Python script below to send a single email. email-example.py: import smtplib from email.mime.
Notes: email-attachment.py: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # create multipart email msg = MIMEMultipart() msg['Subject'] = 'Lily' msg['From'] = 'My RPi ' msg['To'] = 'you@yourdomain.com' msg.preamble = 'This is a multi-part message in MIME format.' # attach email text message = """This is a test of using Python on Raspberry Pi to send an email.
Notes: Lesson 4.3: Remote Procedure Call A Remote Procedure Call (RPC) is bit of code in one program that causes another program to do something, for instance run a subroutine (a bit of a program that performs a specific task). The two programs don’t necessarily have to be on the same computer, although often they are. When using RPC, calling a subroutine looks the same in your code as if it was being executed as part of your program.
Notes: rpc_client.py: import xmlrpc.client s = xmlrpc.client.ServerProxy('http://localhost:8000') # call the 'hello' function with no parameters print(s.hello()) # call the 'hello' function with a name print(s.hello('XMLRPC')) # add two numbers together print('2+3=%s' % s.add(2,3)) To run this example, you need two separate IDLE windows – one for the server and one for the client. You need to run the server first so that it is waiting for requests from the client. To stop the server, press Ctrl-C.
Notes: Lesson 4.4: Web applications A web application is a program that communicates on the World Wide Web. Like any other program, it has inputs, processes them and produces some output. Not every input and output from a web application has to be through a web browser, though! The World Wide Web uses something called HTTP (Hyper Text Transfer Protocol). This is what web servers and web browsers use to communicate with each other at a low level. The port number used for HTTP is 80.
Notes: Inputs The main input to a web application is in the form of a “page request” from a web browser. As part of this request, variables are passed from the web browser to the web server (in this case, your program). These variables might include things such as the specific page you want to see, login details, details about how you would like the site to look and so on. Normally, these variables exist only for the lifetime of one request.
Notes: hello-web.py: from webob import Request, Response class WebApp(object): def __call__(self, environ, start_response): # capture the request (input) req = Request(environ) # get the name variable, # default value of 'World' if it is not set name = req.params.
Notes: Cookies We have just seen an example using a simple form. You may have noticed a drawback – the “name” variable from that form only lasts for the lifetime of one request, then it is lost. If we want a variable to remain between requests, we have to use another type of variable called a “cookie”. The program below is a modified version of the program above that demonstrates how to use cookies. cookies.
When using this program, you will notice that the value of the cookie is remembered even if you close the web browser. How does it work? First, we display the current value of the cookie. If the “cookiechange” variable is set, the value of the cookie is changed and this is sent back to the web browser to store. The cookie has a maximum age though – we have used 30 days in this example. The cookie may be lost even sooner if it is deleted by the user in the web browser.
Notes: Lesson 4.5: General Purpose Input/Output (GPIO) GPIO is short for “General Purpose Input/Output”. Your keyboard, mouse and monitor are examples of input and output devices on a computer, but they are for specialised and well-defined tasks. The “General” part of GPIO indicates that you can design your own device and connect it up to the Raspberry Pi. This section explains the technicalities of how inputs and outputs are connected and processed by computers.
This gives us 4 (22) combinations that we can use. The first “2” is the number of states in a digital channel – on and off. The second “2” is the number of digital channels we are using. An analogue signal is one that can have a range of values, whereas a digital signal only has two. One way to think about digital versus analogue is comparing a flight of stairs with a ramp. When climbing the stairs you can be quite certain that you are on the seventh step, for example.
Notes: Serial and parallel data Serial In serial data signals, there are two information streams: transmit (Tx) and receive (Rx). Parallel In a parallel signal, many bits of data can be sent or received simultaneously. Digital data flows in and out of a computer in one of two ways – in serial or in parallel. On a parallel interface, there is one data channel for each bit of data that is input. Think of it as having lots of lanes on a motorway.
The second method is an example of “polling”. It tends to waste a lot of your time by frequently checking the phone when there is nobody there. It also takes time to swap from one task to the other. This is what you would have to do if the phone had no ringtone. Polling is the method that is used when events occur frequently and must be handled in a timely manner. The third method is an example of “multitasking”. The first person can concentrate on their work on the computer.
Don’t worry, though, if you had your heart set on creating some real-time applications. There is another small electronics prototyping platform, called an Arduino, which contains a programmable microcontroller suitable for real-time applications. It is quite easy to use a Raspberry Pi and an Arduino board together. An Arduino can be used for the high-speed, real-time parts of the design and a Raspberry Pi can run a higher-level GUI or web application that controls the Arduino.
Notes: GPIO board pins There are 17 pins available to operate in GPIO mode, configurable as either inputs or outputs. They carry just one bit of digital data. High = 3.3V Low = 0V Board pin BCM GPIO number Board pin BCM GPIO number 3* 0 16 23 5* 1 18 24 7 4 19 10 8 14 21 9 10 15 22 25 11 17 23 11 12 18 24 8 13 21 26 7 15 22 * Note that these pins have a 1.8k pull-up resistor on the Raspberry Pi board.
Notes: LED circuit Now we know all about data and the Raspberry Pi’s input/output options, let’s get on with building something! This is about the simplest circuit you can build to test the GPIO outputs of a Raspberry Pi. This circuit contains just two components: a 1k resistor and an LED (Light Emitting Diode). The resistor is used to limit the current that flows out of the Raspberry Pi and into the LED. If there is too much current, you could break something! LED circuit experiment wiring diagram. Tip..
Notes: Push-button circuit This is the about the simplest circuit you can use to test GPIO inputs with your Raspberry Pi. The 10k resistor is what is known as a “pull-up” resistor – that means that the input will be pulled high (to 3.3V) when the button is not pressed. When you press the button, it connects the input to 0V via the 1k resistor, sending the input low. The 1k resistor is present to protect your Raspberry Pi in case you accidentally set it up as an output instead of an input.
# start thread running self.start() Notes: def pressed(self): if self._pressed: # clear the pressed flag now we have detected it self._pressed = False return True else: return False def run(self): previous = None while 1: # read gpio channel current = GPIO.input(self.channel) time.sleep(0.01) # wait 10 ms # detect change from 1 to 0 (a button press) if current == False and previous == True: self._pressed = True # wait for flag to be cleared while self._pressed: time.sleep(0.
Notes: Arduino interface To complete this exercise you will need the Python Serial Port Extension. You can either install this from the Raspberry Pi SD card or download them from http://pypi.python.org/pypi/pyserial/. You will also need the Debian package called “arduino”, in order to install the Arduino development IDE. You can download this from the Debian website. Obviously, you will also need an Arduino board.
Notes: Code for the Arduino: // set up the serial connection speed void setup() { Serial.begin(9600); } void loop() { int inByte; if (Serial.available() > 0) { // read data from the Raspberry Pi inByte = Serial.read(); } } // send data to the Raspberry Pi Serial.write(inByte); Serial.print(" = "); Serial.println(inByte); Python code for the Raspberry Pi: import serial # set up the serial connection speed ser = serial.
The Linux Command Line Chapter 6 The operating system on your Raspberry Pi is a version of Linux. In all probability, it looks a bit like Windows, or – more likely – like the Mac OS. It has a graphical user interface (GUI) that allows you to interact with your folders and files by double-clicking, right- or left-clicking, or dragging and dropping. If you want to open a program, you look for it on a menu called something like “Applications”.
Notes: Lesson 6.1: Commands are just programs When you type into the terminal you are running programs. Most of the commands listed here run programs that give you the ability to command the system to do something. When you add programs to your Raspberry Pi, you will be able to run more commands. If you enter a command and it doesn’t work, it may well mean that the program isn’t installed yet.
Or, you could use the “info” command: $ info info Displays online documentation about the target. In the examples above, substitute with the command you want to find out more about. A word of warning: the guidance given by “man” is sometimes a bit formal and very, very detailed. You could almost say, “If you think you know a command then go to the command’s man page in order to find out that you don’t really.” To find out more about Bash, take a look at its Wikipedia entry: http://en.
Notes: Lesson 6.2: Command syntax and file structure Commands take the form: | | | In guides, such as this one, the brackets “<” and “>” are often used to indicate the place a command would take in a string of text being typed into the CLI. The horizontal line “|” is used to denote “or”. Confused? Okay, let’s look at the example above.
Notes: Navigating the file system using “cd” The file system in Linux is hierarchical with nested directories (often called “folders”) in a “tree”. The top of the directory structure is denoted by the symbol “/”, and directories underneath “/” are referred to using “paths”, just like URLs in a web browser. To go to a particular place in the directory structure, you use the command “cd”, which stands for “change directory”, followed by its location in the tree.
Listing the files and folders in a particular place The “ls” command lists all contents of directory you’re working in. There are a range of switches you can use with “ls” to make it display exactly the files you’re interested in and all the useful information about those files. We’ve listed a few of those switches here: l “ls”, the command with no switches, lists all the file in the current directory. l “ls -l” lists the files and displays the long version of the information about each file or directory.
Notes: Change ownership of directories and files In the long List above, the files are owned by Brian and are also in the Brian group. What if we wanted to change the ownership of some of those files? Then we would use the “chown” command. We’ll use the file “brotplot.odt” as an example. Let’s say we want to make Fred the file’s owner. We would use the command: $ chown fred brotplot.odt If we run the command “ls -l” again, we will now see the result: -rw-rw-r--. 1 fred brian 10919 Apr 2 19:52 brotplot.
Notes: Change access to directories and files When you use the “-l” switch to see the long list of information a directory’s contents, the results you see are all preceded by a string of letters and dashes. For instance: -rw-rw-r--. 1 fred students 10919 Apr 2 19:52 brotplot.odt The first character in the sequence, in this case a dash, tells us what the object is.
Now, let’s try out the “chmod” command: chmod o+w brotplot.odt This means add write access for the “other” group to “brotplot.odt”. Add is indicated by the “plus” sign. chmod a-r brotplot.odt This means remove read access for the all three (user, group and other) from “brotplot.odt”. Remove is indicated by the “minus” sign. chmod u+x brotplot.odt This means add execute access for the user/owner to “brotplot.odt”. To find out more about the “chmod” command see its Wikipedia entry: http://en.wikipedia.
Notes: Lesson 6.3: The superuser The “sudo” command introduces the “superuser” or “root user”. The term “root” is the name for the main administrator in a “Unix-like” system, such as Linux. There are many commands that only the root user can run. Depending on the version of Linux you are using, you will either have to log on as the root user or prefix your command with “sudo”. The default Debian distribution of Linux, for instance, has no root password set. So you will have to use the “sudo” command.
You will be asked to enter and then confirm a new root password. Assuming you can manage to enter the same password twice, you now have a root user and you Notes: can issue the command: su When you enter passwords in Unix-like systems, the prompt remains blank: no blobs or asterisks stand in for the characters in your password. Don’t be put off; the password is being entered nevertheless.
Lesson 6.4: Creating and destroying files and directories Finally, let’s look at creating and destroying file and directories, as well as taking a closer look at the mount command. Create a new empty file To create a new empty file, go to where you want the file to be and type: $ touch The “touch” command actually updates a file’s “last accessed” time to the current time and date, but if such a file doesn’t already exist then it will create a new file of that name, with a file size of 0.
Notes: Remove a directory To delete a directory, go its location and type: $ rm -r -f This uses the “rm” command we used above, but the extra switches tell it to remove the directory, all its contents and also any sub-directories and their contents. The “-r” means “recursive”, which – in the case of a directory – removes the entire directory and all its contents, including sub-directories.
You must also make sure that you use the necessary switches, parameters and directories. For instance, from the previous exercise: mount -F smbfs //workgroup;fred:foo@192.168.1.99/homes /mnt/net This, as we learned earlier, tells the system to mount the shared drive called “homes” on the Windows server at 192.168.1.99 , in the directory tree at the point “/mnt/net”, using the Server Message Block Filing System (the -F switch). To find out more about the “mount” command, see its Wikipedia entry: http://en.
Notes: Lesson 6.5: Remote access to the Raspberry Pi OpenSSH is an application that allows you to securely access Linux systems remotely over the network. You can use OpenSSH simply for secure file sharing. But it also allows you to log on to a system and control it over the network, even using the GUI, just as if you were sat in front of it. The default installation of Linux on your Raspberry Pi should have “SSH daemon” running.
Notes: Running a remote GUI To remotely connect to your Raspberry Pi and use its GUI you will need to install an “X server” on your machine. Linux has an X server built in. For Windows, try Xming (http://www.straightrunning.com/XmingNotes) or Cygwin (http://www.cygwin.com) – you can download both for free. For the Mac OS, go to “Shell > New Remote Connection” and choose “Secure Shell (ssh)”. The following command uses the X switch to tell SSH to send the X commands to the X server on your host.
Notes: Open a remote browser Let’s see what happens when I try to run a web browser remotely. The web browser on the Raspberry Pi is called Midori, so this is what we need to enter from the prompt after we connect remotely: brian@raspberrypi:~$ midori & [1] 5773 We need to include the “&” symbol after the program name because this tells the server to launch it as a separate process, which means we get our command line back.
What next? Chapter 7 If you have worked through this manual you will have a good understanding of the basics of computer science and you will be able to write a computer program to solve simple problems. This bears repeating: you can write a set of instructions to make a computer do something. This simple statement embraces a set of powerful thinking skills that include logical reasoning, problem solving, algorithm design and much more.
It concentrates on programming because the Raspberry Pi was made to encourage a new generation of programmers. While there is much more to computing than programming, it is a very good place to start. General resources and help The first place to look is the official Raspberry Pi website and forum (http://raspberrypi.org). There is a lot going on in the forums and there are subforums for specific topics such as GPIO, programming, operating systems and education.
Notes: Raspberry Pi-specific resources Liam Fraser has made a series of Raspberry Pi-specific YouTube tutorials, which you can find at http://goo.gl/MM9hA The Magpi, the free Raspberry Pi Users’ magazine (http://themagpi.com) has some excellent beginners’ articles and tutorials. Python online tutorials, resources and references The official Python site keeps a huge list of quality resources both for beginners (http://goo.gl/MMo5G). It should keep you busy for some time.
Notes: Online practice and tutorials More informal ways of learning to program online include Codingbat (http://codingbat.com) and Codecademy (http://codecademy.com). Codingbat is a series of programming challenges that help build strengths in specific areas, such as string handling and logic. Teachers can track student progress, and tools include a useful graph that logs incorrect and partially correct attempts at a solution (this makes it hard to cheat!). It has exercises for Java and Python.