User:Inferno986return/sandbox

=Wikijunior:Raspberry Pi= Formerly Learn Electronics with the Raspberry Pi

These are Raspberry Pi tutorials courtesy of Cotswold Jam, a Raspberry Jam meetup group based in Gloucestershire, England. Despite these tutorials being many years old they should still work on the latest Raspberry Pi models. Some of these tutorials are software-based and should work on any GNU/Linux distro such as Ubuntu. Perhaps they could be adapted to other single-board computers or even microcontrollers such as the Arduino?

The goal of this Wikibook is to archive, transcribe and improve upon all of the Cotswold Jam tutorials. There is a wealth of content on the downloads section of their website. Though some tutorials may need clarification of their licencing before being added to this Wikibook.

To make this one continous work, this Wikibook needs to minimise repeating itself across multiple chapters and dependence on exernal sources. Also the tutorials should be arranged in an order of difficulty.

Wishlist

 * step-by-step screenshots for the Minecraft tutorials

How to contribute
Find tutorials from the downloads section of the website. Use Evince (or Adobe Acrobat Pro if you have a subscription to that) to save the images from the PDF files. Most content should be public domain, though it may need clarification. Fritzing diagrams are always CC-BY-SA.

Outline
A rough outline of this book:


 * What is a Raspberry Pi?
 * A brief introduction to electronics
 * Projects that require a Raspberry Pi
 * Projects that don't need a Raspberry Pi
 * What if I don't have a Raspberry Pi?
 * Setting up Windows Subsystem for Linux (WSL)
 * Setting up Virtualbox

About this book

 * I've adapted this from Wikijunior The Elements

The target age of this title is 8–12 years old. Section titles are the Raspberry Pi tutorials. There will be an introduction explaining what a Raspberry Pi is, what the relevant electronic components are and how the Python programming language works.

When working on this project, remember that it is aimed at children. Being understood is just as important as being accurate. Authors should concentrate on the most important concepts rather than getting wrapped up in every detail. Use technical vocabulary when you need to, but don't use big words where simpler language would work. Or in other words, write as you would when you were a child.

If you have made contributions to this Wikibook and would like to have formal credit for being an author, please add your name to the list of authors.

=What is a Raspberry Pi?=

A Raspberry Pi is an inexpensive single-board computer designed for educating children about computing. The first models were the Raspberry Pi Model A and Model B which were released in 2012...

=A brief introduction to electronics=

Electricity is energy
Electricity is one form of energy and most energy originates from the sun.

The law of conservation of energy states that that energy can neither be created nor destroyed; rather, it can only be transformed or transferred from one form to another. Such as:


 * sunlight to electricity – solar panels
 * sunlight to heat energy – solar furnace
 * chemical energy to electricity – batteries

Conductors and insulators
Conductors are materials that capable of conducting electricity because they allow the flow of electrons.

Insulators

Semi-conductors

Current, Voltage, Resistence and Power
There are 4 main units for measuring electricity. Each of them are named after a scientist who made significant discoveries related to it.

Ohm's law


Ohm's law states that the current (measured in Amps) is proportional to the voltage (measured in Volts). From there it is possible to calculate the Resistance (measured in Ohms).


 * Voltage = Current × Resistance
 * Current = Voltage ÷ Resistance
 * Resistance = Voltage ÷ Current

Finding the current, voltage or resistance is easy. Just cover which of the three you are looking for with your hand!

SI prefixes
Many of the units we use are defined and standardised by the Systems International (SI) institution in France including the Amp, the Volt and the Ohm.

The SI prefixes should be familiar as we use them every day for units such as the metre (m) and the gram (g). This prevents us from writing out a lot of zeros. Each prefix multiplies the unit (the capital letter prefixes) or divides the unit (the lowercase prefixes).

The Greek letter mu (μ) is used for micro. You may be familiar with a kilogram (1000 grams) or centimetre (0.01 metres).

Electronic components
Most of these components can be purchased inexpensively from hobbyist stores or electronic component wholesalers such as RS Components and Farnell.

Breadboard


A breadboard is used to build and test electronic circuits without having to solder the components in place. They are reusable, and the components are also reusable after being used on a breadboard.

All the vertical lines (usually lettered A–E and F–J) are connected in columns. So electricity going into point 1A also arrives at 1B, 1C, 1D and 1E. But there are no connections across rows – so electricity going into point 1A does not arrive at 2A, 3A and so on.

Some breadboards also have extra rows at the top or bottom which are connected vertically, used for positive and negative. We are not using that type of breadboard, and if you are using one then ignore the rows at the top and bottom of your board. Sometimes, these rows are marked with plus + and minus − or are coloured red and blue.

Capacitor
A capacitor stores a small amount of electric charge, then when it is full it lets all the charge go.


 * If you connect it to a strong charge, it lets the charge go faster.
 * If you connect it to a weak charge, it takes longer to let the charge go.

The capacitor has a short and a long leg, and a stripe on one side. Like LEDs, they must be connected with the short leg and stripe to negative (ground).

DuPont jumper wire
A DuPont jumper wire is used to connect components to a breadboard and is compatible with the Raspberry Pi's GPIO pins.

Light-emitting diode (LED)


A light-emitting diode (LED) emits light and is programmable meaning you can control them using software such as the GPIO on a Raspberry Pi. They also have other benefits:


 * they are much more energy efficient
 * they don't need to heat up first to produce light and most LEDs produce only a very small amount of heat
 * they are individually smaller than other lightbulbs
 * they are available in a wide variety of colours

Lower value (lower Ohm) resistors will allow more current through and will make the LED brighter; higher values will let less current through and make it dimmer.

Switch
A switch completes the circuit by allowing electricity to flow while it's pressed down. When released, the electricity stops. There are three types of switch:


 * A momentary switch requires something to continually press it down.
 * A toggle switch is held down once pressed and requires something to unpress it.
 * A reed switch is a glass tube with two bits of metal separated by a tiny gap. When there is a magnet nearby, the two bits of metal touch and allow electricity through. Be very gentle and careful with reed switches because the glass can break easily.

Photocell
A photocell or photoresistor, is a type of variable resistor which provides a different amount of resistence depending on how much light it detects. They let through more current when there is more light.

Piezo buzzer
A piezo buzzer makes a beep when electricity goes through it. It has two "leg" connectors; one long and one short. The long leg must be connected to positive, and the short leg must be connected to ground (negative).

Resistor


A resistor is a simple coil of wire that reduces the current in a circuit, for this reason, it can wired to a circuit any way around without breaking. Resistance itself is measured in Ohms (using the Greek letter Omega Ω) and the coloured stripes on each resistor indicate how much resistance each resistor is capable of adding to a circuit.

You may recognise the symbol for a resistor used in circuit diagrams:


 * The American symbol for a resistor is a zig-zag shape representing a coil of wire.
 * The IEC symbol for a resistor is just a rectangular box, often the resistance is written inside of it. IEC symbols are a British Standard which is used throughout the United Kingdom.

Resistor colour bands
The colour bands on each resistor show exactly how much resistance it can provide. This includes tolerance which is good to know in case there is an unexpected change in the current.




 * 1st Band – the first significant figure of component value (left side).
 * 2nd Band – the second significant figure (some precision resistors have a third significant figure, and thus five bands).
 * Multiplier – the number of trailing zeroes, or power of 10 multipliers.
 * Tolerance – if present, indicates the value in percent (no band means 20%).

The example resistor above has red, violet, green and gold colour band rings. Let's find out how much resistance it can provide:


 * 1st Band – Red = 2
 * 2nd Band – Violet = 7
 * Multiplier – Green = ×100000 (×105)
 * Tolerance – Gold = ±5%

By referring to the table below we can see that the amount of resistance provided by this resistor is 2700000 Ohms or 2.7 MegaOhms (MΩ) with a tolerance of ±5%.

This resistor colour code table has been simplified from the Electronic colour code article on Wikipedia.

Web links
How Semiconductors work. This tutorial includes Diodes, LEDs and Transistors, gets Techy.
 * 1) http://engineering.nyu.edu/gk12/amps-cbri/pdf/Basic%20Electronics.pdf

Distance Learning – Tutorials
 * 1) http://www.instructables.com/id/Basic-Electronics/
 * 2) http://www.electronics-tutorials.ws/
 * 3) http://www.electronics-tutorials.com/index.htm

Wikibooks has its own book on Electronics which goes into a lot more detail than this book does.

=Raspberry Pi Python GPIO Zero Simple LED Tutorial= Tutorial by Andrew Oakley Public Domain 24 Sept 2016 www.cotswoldjam.org

The electronics
You should also have two short and one long jumper wire (all "female to female" – holes at both ends).

Connect one short wire to GPIO 4. This is the 4th pin from the left of the bottom row.

Place the resistor in the end of the short wire.

Connect another short wire to the resistor.

Connect the end of this short wire to the long leg of the LED. This is the positive connection.

Next, connect the long jumper wire to ground (negative, GND). There are several ground pins on the Raspberry Pi, for example the 5th pin from the left the bottom row.

The program
Power up your Raspberry Pi. From the desktop menu, select Programming - Python 3 (IDLE). Then use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the led.py program in the python/led folder.

Use File, Save to save this program as led.py and the run it by selecting Run menu, Run Module.You should see the LED light up for one second, and then turn off.

Not working? Check you’ve got:


 * The correct GPIO pins
 * The LED is the correct way round; short leg to ground (GND)
 * No spelling mistakes, no missing brackets, and you’ve used round brackets instead of pointy, curly or square ones.

What is this program doing?
The first two lines tell the computer to learn about a new thing. Computers can learn from programs that other people have written, and we call these other programs "libraries". Our instructions tell the computer to learn about LEDs from the GPIOZero library, and learn about sleeping from the time library.

We then create an LED object. We say that the LED is connected to GPIO 4.

Turn the LED on, wait for 2 seconds, then turn it off.

See if you can flash SOS in Morse code. Have a look at the  program and learn about the   command.

Files
led2.py

=Screaming Jelly Babies Tutorial=

In this tutorial, you will be making a jelly baby scream! Alternatively, you could use a gummy bear if you are based outside of the UK or Australia.

Your tutor should have prepared your Raspberry Pi’s SD card for you. If not, please read the last section “For Tutors”.

Conventions
At the end of each line, you will usually need to press the Enter key.

Log in and start IDLE
When you turn on your Raspberry Pi, after a few moments it will ask you to log in. You will need to type the username followed by the Enter key, then the password, followed by the Enter key.

Note that the password won’t appear on the screen when you type it.

From now on, you should assume that you always need to press the Enter key at the end of every line.

Once you have logged in, the screen will go black for a few moments, then the desktop should display and you should be able to move the pointer with your mouse. If not, enter:

Find the "IDLE" icon and double-click on it. If you find it difficult to double-click, you can right-click it and select "Open" instead.

You want IDLE and not IDLE3.

IDLE is a program for writing programs, using the Python version 2 programming language. The more advanced you become with Python, the more useful features you’ll use. However, it is possible to write programs without IDLE, using a text editor such as nano. There are other versions of this tutorial which use nano instead of IDLE.

IDLE3 is for version 3 of Python. This tutorial is written for version 2.

Your first program – Hello World
Type in the following program:

Save it using the File menu, Save, and then double-click into the python folder and then the jellybaby folder. Save the program as:

On the desktop, double-click the LX Terminal icon. A new black window will appear.

Switch into the python/jellybaby folder by entering:

Have a look at what files are in this folder by entering:

You should see your  program, some .wav sound files (those are the scream sounds we’ll use later) and an examples directory (if you want to cheat, you’ll find a fully working version of the screaming jelly baby program already there!).

Now run your program:

The computer should respond:

Let’s have a quick look at what we did there:

means “superuser do”. For many programs this doesn’t matter, but in a minute we are going to use electronics attached to the Raspberry Pi’s GPIO ports (General Purpose Input and Output), and you need to be the superuser to do that. On the downside, running a program as a superuser allows you to do things which can break the computer – the superuser is like a superhero who can do anything. Since the Raspberry Pi is a very cheap computer, that doesn’t matter too much, but on other expensive computers you might want to be more careful with.

tells the computer to run a program written in the python programming language. is the name of your program.

Wires
You should always turn off your Raspberry Pi before attaching wires to it. Make sure you tell the Raspberry Pi to shut down safely before you unplug the power. You can either use the red power icon in the bottom-right corner of the desktop, or in the LXTerminal window (the black window) type:

is the superuser-do command again. shutdown means to turn itself off. means halt (as opposed to  which means restart) and   means, well, right now! (if there were other people using your Pi over the network, you could say  instead of now, to give five minutes’ warning).

Wait for the Raspberry Pi to turn itself off, then unplug the power cable.

Unwind a metal paper clip so that it is a long straight-ish wire.

Take a female-to-female jumper cable and push the unwound paper clip in one end.

Do this twice, so you have two wires, both with an unwound paper clip in the end.

Larger paperclips may be difficult to fit. Your tutor may have already put them in for you, or you might ask your tutor for some pliers to help push them in.

Now attach the other ends of the jumper cables to pin 3 and pin 25 of the Raspberry PI's GPIO pins.

The pins are in two rows. Even numbers are on the edge of the board and odd numbers are on the other row. You will need to count in 2s starting from 1 on the left, so the count goes 1, 3, 5, 7 and so on.

It’s easy to make a mistake identifying pin 25, especially on the "Plus" models of Raspberry Pi which have 40 pins! It’s a lot less hard on the old Model B and Model A which only have 26 pins – pin 25 is the one at the end on the right.

The GPIO Program – Version 1
Put the power lead back in, wait for the Raspberry Pi to turn on, then log in ( /  ; don’t forget startx if your desktop doesn’t start automatically).

Start IDLE from the desktop (double-click), the load your old program by going to File menu, Recent Files and selecting.

Change the program so that it reads:

All the capitals really matter. You need to make sure that everything in capitals really is in capitals, and everything in lowercase really is in lowercase. This is called being case-sensitive.

The spaces under the  and   lines are also important. You need to press the spacebar to make sure they line up. These indentations are called blocks. Blocks of code can be repeated, or the program can decide to run or miss out a block. We're using four spaces to indent each block; some programmers prefer two or another number.

The  lines allow us to use other people’s little programs inside our program. These little programs are called libraries. The time library lets us tell the computer to wait. The  library lets us use the GPIO pins. The  library lets us call other programs, such as the music player, but we’re not using that just yet.

tells us to repeat a block of code. True tells the computer to always do something.

asks a question. The question being asked is whether the two wires are touching; is pin 3 connected to the electrical ground? Connecting an input pin to ground results in the value. Note the use of two equals signs. One equals sign is used to set a value, such as  means that every time the computer sees a it will know it has the value. Two equals signs are used to compare one thing with another.

means to wait for 1 second.

Save the program, then run it by starting LXTerminal from the desktop (double-click) then enter:

The program will print Hello World! and then it will wait.

Touch the paperclip wires together. You should see it say:

Release the wires, wait few seconds and then touch the wires together again. It should say  each time.

If it doesn’t work, check your program has been typed in right, check you saved it, and check that your wires aren’t covered in anything that might be stopping the electricity.

When you’ve had enough, hold down the CTRL key and press C to stop the program. This is called a "break" or a "keyboard interrupt" – you're asking the computer to take a break, and you’re interrupting the program using the keyboard. Sometimes you might see Ctrl and C written as CTRL-C or even ^C. You don’t need to use the shift key – the C is actually a lower case c.

The GPIO Program – Version 2
Let’s change the program so that it makes a sound instead of just printing “Ouch!” on the screen. Change:

…to:

Make sure the speakers are plugged in, turned on and have the volume at least half way (some speakers do not have on/off buttons or volume).

Go to the LXTerminal window and run the program again.

Touch the wires together and you should hear a scream!

Wire up the Jelly Baby
Get a jelly baby and push the wires into it.

You need to make them cross over inside the jelly baby, but not quite touch.

Now, when you press down hard on the jelly baby, it will scream!

You might have to press quite hard – hard enough to push through the sticky middle of the jelly baby.

Pressing down hard means that the jelly baby will probably be useless after three or four presses. If you’re not diabetic or allergic to jelly babies, you could eat the jelly babies after they’re squished!

Further fun
Your program plays a scream for the musical note C. There are also scream sound files for the notes D and E. Try changing your program to use a different note. See if you and your classmates can play a tune such as Mary Had A Little Lamb (EDCDEEE,DDD,EEE,EDCDEEE,EDDEDC).

Find a list of GPIO pins (http://raspi.tv/download/RPi.GPIO-Cheat-Sheet.pdf). Can you connect more wires and have one Raspberry Pi wired up to two or three jelly babies at the same time, playing different notes?

Equipment – for each workstation

 * ×1 Raspberry Pi, any model, with monitor, mouse and keyboard
 * ×1 SD or Micro SD card with up-to-date Raspbian operating system
 * ×1 speaker or pair of speakers, powered (rechargeable mobile MP3 speakers are fine, as are proper PC speakers)
 * ×2 Female to Female jumper wires – recommended minimum length 20 cm (about 8 inches)
 * ×2 small metal paper clips (not plastic coated) (if you use large clips, you may need to use pliers to push them into the jumper wires)

Several jelly babies – allow at least 6 per workstation, although probably best to only hand them out one or two at a time!

Knowledge of which of your pupils are diabetic or allergic to jelly babies.

Prerequisites
Download and unzip the folder structure, scream sound samples and example program. To do this, from an internet-connected Raspberry Pi, log in ( /   ) and do:

This will create:

Resources
jellybaby.py

Note that there is an excellent diagram of GPIO pins available at: http://raspi.tv/download/RPi.GPIO-Cheat-Sheet.pdf

Written by Andrew Oakley of Cotswold Raspberry Jam www.cotswoldjam.org CC-BY-SA

Latest version always at: http://www.cotswoldjam.org/tutorials/

Based on “Make a Jelly Baby Scream!” by the Raspberry Pi Foundation, CC-BY-SA http://www.raspberrypi.org/learning/screaming-jellybaby/ https://creativecommons.org/licenses/by-sa/4.0/

=Raspberry Pi LED Birthday Candle= Tutorial by Andrew Oakley Public Domain 17 Apr 2015 www.cotswoldjam.org

Introduction
This tutorial shows you how to build a birthday candle based around an LED (light) and a photocell (light detector) using a Raspberry Pi computer.

You'll be able to "blow out" the LED - and it'll turn off and play a tune!

At the end of each line, you will usually have to press the Enter key.

Your tutor should have prepared your Raspberry Pi for you. If not, see the section “Preparation” at the end.

The circuit
Build up the circuit as follows. Place the components first, and the jumper wires last. Don't worry about the paperclips just yet.



Leg trimming
When components come out of the factory, they have long legs (wires). Your tutor may have already trimmed the legs of your components, in which case you do not need to do it again. If your components have long legs, then before you cut them, you should try out your circuit by connecting it to the Raspberry Pi and running the programs.

If and when you need to trim the legs, you can use kitchen scissors or a special wire snipping tool. Either way, be careful when cutting the legs of components:


 * Don't trim the legs so short that they don't stick into the breadboard holes.


 * For LEDs and capacitors, remember you can use the LED rim or capacitor stripe to tell positive from negative, even if you trim both legs the same length.

Connecting the Raspberry Pi
Connect the jumper wires as per the diagram. The pins on the Raspberry Pi's GPIO port are numbered as follows. On older models there will only be 26 pins, but they still start from 1 and 2 on the left side. The top row has evens, the bottom row has odd numbers.



The test programs
Power up your Raspberry Pi, log in and go to the desktop. If you need to log in, the default username is  and the password is. If the desktop still does not appear, type  and press the Enter key.

From the menu, select Programming - Python 2 (not Python 3). Then use File, New Window to create a new program. Click File, Save As and go into the python/candle folder by double-clicking python and then double-clicking candle. Save as:

Lighting up the LED
Let's start by lighting up the LED. Type in the following program, or load it from mycandle1.py in the examples folder:

Save the program using File - Save. Now leave the Python window open, and start a terminal session by going to the main desktop Menu - Accessories - Terminal. You should see a black window open.

In the terminal, type:

You should see the LED light up for two seconds, and then the program will end. You can repeat the program by entering  again.

Let's have a quick look at what this program is doing.

The  command tells the computer to use bits of another program that have been written by someone else. These other programs are called libraries. We call in two libraries;  which lets us use the GPIO pins, and   which includes the   command which we use to wait for two seconds.

If the program gets stuck, hold down the CTRL key and press C. Then check your wiring and the spelling in your program.

If the program works, it will light the LED for a second, then start counting. It then says what the count was. A small count means light, a big count means dark.

Try running the program with your finger blocking the photocell. Try using bits of black card to put the photocell into shadow. If you're trying this in a well-lit room, the room lights might be more powerful than the LED – later we will make a blackout hood using paperclips and card.

In the program, you can see that we briefly (for 0.1 seconds) set  to an output and set the voltage low, just to clear any voltage on the connection, before we set it to an input with.

We then start counting. We have a new variable,, which we set to zero.

The program then loops around until it detects high voltage from the capacitor, adding one to the  count every time. When it detects high voltage, it ends the loop and prints out the value of the.

Hoods and flaps – detecting breath
We are going to use a little flap of card to detect breath. We're going to make a U-shaped hoop out of a paperclip, then hang a bit of card from it.

We'll place that hoop and card between the LED and the photocell, and make sure it can get blown out of the way when we blow on it.

We'll also put a hood over the photocell so that the only light it can see, will be from the LED. We'll use another two larger paperclip U-hoops to hold the card in place. Paperclips are quite handy with electronics breadboards as they fit firmly in the holes!

Have a good look at the following photo, and create your own hood and flap.

Your tutor may have already bent and cut your paperclips to size. If not, be careful of flying metal when you snip your paperclips to the right length.

The flap is made from:


 * A piece of black card approx. 2cm × 1cm
 * A paperclip hoop approx. 1.5cm tall and 1.5cm wide
 * Bend one end of the card gently (bend don't fold) over the hoop and use a very small amount of sticky tape to hold it loosely. Remember it has to be loose and delicate enough to swing when you blow it. It you tape it down too tight, it won't swing and it won't work.



The hood is made from:


 * A piece of black card approx. 4.5cm × 2cm
 * Two paperclip hoops approx. 2.5cm tall × 1.5cm across
 * Just gently bend the card and hold it in place with the hoops

The final program
The final program is based on the second test program:


 * It sets up the GPIO pins and lights the LED.
 * It does some "calibration" – it works out what the reading for "dark" is, when the flap is closed.
 * It loops around waiting for a new reading which is significantly lower than the calibration reading. This lower reading should mean there is much more light on the photocell – and that therefore the flap has been blown out of the way!
 * There is a variable  which controls how much lower the reading has to be for the program to detect the flap has been blown. By default it is set to 50% but you can change this. Remember you can use CTRL to stop your program if it gets stuck.
 * When the program detects light, it plays the tune "Good Morning To All" from 1893. This tune is out of copyright, but you may decide to sing along with some birthday-related lyrics at your own risk. This program is rather long to type in, so you can load it as  from the   folder if you prefer.

As before, run the program by switching to the terminal window and entering  or   depending on how you named it.

The program will run in a loop. To stop it, hold down the CTRL key and press C.

Preparation
If your tutor has not prepared your Raspberry Pi and equipment, or if you don't have a tutor, you can set things up by following these instructions before you start.

Equipment
You will need:


 * A Raspberry Pi running the Raspbian operating system. This tutorial suits all models to date, which includes the A, A+, B, B+ and 2B.
 * A solderless breadboard – we’re using a mini 170-point one, but any solderless breadboard will do.
 * An LED. We’re using a 5mm yellow one. It needs to be bright enough to trigger the photocell, so yellow, green or white will usually work better than red or blue.
 * A photocell, also known as a photoresistor. We’re using a 4mm 2–20k ohm one.
 * Four female-to-female jumper wires, at least 20cm long each.
 * Two short male-to-male jumper wires, about 2–6cm each. We’re using solid wire.
 * Three paperclips, cut into U-shapes.
 * Two small bits of black card; one about 4.5 × 2cm, and one about 2 × 1cm

Files
Please use an up-to-date installation of Raspbian. This tutorial was written in April 2015 and, at the time, the most recent recommended Raspbian image was dated 2015-02-16. You can create the folder structure and download the files by going to the terminal (Menu - Accessories - Terminal) and typing:

…where  is a minus sign followed by a capital letter O (not the numeral zero).

mycandle1.py

mycandle2.py

=Raspberry Pi LEGO® Traffic Lights= Tutorial by Andrew Oakley Public Domain 26 Sept 2015 www.cotswoldjam.org

LEGO® is a trademark of the LEGO Group of companies which does not sponsor, authorize or endorse this tutorial nor Cotswold Raspberry Jam.

Introduction
This tutorial shows you how to build a set of traffic lights based around LEDs (lights) and a Raspberry Pi computer. The lights can be placed inside a LEGO® Technic brick and used with other LEGO® models.

Conventions
At the end of each line, you will usually have to press the Enter key.

Your tutor should have prepared your Raspberry Pi for you. If not, see the section "Preparation" at the end.

Components
These three LEGO® bricks can be made into a traffic light, and the 5mm LEDs fit inside the holes of the Technic brick.



The part numbers for these bricks – which can be purchased second-hand on sites such as eBay or Bricklink.com – are:


 * 3701 – Technic, Brick, 1×4 with holes, black
 * 3460 – Plate, 1×8, grey
 * 3022 – Plate, 2×2, grey

Push the LEDs into the Technic brick so that the short legs of each LED are at the bottom.

You will need to connect the short legs to a single resistor and then to one of the Raspberry Pi’s ground pins. Your tutor may have made up a special "pigtail" cable to do this, or you may use a breadboard.

Ground (negative) wires
Pigtail cable Your tutor may have made up this cable using a DuPont crimper





It has three female ends on one side, which plug into the short legs of the LEDs, a resistor in the middle, and a single female end on the other side which plugs into pin 9 (ground) of the Raspberry Pi. A short bit of clear sticky tape wraps around the resistor to hold it in place.

Breadboard

Signal (positive) wires
Once you’ve got the resistor and ground connected to the LEDs’ short legs, you can test any LED by using a female-to-female jumper wire to connect the long leg to pin 1 (live 3.3 Volts) on the Raspberry Pi (assuming the Raspberry Pi is powered on).

However, we don’t want the lights on all the time; we need them to be controlled by a program. Disconnect pin 1 once you’re finished testing the lights.

To control the LEDs from our program, use female-to-female jumper wires to connect the long (positive) legs of the LEDs to the following pins on the Raspberry Pi:


 * Pin 11 — Red
 * Pin 13 — Yellow
 * Pin 15 — Green

The program
Power up your Raspberry Pi, log in and go to the desktop. If you need to log in, the default username is  and the password is. If the desktop still does not appear, type  and press the Enter key.

From the menu, select Programming - Python 3. Then use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the traffic1.py program in the python/traffic folder.

Use File, Save to save this program as. Here's what this program is doing:

This command teaches the Raspberry Pi about its GPIO pins, so it can turn the LEDs on and off, and about time, so we can tell it to wait for a few seconds between each colour.

Here we’re telling the computer to use call the pins by the numbers in the order they are laid out on the board (there is an alternative way of numbering them called BCM). Next we tell it not to warn us if the GPIO pins have already been used.

Now we're telling the Raspberry Pi which pins are used for which coloured LEDs. Note that we don’t have to state that we're using pin 9 for ground; it doesn’t matter.

Finally we tell the Raspberry Pi to prepare the red, yellow and green pins for output. If we were getting input, such as reading a switch, then this bit would look different.

This part of the program just gets everything ready. It doesn’t actually turn any of the LEDs on. We'll do that next.

Use File, Save As to save the program as. Don't worry it it tells you that the program already exists – save it anyway.

Lighting up one LED
Let's start by lighting up the yellow LED. At the bottom of the program, add these lines:

HIGH turns a light on. LOW turns it off.

Save the program as.

Now leave the Python window open, and start a terminal session by going to the main desktop Menu - Accessories - Terminal. You should see a black window open.

In the terminal, type:

You should see the yellow LED light up for two seconds, and then the LED will turn off and the program will end. You can repeat the program by entering  again.

Try changing the program to light up the red or green LED.

Flashing an LED on and off repeatedly
Now let’s change the program so that the last lines read:

Save this program as. Go back to the black terminal window and run it with:

The yellow LED should flash on and off every 2 seconds.

Exit the program by holding down the CTRL key and tapping the C key. This may leave the yellow light on! Don’t worry about that.

The full sequence
The full sequence for British traffic lights is:


 * Red (stop) — for a long time
 * Red and Yellow together (get ready to go) — for a short time
 * Green (go) — for a long time
 * Yellow on its own (get ready to stop) — for a short time

Let's change our program to do this full sequence:

That's it! Save this program as. Go back to the terminal window and run it with:

Exit the program by holding down the CTRL key and tapping the C key.

You can use the alloff.py program to turn all the lights off after you've stopped the program. Also there is the  program which uses some advanced techniques to turn off the lights when the program is stopped.

Further adventures
Here’s some ideas for other things you could do:

Run two sets of lights from one Raspberry Pi
You could use pins 12, 16 and 18 (plus pin 14 for ground) to control another set of lights.

For a T-junction you need 3 sets of lights. For a crossroads, 4 sets
On a Model B+ or Pi 2 you could use pins 36, 38 and 40 (plus pin 34 for ground) to control a third set of lights, or you could use two Raspberry Pis.

If you had more than one Raspberry Pi, how could you synchronise the lights? How could two Raspberry Pis communicate between each other?

How could you detect a toy car waiting at the lights?
Does your strategy work if it is a plastic LEGO® car or a metal toy car, or both? Does it matter if the car is heavy or light?

What about if it was a bicycle or a horse? How do traffic lights in the real world detect cycles and horses – do they have another strategy, or do they ignore that problem?

How could you run your program automatically when you turn on your Raspberry Pi?
Try searching for information on the  command.

Preparation
The files for this tutorial can be found at: http://www.cotswoldjam.org/downloads/2015-09/

Please create a  folder under the home/pi directory, then unzip the files into that directory. This can be done in the LXTerminal:

=Raspberry Pi GPIO Zero Reaction Timer= Tutorial by Andrew Oakley Public Domain 1 Feb 2016 www.cotswoldjam.org

Introduction
This Python programming tutorial, shows you how simple it is to use an LED light and a button, with the new GPIO Zero library.

Conventions
At the end of each line, you will usually have to press the Enter key.

Your tutor should have prepared your Raspberry Pi for you and given you a bag of components. If not, see the section "Preparation" at the end.

The electronics
An Light Emitting Diode (LED) is a light bulb with a short leg and a long leg. If you feel around the rim, you'll also find a flat edge. The short leg and flat edge always connect to negative (ground).

The resistor can be connected any way around. Lower value (lower Ohm) resistors will allow more current through and will make the LED brighter; higher values will let less current through and make it dimmer. We're using a 270 Ohm resistor but anything between 220-470 Ohms will work fine.

A switch can be connected any way around. When pressed, it allows electricity to flow; when released, the electricity stops. This kind of push-button is known as a "momentary press-to-make switch".

You should also have a breadboard and some jumper wires. You should have three long male-to-female wires (with a sticky-out bit at one end, and a sticky-in bit at the other end), and one short male-to-male wire (with sticky-out bits at both ends).

The circuit
Connect up the breadboard as shown.

Breadboards allow us to quickly make electronic circuits. The board has a top section and a bottom section. All the vertical holes in each section are connected together, so if you plug things in in a vertical column, they'll make a connection.

Don’t worry about the colours of the wires – the author of this tutorial is colour-blind.

The Raspberry Pi uses two sets of numbers to refer to the General Purpose Input Output pins (GPIO pins).

"Board numbering" just starts from the bottom-left at 1, and works its way up and right, through to 40.

"BCM numbering" (Broadcom numbering) is the way the Raspberry Pi's processor sees the pin connections.

GPIO Zero uses BCM numbering.

Connect the short leg of the LED to a Ground connection.

Connect the resistor to the long leg of the LED.

Connect the other end of the resistor to GPIO 23.

The program
Power up your Raspberry Pi and go to the desktop.

From the menu, select Programming - Python 3. Then use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the led.py program in the python/reaction folder.

Use File, Save to save this program as led.py and the run it by selecting Run menu, Run Module.

You should see the LED light up for two seconds, and then turn off.

Not working? Check you’ve got:
 * The correct GPIO pins
 * The LED is the correct way round; short leg to ground (GND)
 * Components lined up on the correct vertical columns on the breadboard
 * No spelling mistakes, no missing brackets, and you’ve used round brackets instead of pointy, curly or square ones

What is this program doing?
The first two lines tell the computer to learn about a new thing. Computers can learn from programs that other people have written, and we call these other programs "libraries". Our instructions tell the computer to learn about LEDs from the GPIOZero library, and learn about sleeping from the time library.

We then create an LED object. We say that the LED is connected to GPIO 23.

Turn the LED on, wait for 2 seconds, then turn it off.

The circuit
Now add the button and connecting wires.

The short jumper wire should go from the same column as the existing ground wire, to the column connecting to one of the button's legs.

The remaining long jumper wire should go from the column with the other leg of the button, to GPIO 24 on the Raspberry Pi.

The program
In Python 3, use File, New Window to create a new program. Type in the following program, or alternatively you can use File, Open to open the button.py program in the python/reaction folder.

Indentation matters in Python. For example, you must type the two spaces before the word. Indentations like these define a block of code – hence the word.

Use File, Save to save this program as button.py and the run it by selecting Run menu, Run Module.

Hold down the button. It should say "Button PRESSED!" in the Python 3 shell window.

Let go of the button. It should say "Button unpressed!". You can press and release the button many times.

Halt the program by selecting Shell menu, Restart shell.

What is this program doing?
These are called functions. They define something that should happen, and they give that action a name. The code is indented to show it belongs to the function. The  function says "Button PRESSED!" and the  function says "Button unpressed!".

Here we set up a button object and tell the computer that it is connected to GPIO 24.

We also tell the computer what to do, when the button is pressed or released.

This tells the computer to wait for events to happen, such as button presses.

Button and LED together
In Python 3, use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the  program in the python/reaction folder.

Use File, Save to save this program as led-button.py and the run it by selecting Run menu, Run Module.

Press the button and the LED should light up; release the button and it should turn off.

Halt the program by selecting Shell menu, Restart shell.

Reaction timer
In Python 3, use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the reaction.py program in the python/reaction folder.

Use File, Save to save this program as reaction.py and the run it by selecting Run menu, Run Module.

The LED will flash four times, then on the fifth time it will stay on until you press the button.

Try to press the button as quickly as possible when it comes on for the fifth time.

You will be shown your reaction time in seconds.

You can have as many goes as you like - try challenging a friend to see who has the fastest reactions. When you've had enough, halt the program by selecting Shell menu, Restart shell.

What is this program doing?
We've introduced several new concepts in the reaction program.

We're using a value which we call  to record when the fifth flash starts. We can then compare it to the time when the user presses the button, and that will tell us the reaction time.

Values which are given a name, like, are called variables, because the actual value they contain can vary.

Some variables are global. This means they can be used in any part of the program.

tells the computer to print a decimal fraction with 3 decimal places after the decimal point.

The number we're going to print is the value of time now, minus the value of time when we started the final flash. This is measured in seconds.

The  command is used here to pick a random number between 0.5 and 3. It will probably pick a decimal fraction rather than a whole number. The command is called uniform because it you call it enough times, you will get uniform random distributon of numbers - you'll eventually get every possible number in that range.

This command tells the LED to blink for 0.1 of a second, then wait for 0.4 of a second, then repeat that 4 times.

The last value, False, tells it to wait until it has finished before moving on to the next command. If you put True then it would start executing the next commands whilst carrying on blinking! We don't want that here.

You can find more about GPIO Zero commands at: http://pythonhosted.org/gpiozero

Preparation
You will need the following electronic components for this tutorial:
 * 1× Breadboard – mini 170 point
 * 1× LED – 5mm diffused through-hole, red
 * 1× Resistor – carbon film 270 Ohm through-hole
 * 1× Switch – 2 pin tactile push-button through-hole
 * 3× Male to Female jumper wires - 20cm
 * 1× Male to Male jumper wire – 10cm

The files for this tutorial can be found at: http://www.cotswoldjam.org/downloads/2016-01/

You will need Raspbian Jessie with Python 3, IDLE and GPIO Zero. Once you have Raspbian Jessie and an internet connection working, you can ensure all the other files are installed by going to Menu, Accessories, Terminal and typing:

The  may take a while – maybe half an hour if your system hasn’t been updated recently. Don’t worry if  tells you that you already have packages installed.

=Raspberry Pi LEGO® Burglar Alarm= Tutorial by Andrew Oakley Public Domain 2016-04-24 updated 2018-03-01 www.cotswoldjam.org

LEGO® is a trademark of the LEGO Group of companies which does not sponsor, authorize or endorse this tutorial nor Cotswold Raspberry Jam.

Getting started
This tutorial shows you how to make a burglar alarm that sounds when a LEGO® door is opened.

At the end of each line, you will usually have to press the Enter key. Your tutor should have prepared your Raspberry Pi for you and given you a bag of components. If not, see the section "Preparation" at the end.

The electronics
Be very gentle and careful with reed switches. The glass can break easily.

You should also have four female-to-female jumper wires, a small magnet and a LEGO® door. Your tutor should have already stuck the reed switch to the inside top of the door frame with sticky tape, and stuck the magnet to the inside top of the door.

If you have a burglar alarm at home, get a step-stool and look at the top of the door. I bet you have some white plastic bits – one on the door frame, one on the top of the door. These contain a reed switch and a magnet, just like this tutorial.

The circuit
Don’t worry about the colours of the wires – the author of this tutorial is colour-blind.

The Raspberry Pi uses two sets of numbers to refer to the General Purpose Input Output pins (GPIO pins).

"Board numbering" just starts from the bottom-left at 1, and works its way up and right, through to 40.

"BCM numbering" (Broadcom numbering) is the way the Raspberry Pi's processor sees the pin connections.

We're going to program with GPIO Zero, which uses BCM numbering.

Connect the reed switch to Ground and GPIO4.

Connect the short leg of the piezo buzzer to Ground. Connect the long leg to GPIO23.

Detecting the door opening
Power up your Raspberry Pi and go to the desktop.

From the menu, select Programming - Python 3. Then use File, New Window to create a new program.

Type in the following program, or alternatively you can use File, Open to open the  program in the python/burglar folder.

Use File, Save to save this program as burglar1.py and the run it by selecting Run menu, Run Module.

Close the door and then open it. You should see the words "Door opened" on the screen.

Not working? Check you’ve got:


 * Wires going to correct GPIO pins.
 * The reed switch is aligned with the magnet. Rotate it gently so that the contacts are pulled together by the magnet.
 * The reed switch hasn't got broken (ask your tutor for another if so).
 * No spelling mistakes, no missing brackets, and you’ve used round brackets instead of pointy, curly or square ones.

What is this program doing?
The first line tells the computer to learn about a new thing. Computers can learn from programs that other people have written, and we call these other programs "libraries". Our instructions tell the computer to learn about buttons, which can either be pressed or released.

A reed switch is a special type of button. It is "normally open" (released) and no electricity goes through it. When a magnet is nearby, it becomes closed (like a pressed button) and electricity flows from the GPIO4 pin to the ground pin.

This causes the program to wait until the reed switch is newly opened – it has to change from closed to open. If the door was already open at the start of the program, that doesn't count.

This prints a message to the screen.

Looping the program
Let's add a loop so that we can keep opening and closing the door.

Alternatively, you can load in the  program if you don't want to type it in.

The  command repeats a section of the program; the word   makes it repeat forever.

Indentation matters in Python. For example, you must type the two spaces in the lines after. Indentations like these define a block of code.

Python is picky about punctuation and capitals, too. The initial letter of  must be a capital, and the line   must end with a colon.

Use File, Save to save this program as burglar.py and then run it by selecting Run menu, Run Module. Try opening and closing the door.

Halt the program by selecting Shell menu, Restart shell.

The buzzer
Change the program to add in the buzzer. Alternatively, load the  file.



Note that we have imported the Buzzer object from the library, as well as the Button.

Next we set the buzzer to work on GPIO23.

When the door has been opened, we use:

This command has three numbers, called parameters:


 * 1) . The number of seconds to sound the buzzer (1)
 * 2) . The number of seconds to keep the buzzer quiet (0, zero)
 * 3) . The number of times to loop through sound and quiet periods (1, once only)

will give us a single 1-second beep. You could change it to sound really annoying!

Use File, Save to save this program as burglar3.py and the run it by selecting Run menu, Run Module.

The buzzer should now sound for one second when you open the door.

Halt the program by selecting Shell menu, Restart shell.

Preparation
Download the sample program files from: http://www.cotswoldjam.org/downloads/2016-04

Glass reed switches break easily. Hold the legs while bending them, don't rely on the glass holding them. Use Sellotape® to ensure any shards do not escape if the switch breaks.

Files
burglar1.py

burglar2.py

burglar3.py

=Raspberry Pi Star Wars lightsaber= Tutorial by Andy Baker, instructions by Hal Motley

This tutorial is available in the public domain. In this tutorial you will connect a multi-colour LED to the Raspberry Pi to create a lightsaber like in Star Wars.

How lightsabers work


For this tutorial, the multicolour LED represents a kyber crystal. In the Star Wars universe lightsabers are powered by a kyber crystal which the Jedi attunes to their will using the Force. There are a wide variety of blade colours including:


 * Luke Skywalker – green
 * Obi-Wan Kenobi – blue
 * Mace Windu – Purple
 * Rey Skywalker – yellow
 * Ahsoka Tano – white

Sith lords such as Darth Vader, Darth Sideous and Darth Maul have red lightsabers because they dominate the kyber crystals using the Force causing them to bleed.

There is a full list of lightsaber colours here: https://sabersguru.com/lightsaber-color-meanings/

The kit

 * ×4 male-female GPIO jumper cables (also called DuPont cables, preferably of different colours)
 * ×1 breadboard (a small 5×5 breadboard works well, but any size is fine)
 * ×1 68 Ohm (blue grey black gold) resistor
 * ×1 4-pin colour-changing LED

Connecting the components
To setup the lightsaber, do the following:

Step 1: Connect the 4 jumper cables from the GPIO pins 33, 35, 37 and 39 (GND) (last four bottom right pins, assuming the USB and Ethernet ports are to the right) to the bottom left four holes of the breadboard. I recommend trying to use the same coloured jumper wires that match the diagram exactly, though any colour combination can be used.

Step 2: Connect the 68 Ohm resistor into the breadboard by placing one connector into the first hole and another into the last hole of the row above the jumper wires.

Step 3: Connect the colour-changing LED to the 4 holes on the right of the last row, make sure that the longest pin (the ground) is lined up with the black jumper wire so the LED is properly grounded.

Step 4: Run each of the Python scripts in order, which are,  ,   and. Try altering the code and see if you can make your own colour combinations.

The programs
ls1.py

ls2.py

ls3.py

lightsaber.py

=Raspberry Pi Python GPIO Zero Distance Sensor= Tutorial by Jonathan Teague - Public Domain 28th Jan 2017 - www.cotswoldjam.org

This tutorial will cover using the popular HC-SR04 ultrasonic distance sensor, the Raspberry Pi and the  library to measure distances.

The kit
In your bag you will find the following components:


 * ×4 M-F Jumper leads (pin to socket)
 * ×1 R1 680Ω resistor
 * ×1 R2 470Ω resistor
 * ×1 Mini Breadboard
 * ×1 HC-SR04 Ultrasound sensor

Putting it together:

The colour of the jumper wires in your kit is not important – where you put them is VERY important! Breadboard holes are numbered – make sure you connect to the correct hole.

Step 0: Make sure your Pi is shut down and the power lead disconnected.

Step 1: Take 1 jumper lead and plug the pin (male end) into B1 on the breadboard and the socket (female end) into GND (Pin 6) on the Pi.



Step 2: Take 1 jumper lead and plug the pin into B3 on the breadboard and the socket into GPIO20 on the Pi. This is the connector that the Pi will use to trigger the distance measurer to take a measurement.



Step 3: Take the R1 680Ω resistor – the one with a blue colour line on and insert the legs into holes E1 and I2 on the breadboard – it doesn’t matter which way round the resistor is.



Step 4: Take the other resistor, the R2 470Ω – with a yellow colour line on and insert the legs into holes D2 and H2 on the breadboard – again it doesn’t matter which way round.



Step 5: Gently bend the R1 resistor away from R2 so the legs in E1 and D2 won’t touch each other (if they do it won’t damage anything, it just won’t work).



Step 6: Take 1 jumper lead and plug the pin into J2 on the breadboard and the socket into GPIO21 on the Pi. This is the connector that the Pi will use to listen for the measurement.



Step 7: Take the last jumper lead and plug the pin into B4 on the breadboard and the socket into 5V(Pin 2).



Step 8: Finally, plug in the HC-SR04. It has 4 pins and these need to go into A1, A2, A3 and A4. The back of the sensor with all the black ICs on should be facing the breadboard and the two silver sensors pointing away from the breadboard.



The program
Power up your Raspberry Pi. From the desktop menu, select Programming - Python 3 (IDLE). Then use File, New File to create a new program.

Type in the following program then use File, Save to save your program as the name of your choice (don’t forget to put .py on the end) in the ~/python/distance folder and then run it with Run menu, Run Module.

What does the program do?

The first line is a comment (it starts with #) and tells the operating system what langauge the program is written in, as you will run the progam from Python yourself this is redundant (but good practice).

The  lines tell the computer to learn about new things. Computers can learn from programs that other people have written; we call these other programs "libraries". Our program needs the function called  from the   library which it will use to talk to the sensor and the function   from the time library so that we can insert pauses. A function is just some code located somewhere else that we can make use of to do something.

We then create an object we call  using the imported function. The parameters that we pass say that the  to invoke the sensor will be on GPIO pin 20; the   to listen for the reply will be on GPIO pin 21 and that the maximum distance that should be returned is 2.0 metres.

This  tells the program to run forever in a loop.

Then we get the current sensor reading by calling, multiply this by 100 (as the returned value is in mm); print out the value with only one digit after the decimal point; and finally go to sleep for a second before the   makes us go around again.

Additional notes
These notes are additonal to the main tutorial and explain the use of two resistors to make a "voltage divider" and give an example program that directly controls the sensor.

The Voltage Divider
The Raspberry Pi is a 3.3V device. The sensor used in this tutorial, an HC-SR04, is a 5V device. This means that the sensor needs 5V to power it and, crucially for the Pi, that the voltage levels that the sensor returns the results to the Pi are also at 5V. Connecting the sensor output directly to the Pi would almost certainly result in damage to the Pi.

This sort of situation is often found in the real world, you have two devices you wish to connect to each other but they operate at different voltages. There are several ways to solve this but one of the simplest, and the one used here, is to drop the voltage from 5V to just under the safe value of 3.3V by making a "voltage divider" out of two resistors.

The two resistors are placed in series across the source voltage and zero volts and the voltage at the point between the two resistors will be reduced in proporation with the values of the two resistors.

$VinR1⁄R1 + R2$

So substituting in the values for 5V as the Vin and the two resistors we have used, R1 = 680Ω and R2 = 470Ω we get:

$Vin680⁄470 + 680 = 2.95V$

This 2.95V is then safe to connect to the Pi.

A program to interface to the HC-SR04 directly
In the tutorial we don't talk directly to the HC-SR04 but leave all that to the DistanceSensor functionality of the GPIO Zero library. This is convenient but sometimes it's useful to know exactly what is going on and to be able to understand how to control devices directly.

In the ~/python/distance folder you will find a file  which shows how to trigger and read the HC-SR04 sensor directly and which uses the RPi.GPIO library.

Here is the important bit that triggers the HC-SR04 to take a measurement and gets the result back, it's all contaned in a function called :



What does this do?

Setting the GPIO_TRIGGER to True, sleeping for 10uS then setting the GPIO_TRIGGER to False triggers the sensor to take a reading.

The code then sets a variable called  to the current time and goes into a tight loop while GPIO_ECHO is 0 (= low), every time round the loop it resets the variable.

Once GPIO_ECHO is 1 (= high) this first look will stop. At this point  contains the time when the Echo pin went high.

Now the code goes into a tight loop while GPIO_ECHO is high, every time round the loop setting the variable.

Finally when the GPIO_ECHO goes low again the loop exits. At this point start contains the time when the Echo went high and  the time when it went low again.

Now it's just some maths to work out how long the Echo pin was high for, multiply this by the speed of sound (the 34300) and divide by 2 (because the sound from the sensor went out and back) and we get the  value in cm.

Files
rpigpio_DistanceSensor.py

gpiozero_DistanceSensor.py

=Raspberry Pi Web Server & HTML Tutorial= Tutorial by Andrew Oakley Public Domain 28 Jan 2017 www.cotswoldjam.org

The Terminal
Start the terminal with the Raspberry Pi menu – Accessories – Terminal.

We’re going to install a web server. A server is a program that other people can connect to.

The ordinary user pi doesn’t have the ability to install software, so we use the sudo command to temporarily switch to the superuser (also known as the root user). Enter:

Update gets an up-to-date list of software. Upgrade installs new versions of any out-of-date software you have. If you are on a slow internet connection, upgrade might take a long time. You might be asked to confirm by pressing Y and Enter. Now let's install the Apache web server, the most commonly used Linux web server.

You’ll see that this asks to install apache2 and a few other programs too. These are called "dependencies" – they are programs which apache2 needs in order to work.

Once Apache is installed, start your web browser. On a Raspberry Pi 2 or 3, you can use the Pi menu – Internet – Chromium web browser.

If you are on an older Pi 1 or Pi Zero, select Pi menu - Run – and then type  and press Enter. Epiphany is a simpler browser for slower computers.

In the web browser's address bar, type  and press Enter.

You should see the Apache2 Default Page. localhost always refers to the computer you're using. So if someone types it into their Raspberry Pi, it'll refer to their Raspberry Pi and not yours.

Go back to the terminal and enter:

It will tell you the name of your computer. This might be raspberrypi or someone might have customised it for you, such as rpi-ab12. Now go back to your web browser, and type:

… where hostname is the name of your computer. You must put .local afterwards on Linux computers. On Microsoft Windows, you'd use .lan instead: hostname.lan

Provided you don't have the same hostname as someone else on the same network (usually "your network" means "your building") then this should find only your computer. This is called Zeroconf and is also known as Avahi or Bonjour. Some computers don't support Zeroconf so you can find our your IP address instead:

(note capital i) Your IP address will look like four sets of numbers, such as 192.168.0.42. Now try browsing to your IP address in the web browser.

Creating your own web page in HTML5
Back in the terminal, enter:

/var/www/html is where web pages are kept. You should see index.html. We're going to rename it to -old (to keep a copy, just in case) and create a new index.html of our own.

A text editor program should pop up, with a blank page. Start typing:

Change Andrew to whatever your name is, and save the page with File menu, Save.

Reload the web browser using the reload button, near the address bar.

What did this code do?
  tells the browser this is the start of a web page; is the end   says this is the start of the header, where the title goes; is the end   is the start of the text of a web page; is the end    is the start of a new paragraph; the closing tag   is optional in HTML5

is a special file name that gets loaded if you don't specify a particular web page inside a folder. So http://localhost is the same as http://localhost/index.html

Under "My name is Andrew" now type:

Don’t forget to File, Save, then reload browser.

   is a link to another web page (or any file on a web browser). The href (hypertext reference) can be "relative" such as pets.html - this will become http://hostname.local/pets.html because pets.html is in the same folder as index.html.

To link to web pages in other folders on other computers, you can use an "absolute" address such as: http://www.bbc.co.uk/news/technology-37305200

Close Leafpad with the X at top right. We're going to add a photo. Let's list the photos (if you’re not using the Cotswold Jam preinstalled SD card, you'll need to find your own photos):

Pick a pet (cat, dog, guinea pig, hamster) and copy the picture to the web server directory:

Create a new web page with:

Reload browser and click on the "My favourite pet link". You can use the Back button to go back to the index page.

Now try browsing other classmates' websites. You will need to know their hostname or IP address. For example http://rpi-12ab.local or http://192.168.0.123

If your hostname is raspberrypi (the default) then that might clash with other similarly named computers. You can change it by going to Pi menu - Preferences - Raspberry Pi Configuration and changing the Hostname. You'll be prompted to reboot your machine when done.

If you want to uninstall Apache:

Create a CSS file for your webpage
Cascading style sheets (CSS) are files used by websites to change the appearance of the content on each webpage.

Create the  file just like the corresponding   file.

Type this CSS to alter the  tags.

Now to add the CSS file to the HTML file so that web browser knows to use it.

By just using the name of the tag on its own that will alter all uses of the tag. CSS uses classes which can be used on specific tags. Type the follwowing into the  file to add a class:

Then declare the class to the  tags.

You can try other CSS attributes to style your webpage such as:


 * makes the font italic.
 * adds a margin to seperate the tag from other elements on the page. Using  on its own will add a margin to all four sides of the tag.
 * changes the colour of the text to red.
 * changes the background colour of the webpage to black.

You can refer to the colour table below or do a Google search to find your preferred colour. CSS supports RGB, HSL and hexidecimal colour standards, though hexadecimal is preferred because it's the most concise.

Numerical bases
A numerical base is the amount of single digit numbers that can be used for counting. In everyday maths we use is called decimal (base 10) which are the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. However, computers are based on binary (base 2) which means they don't count or perform calculations in the same way we do.

Hexadecimal (base 16) is a simplified way to write binary which prevents us from writing out a lot of zeros! Much like binary being the numbers 0 and 1, hexadecimal are the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F.

For example: Decimal 255 = Binary 11111111 = Hexadecimal FF

Each binary digit is doubled for each column. So 1+2+4+8+16+32+64+128 = 255

For further information: https://www.mathsisfun.com/numbers/bases.html

Public IP Addresses
To make your website visible to people outside your network (for example, in other buildings or other towns or countries), you will need a Public IP address. Read the manual for your router to find out how to set up Port Forwarding for port 80. You can find your public IP address by searching Google for "what is my ip".

Your public IP address can change; ask your internet service provider for a Static Public IP address. You can then buy a domain name and associate it with your static public IP address. For some UK ISPs, you might already have a subdomain, for example Plusnet gives every customer accountname.plus.com.

Stopping and starting server programs
From the terminal:

Reload localhost in the browser. Note the error message - the web server has been stopped.

Shows "Active: inactive (dead)" – it’s not running.

Reload the browser. It works again.

Shows "Active: active (running)"

Shows "Loaded: not-found". This means bing-bong-pop doesn't exist, isn't installed, or you spelt it wrong. Of course it doesn’t exist, I made it up as an example.

Controlling automatic starts
Reboot the machine with Pi menu - Shutdown... – Reboot.

Once the machine has restarted, browse to localhost. Note how the web server is started automatically on boot. From the terminal:

Reboot again and, once restarted, try browsing to localhost. You get an error message – the web server didn’t automatically start when you rebooted.

You can start it manually with:

or you can reenable it to start automatically every reboot with:

Removing installed programs
Remember those "dependencies", extra programs which Apache needed to install so that it would work? We use the autoremove directive to uninstall them after we’ve uninstalled Apache.

Updating and installing other programs
…to get the latest versions of the software you already have.

You can find names and descriptions of other packages to install on this website: http://www.raspberryconnect.com/raspbian-packages-list

Once you’ve done an, you can install new software with:

…where packagename is the name of the software you want to install.

Be wary of anything that asks to install lots and lots of other packages. Learn how to make a backup of your SD card, for example with Win32DiskImager on a Windows laptop.

=Raspberry Pi Updates & Backups Tutorial= by Andrew Oakley - Public Domain Jan 2018 www.cotswoldjam.org

Updating your system
You will need a working internet connection. Select the Raspberry menu – Accessories – Terminal. A black box should appear.

These commands will get the list of updated software, and then upgrade. You may be asked to type Y to confirm. This can take a very long time, especially on a Pi 1 or Zero!

autoremove will uninstall any software which has been superseeded by new software. clean removes any temporary installation files, to free up space on your SD card.

Restart your system with Raspberry menu – Shutdown – Reboot.

Connect a USB memory stick and find out what it's called on the system
Insert the USB memory stick into a USB port. We need to find out what the USB stick is called, and where it is on the system.



The memory stick may open automatically in File Manager. In this case, you can read the name from the address bar. In this example it is BLUE64GB.

Alternatively, you can find the name by clicking the "Eject" symbol in the top right of the desktop.



In this example, the name is BLUE64GB. It also shows the brand name (SanDisk Ultra Fit) but we don't care about that.

Don't actually eject the USB stick yet! We're going to put some backups on it. There's another way to find the name and location of your USB stick; find out about the  command.

Back up all your files to a USB stick
These commands back up all files in the /home/pi directory. This includes all documents, images, Scratch and Python source code files and Minecraft worlds that you have made, but it doesn't include programs that have been installed on the system.

Note how we used  to move from the   directory to the   directory.

This allows us to treat the entire pi directory as a subfolder that we can back up.

We also use the  option to ignore the   subfolder, as this can contain a lot of large temporary web browser files.

It's a good idea to use the date in the name of your backups, so you can quickly find a backup from a particular day. We used 2018 01 27 for 27th January 2018. Putting the year and month first, will make it easier to find in a list that's sorted in file name order.

Once we've finished, we use the  command on its own, to return to our   directory. We could have done  which would have done the same thing.

Restore all your files from a USB stick
Insert the USB memory stick into a USB port. Find the .zip file you want to restore using File Manager.

Using the Terminal, restore the files. Note this will overwrite existing files with the older versions.

Back up just one folder
Note that folders beginning with a full stop are sometimes hidden from file listings, but you can still back them up. For example, the Minecraft folder with all your Minecraft worlds:

Restore just one folder
We didn't use, so it will ask before overwriting any existing files.

List all the files in a large .zip backup archive and pick just one file or folder to restore
Although you can use the  command to extract specific individual files, it's easier to use the Xarchiver program. Use File Manager (Raspberry menu – Accessories – File Manager) to open the USB stick and find your .zip file.

Double-click on your .zip file and the Xarchiver program will start.

You can now double-click to open any folder inside the .zip file. Right-click any file or folder and select Extract to recover it.

Click the folder icon beneath "Extract to" to pick a folder to copy the recovered file to. You probably want  which you can either type in, or click the   folder from the list of folders.

If you're just recovering one file, untick "Extract files with full path".

Click the Extract button to recover the file.

Use File Manager (Raspberry menu – Accessories – File Manager) to find the files you've extracted.

Safely remove the USB memory stick


Click the "Eject" symbol at the top-right of the desktop, then click the smaller eject symbol to the right of your listed USB memory stick.

You should see the message "It is now safe to remove your device". You can remove the USB memory stick from the Raspberry Pi now. You can also eject it from the command line – learn about the  command.

Don't keep your backups near your Pi. If your Pi gets lost, stolen, destroyed by fire or eaten by zombies, you don't want your backups to go missing too!

Grandparents, Aunties and Uncles' houses are a really, really good place to keep your backups. Consider having two memory sticks – one to keep at a relative's house, and one to keep in your house. Swap them over every time you visit!

Migrating to a new release of Raspbian
Every two or three years, a completely new release of Raspbian happens. For example, in 2017 we moved from Raspbian Jessie to Raspbian Stretch.

Raspbian is the operating system that runs on most Raspberry Pis. It handles the desktop, most of the programs, the command line and much more. Raspbian is based on Debian GNU/Linux, which names releases after characters from the Toy Story films. Debian is short for "Debra and Ian"; Ian Murdoch created it, and Debra was his girlfriend.

Whilst it is technically possible to upgrade an existing SD card to a new release, it's prone to mistakes, so our advice is to:


 * Back up all your files to a USB stick, as we showed previously in this tutorial
 * Download the new release image, and burn it to a new SD card, as per the instructions here: https://www.raspberrypi.org/documentation/installation/installing-images/README.md
 * Restore your files from your USB stick backup, as per this tutorial.

Other top tips
If you have both a Pi Zero or Pi 1, and a Pi 2 or a Pi 3, do all your updates on the Pi 2 or Pi 3. It will be much, much faster. You can usually swap the memory cards between them (unless your Pi 1 has a really, really old version of Raspian – in that case it won't work on the Pi 2/3 but it won't cause any harm, just put it back).

Using an Ethernet network cable directly plugged in to your broadband router can often make downloading updates much faster than WiFi. You can buy a simple CAT5e Ethernet cable from Poundland and other bargain shops, just don't pay more than £5.

=Raspberry Pi Minecraft Python coding= Tutorial by Andrew Oakley Public Domain 17 May 2018 www.cotswoldjam.org

To start Minecraft, click the Pi menu - Games - Minecraft Pi

Click Start Game then click an existing game or click Create New

TAB key to switch between the Minecraft world and the normal mouse on the desktop. The TAB key is to the left of the letter Q.

ESC for the game menu

To code with Minecraft, leave Minecraft running. Press the TAB key to release the mouse from the game, so you can use the mouse on the desktop.

Click Pi menu - Programming - Python3 (IDLE).

At this point your tutor may want you to open an existing program using File menu - Open.

Alternatively, to create a new program use File menu - New File.

Once you have loaded or written your program, use Run menu - Run module or press F5.

Example Minecraft code: