User:Inferno986return/sandbox
Formerly Learn Electronics with the Raspberry Pi
This is a work-in-progress Wikibook which will be moved over once a few tutorials have been transcribed. I plan on this being worked into a Wikijunior book for Raspberry Pi projects. |
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
edit- step-by-step screenshots for the Minecraft tutorials
How to contribute
editFind 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
editA 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
edit- 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?
editA 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
editWhat is electricity?
editElectricity is energy
editElectricity 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
editConductors are materials that capable of conducting electricity because they allow the flow of electrons.
Insulators
Semi-conductors
Current, Voltage, Resistence and Power
editThere are 4 main units for measuring electricity. Each of them are named after a scientist who made significant discoveries related to it.
Type | SI Unit | Discoverer | Description |
---|---|---|---|
Current | Amp (A) | André-Marie Ampère | The current is the flow of electrons. |
Voltage | Volt (V) | Alessandro Volta | The voltage is the force that pushes the electrons. |
Resistence | Ohm (Ω) | Georg Ohm | The resistence is the force that reduces the current. |
Power | Watt (W) | James Watt | The power is the energy consumption over a period of time. |
Ohm's law
editIn the Ohm's law formula the current is abbreviated to a capital I . |
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
editMany 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).
Prefixes | Value | Standard Form | Symbol |
---|---|---|---|
Tera | 1 000 000 000 000 | 1012 | T |
Giga | 1 000 000 000 | 109 | G |
Mega | 1 000 000 | 106 | M |
Kilo | 1 000 | 103 | K |
deci | 0.1 | 10-1 | d |
centi | 0.01 | 10-2 | c |
milli | 0.001 | 10-3 | m |
micro | 0.000 001 | 10-6 | μ |
nano | 0.000 000 001 | 10-9 | n |
pico | 0.000 000 000 001 | 10-12 | p |
The Greek letter mu (μ) is used for micro. You may be familiar with a kilogram (1000 grams) or centimetre (0.01 metres).
Electronic components
editMost of these components can be purchased inexpensively from hobbyist stores or electronic component wholesalers such as RS Components and Farnell.
Breadboard
editA 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
editA 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
editA 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)
editLEDs are sensitive to a high electrical current within a circuit and they may break. Always use an appropriate resistor when connecting them to a circuit. |
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
editA 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
editA 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
editA 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
editA 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
editThe 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%.
Colour | Code | Significant Figure | Multiplier | Tolerance |
---|---|---|---|---|
None | - | - | - | ±20% |
Pink | PN | - | ×0.001 (×10−3) | - |
Silver | SR | - | ×0.01 (×10−2) | ±10% |
Gold | GD | - | ×0.1 (×10−1) | ±5% |
Black | BK | 0 | ×1 (×100) | - |
Brown | BN | 1 | ×10 (×101) | ±1% |
Red | RD | 2 | ×100 (×102) | ±2% |
Orange | OG | 3 | ×1000 (×103) | ±0.05% |
Yellow | YE | 4 | ×10000 (×104) | ±0.02% |
Green | GN | 5 | ×100000 (×105) | ±0.5% |
Blue | BL | 6 | ×1000000 (×106) | ±0.25% |
Violet | VT | 7 | ×10000000 (×107) | ±0.1% |
Grey | GY | 8 | ×100000000 (×108) | ±0.01% |
White | WH | 9 | ×1000000000 (×109) | - |
This resistor colour code table has been simplified from the Electronic colour code article on Wikipedia.
Further reading
editThe books are recommended for further reading on the Raspberry Pi and for learning electronics as whole.
Bibliography
editTitle | Author | Year | ISBN |
---|---|---|---|
Adventures in Minecraft | Martin O'Hanlon, David Whale | 2018 | 978-1-11-9439585 |
Adventures in Raspberry Pi | Carrie Philbin | 2014 | 978-1-11-899753-6 |
Practical Electronics for GCSE | Michael McLoughlin | 1989 | 978-0-09-173044-4 |
Practical Electronics: Complete Introduction | Andy Cooper, Malcolm Plant | 2016 | 978-1-47-361407-1 |
Electronics for Dummies | Dickon Ross, Cathleen Shamieh, Gordon McComb | 2010 | 978-0-47-068178-7 |
Raspberry Pi Cookbook | Simon Monk | 2014 | 978-1-449-36522-6 |
Web links
editHow Semiconductors work. This tutorial includes Diodes, LEDs and Transistors, gets Techy.
Distance Learning – Tutorials
- http://www.instructables.com/id/Basic-Electronics/
- http://www.electronics-tutorials.ws/
- 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
editTutorial by Andrew Oakley
Public Domain 24 Sept 2016
www.cotswoldjam.org
The electronics
editLEDs always need to be connected with a resistor. If you connect them without a resistor, they will burn out and probably won't work again. |
The LED (Light Emitting Diode) has 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. Any resistor between 220 and 470 Ohms will work fine. |
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
editPower 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.
from gpiozero import LED
from time import sleep
led=LED(4)
led.on()
sleep(1)
led.off()
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?
editfrom gpiozero import LED
from time import sleep
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.
led=LED(4)
We then create an LED object. We say that the LED is connected to GPIO 4.
led.on()
sleep(1)
led.off()
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 led2.py
program and learn about the led.blink()
command.
Files
editled2.py
from gpiozero import LED
led=LED(4)
# Blink the time signal
# 6 short flashes followed by 1 long
led.blink(0.5,0.5,6,False)
led.blink(1,0,1,False)
# led.blink() has 4 parameters:
# On time, in seconds, can be decimal fraction
# Off time, in seconds, can be decimal fraction
# Repeats, a whole number
# or the value None which means forever
# default is None
# Background, whether to wait (False)
# or carry on (True) (default is True)
# Try to blink SOS in Morse Code
# S = short short short
# O = long long long
Screaming Jelly Babies Tutorial
editIn 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
editThings that appear on the screen or need to be typed in are written like this.
At the end of each line, you will usually need to press the ↵ Enter key.
Log in and start IDLE
editWhen you turn on your Raspberry Pi, after a few moments it will ask you to log in. You will need to type the username (pi
) followed by the ↵ Enter key, then the password (raspberry
), followed by the ↵ Enter key.
raspberrypi login: pi
password: raspberry
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:
startx
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
editType in the following program:
print "Hello World"
Save it using the File menu, Save, and then double-click into the python folder and then the jellybaby folder. Save the program as:
jellybaby.py
On the desktop, double-click the LX Terminal icon. A new black window will appear.
Switch into the python/jellybaby folder by entering:
cd python/jellybaby
Have a look at what files are in this folder by entering:
ls
You should see your jellybaby.py
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:
sudo python jellybaby.py
The computer should respond:
Hello World
Let’s have a quick look at what we did there:
sudo
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 sudo
.
python
tells the computer to run a program written in the python programming language. jellybaby.py
is the name of your program.
Wires
editPlease check and check again that you’ve plugged in to the right pins. If you get it wrong, you can permanently damage your Raspberry Pi. Ask your tutor to check. |
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:
sudo shutdown –h now
sudo
is the superuser-do command again. shutdown means to turn itself off. –h
means halt (as opposed to –r
which means restart) and now
means, well, right now! (if there were other people using your Pi over the network, you could say +5
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
editPut the power lead back in, wait for the Raspberry Pi to turn on, then log in (pi
/ raspberry
; 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 jellybaby.py
.
Change the program so that it reads:
import time
import RPi.GPIO as GPIO
import os
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(3,GPIO.IN)
print "Hello World"
while True:
if GPIO.input(3) == False:
print "Ouch!"
time.sleep(1)
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 while
and if
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 import
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 (sleep
). The GPIO
library lets us use the GPIO pins. The os
library lets us call other programs, such as the music player, but we’re not using that just yet.
while
tells us to repeat a block of code. True tells the computer to always do something.
if
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 False
. Note the use of two equals signs ==
. One equals sign is used to set a value, such as a=3
means that every time the computer sees a it will know it has the value 3
. Two equals signs are used to compare one thing with another.
time.sleep(1)
means to wait for 1 second.
Save the program, then run it by starting LXTerminal from the desktop (double-click) then enter:
cd python/jellybaby
sudo python jellybaby
The program will print Hello World! and then it will wait.
Touch the paperclip wires together. You should see it say:
Ouch!
Release the wires, wait few seconds and then touch the wires together again. It should say Ouch!
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
editLet’s change the program so that it makes a sound instead of just printing “Ouch!” on the screen. Change:
print "Ouch!"
…to:
os.system('omxplayer scream-c.wav')
|
|
Problems listening to this file? See media help. |
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
editGet 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
edit
|
|
Problems listening to this file? See media help. |
|
|
Problems listening to this file? See media help. |
|
|
Problems listening to this file? See media help. |
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?
For Tutors
editEquipment – for each workstation
edit- ×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
editDownload and unzip the folder structure, scream sound samples and example program. To do this, from an internet-connected Raspberry Pi, log in (pi
/ raspberry
) and do:
cd
wget http://www.cotswoldjam.org/downloads/2014-11/jellybaby.zip
unzip jellybaby.zip
This will create:
~/python/
~/python/jellybaby/
~/python/jellybaby/scream-c.wav
~/python/jellybaby/scream-d.wav
~/python/jellybaby/scream-e.wav
~/python/jellybaby/example/
~/python/jellybaby/example/jellybaby.py
Resources
editjellybaby.py
import time
import RPi.GPIO as GPIO
import os
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(3,GPIO.IN)
print "Hello World"
while True:
if GPIO.input(3) == False:
os.system('omxplayer scream-c.wav')
time.sleep(1)
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
editTutorial by Andrew Oakley
Public Domain 17 Apr 2015
www.cotswoldjam.org
Introduction
editThis 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!
Words you will see on the screen are highlighted like this
Words you need to type in are highlighted and underlined
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
editBuild up the circuit as follows. Place the components first, and the jumper wires last. Don't worry about the paperclips just yet.
LEDs always need to be connected with a resistor. If you connect them without a resistor, they will burn out and probably won't work again. |
The LED (Light Emitting Diode) has 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. We're using a 270 Ohm resistor but anything between 220–470 Ohms will work fine. | |
The photocell, or photoresistor, can be connected any way around. They let through more current when there is more light. We're using one that is rated between 2 and 20,000 Ohms but most photocells you find in hobby kits will work fine. | |
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). We're using a 1 microfarad capacitor and you should too. A capacitor stores a small amount of charge, then when it is full it lets all the charge go. If you connect it to a stronge charge, it lets the charge go faster. If you connect it to a weak charge, it takes longer to let the charge go. |
Here's what the breadboard should look like before you plug in the jumper wires. | |
And here's the breadboard with the jumper wires attached. |
Important – bend the photocell to face the light. You will need to bend the top of the photocell so that it is "looking" towards the LED. See the photos for an example. |
Leg trimming
editWhen 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.
Metal will fly off when cutting and can be very dangerous near your eyes – wear goggles or place the component under a tea-towel when snipping the legs. |
Connecting the Raspberry Pi
editConnect 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
editPower up your Raspberry Pi, log in and go to the desktop. If you need to log in, the default username is pi
and the password is raspberry
. If the desktop still does not appear, type startx
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: mycandle.py
Lighting up the LED
editLet's start by lighting up the LED. Type in the following program, or load it from mycandle1.py in the examples folder:
import RPi.GPIO as GPIO, time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
pin_write=7
GPIO.setup(pin_write, GPIO.OUT)
GPIO.output(pin_write, GPIO.HIGH)
time.sleep(2)
GPIO.output(pin_write, GPIO.LOW)
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:
cd python/candle
sudo python mycandle.py
You should see the LED light up for two seconds, and then the program will end. You can
repeat the program by entering sudo python mycandle.py
again.
Let's have a quick look at what this program is doing.
The import
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; GPIO
which lets us use the GPIO pins, and time
which includes the sleep
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 pin_read
to an output and set the voltage low, just to clear any voltage on the connection, before we set it to an input with GPIO.setup(pin_read, GPIO.IN)
.
We then start counting. We have a new variable, reading
, which we set to zero.
The program then loops around until it detects high voltage from the capacitor, adding one to the reading
count every time. When it detects high voltage, it ends the loop and prints out the value of the reading
.
Hoods and flaps – detecting breath
editWe 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
edit
|
|
Problems listening to this file? See media help. |
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
sensitivity
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+C 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
candle.py
from theexamples
folder if you prefer.
#!/usr/bin/env python
# Raspberry Pi GPIO Birthday Candles by Andrew Oakley aoakley.com Public Domain 2015
# Adapted from "Basic Photocell Reading" by Adafruit
# Import the libraries we will be using
import RPi.GPIO as GPIO, time, os
# RPi.GPIO - for controlling GPIO pins
# time - for waiting
# os - for calling the music program
# Set up the GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
pin_read=12 # GPIO 18
pin_write=7 # GPIO 4
# Sensitivity, in percent
sensitivity=50
def timeLowHigh ():
# This times how long it takes for a pin to go from low to high.
# It is handy for reading variable resistance using a capacitor.
# If the capacitor fills slowly, there is high resistance.
# Photocells are a type of variable resistor. When there is low light, then there is high resistance.
# Therefore long time = darker, short time = lighter
# Try using a 1 microfarad capacitor and a 2-20K ohm photocell.
# Reset the reading to zero
reading = 0
# Reset the pin to low - we briefly set it to output
GPIO.setup(pin_read, GPIO.OUT)
GPIO.output(pin_read, GPIO.LOW)
# Brief sleep just to let it settle on low
time.sleep(0.01)
# Now change the pin back to an input
GPIO.setup(pin_read, GPIO.IN)
# This takes about 1 millisecond per loop cycle
while (GPIO.input(pin_read) == GPIO.LOW):
reading += 1
return reading
def calibrate():
# This turns on the LED and works out what the
# "normal" level of dimness is with the LED on.
# Turn on the LED
GPIO.setup(pin_write, GPIO.OUT)
GPIO.output(pin_write, GPIO.HIGH)
# Read the dimness lots of times over 3 seconds
# and keep a running tally of the average
print ("Calibrating...")
dimness=timeLowHigh()
t=time.time()
while time.time() < t+2:
c=timeLowHigh()
print "calibration: %05d now: %05d" % (dimness, c)
dimness=( dimness+c )/2
return dimness
# Record what normal dimness is
normal_dimness=calibrate()
while True:
# Find out what the dimness is now
dimness_now=timeLowHigh()
# Print out the values
print("dimness normal: %05d now: %05d target: %05d" % (normal_dimness, dimness_now, normal_dimness*(sensitivity/100.0) ))
# Has the dimness fallen below the target?
if dimness_now < normal_dimness*(sensitivity/100.0) :
GPIO.output(pin_write, GPIO.LOW)
print ("Good Morning to All!")
os.system('omxplayer good-morning-to-all.ogg')
normal_dimness=calibrate()
As before, run the program by switching to the terminal window and entering sudo python candle.py
or mycandle.py
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
editIf 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
editYou 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
editPlease 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:
cd
mkdir python
cd python
curl -O http://www.cotswoldjam.org/downloads/2015-04/candle.tgz
tar xvzf candle.tgz
…where -O
is a minus sign followed by a capital letter O (not the numeral zero).
mycandle1.py
#!/usr/bin/env python
import RPi.GPIO as GPIO, time, os
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
pin_write=7
GPIO.setup(pin_write, GPIO.OUT)
GPIO.output(pin_write, GPIO.HIGH)
time.sleep(2)
GPIO.output(pin_write, GPIO.LOW)
mycandle2.py
import RPi.GPIO as GPIO, time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
pin_write=7
pin_read=12
GPIO.setup(pin_write, GPIO.OUT)
GPIO.output(pin_write, GPIO.HIGH)
time.sleep(1)
GPIO.setup(pin_read, GPIO.OUT)
GPIO.output(pin_read, GPIO.LOW)
time.sleep(0.01)
GPIO.setup(pin_read, GPIO.IN)
reading=0
while (GPIO.input(pin_read) == GPIO.LOW):
reading += 1
print "Reading: %d" % reading
GPIO.output(pin_write, GPIO.LOW)
Raspberry Pi LEGO® Traffic Lights
editTutorial 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
editThis 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.
Getting started
editConventions
editThings that appear on the screen or need to be typed in are written like this.
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 electronics
editComponents
editLEDs always need to be connected with a resistor. If you connect them without a resistor, they will burn out and probably won't work again. |
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:
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
editPigtail 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
editOnce 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
editPower up your Raspberry Pi, log in and go to the desktop. If you need to log in, the default username is pi
and the password is raspberry
. If the desktop still does not appear, type startx
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.
import RPi.GPIO as GPIO, time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
red=11
yellow=13
green=15
GPIO.setup(red, GPIO.OUT)
GPIO.setup(yellow, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
Use File, Save to save this program as
traffic1.py
. Here's what this program is doing:
import RPi.GPIO as GPIO, time
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.
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
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.
red=11
yellow=13
green=15
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.
GPIO.setup(red, GPIO.OUT)
GPIO.setup(yellow, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
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 traffic1.py
. Don't worry it it tells you that the
program already exists – save it anyway.
Lighting up one LED
editLet's start by lighting up the yellow LED. At the bottom of the program, add these lines:
GPIO.output(yellow, GPIO.HIGH)
time.sleep(2)
GPIO.output(yellow, GPIO.LOW)
HIGH turns a light on. LOW turns it off.
Save the program as traffic2.py
.
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:
cd python/traffic
sudo python traffic2.py
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 sudo python traffic2.py
again.
Try changing the program to light up the red or green LED.
Flashing an LED on and off repeatedly
editNow let’s change the program so that the last lines read:
while (True):
GPIO.output(yellow, GPIO.HIGH)
time.sleep(2)
GPIO.output(yellow, GPIO.LOW)
time.sleep(2)
Save this program as traffic3.py
. Go back to the black terminal window and run it with:
sudo python traffic3.py
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
editThe 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:
while (True):
GPIO.output(red, GPIO.HIGH)
time.sleep(5)
GPIO.output(yellow, GPIO.HIGH)
time.sleep(2)
GPIO.output(red, GPIO.LOW)
GPIO.output(yellow, GPIO.LOW)
GPIO.output(green, GPIO.HIGH)
time.sleep(5)
GPIO.output(green, GPIO.LOW)
GPIO.output(yellow, GPIO.HIGH)
time.sleep(2)
GPIO.output(yellow, GPIO.LOW)
That's it! Save this program as traffic4.py
. Go back to the terminal window and run it with:
sudo python traffic4.py
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 traffic5.py
program which uses some advanced techniques to turn off the lights when the program is stopped.
Further adventures
editHere’s some ideas for other things you could do:
Run two sets of lights from one Raspberry Pi
editYou 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
editOn 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?
editDoes 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?
editTry searching for information on the crontab @reboot
command.
Preparation
editThe files for this tutorial can be found at: http://www.cotswoldjam.org/downloads/2015-09/
Please create a python
folder under the home/pi directory, then unzip the files into that
python
directory. This can be done in the LXTerminal:
mkdir python
unzip traffic.zip
Raspberry Pi GPIO Zero Reaction Timer
editTutorial by Andrew Oakley
Public Domain 1 Feb 2016
www.cotswoldjam.org
Introduction
editThis Python programming tutorial, shows you how simple it is to use an LED light and a button, with the new GPIO Zero library.
Getting started
editConventions
editWords you will see on the screen, or that you need to type in, are highlighted like this.
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
editLEDs always need to be connected with a resistor. If you connect them without a resistor, they will burn out and probably won't work again. |
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).
Lighting the LED
editThe circuit
editConnect 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
editPower 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.
from gpiozero import LED
from time import sleep
led=LED(23)
led.on()
sleep(2)
led.off()
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?
editfrom gpiozero import LED
from time import sleep
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.
led=LED(23)
We then create an LED object. We say that the LED is connected to GPIO 23.
led.on()
sleep(2)
led.off()
Turn the LED on, wait for 2 seconds, then turn it off.
Detecting the button
editThe circuit
editNow 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
editIn 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.
from gpiozero import Button
from signal import pause
def press():
print ( "Button PRESSED!" )
def unpress():
print ( "Button unpressed!" )
button = Button(24)
button.when_released = unpress
button.when_pressed = press
pause()
Indentation matters in Python. For example, you must type the two spaces before the word print
. Indentations like these define a block of code – hence the word def
.
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?
editdef press():
print ( "Button PRESSED!" )
def unpress():
print ( "Button unpressed!" )
These are called functions. They define (def
) something that should happen, and they give that action a name. The code is indented to show it belongs to the function. The press()
function says "Button PRESSED!" and the unpress()
function says "Button unpressed!".
button = Button(24)
button.when_released = unpress
button.when_pressed = press
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.
pause()
This tells the computer to wait for events to happen, such as button presses.
Button and LED together
editIn 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 led-button.py
program in the python/reaction folder.
from gpiozero import Button, LED
from signal import pause
def press():
print ( "Button PRESSED!" )
led.on()
def unpress():
print ( "Button unpressed!" )
led.off()
led=LED(23)
led.off()
button=Button(24)
button.when_released=unpress
button.when_pressed=press
pause()
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
editIn 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.
from gpiozero import LED, Button
from signal import pause
from random import uniform
from time import time, sleep
timestarted=None
def press():
global timestarted,led,button
print ( "Reaction time: %.3f" % (time()-timestarted) )
led.off()
sleep(2)
reset()
def reset():
global timestarted,led
sleep(uniform(0.5,3))
led.blink(0.1,0.4,4,False)
led.on()
timestarted=time()
led=LED(23)
led.off()
button=Button(24)
button.when_pressed=press
reset()
pause()
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?
editWe've introduced several new concepts in the reaction program.
We're using a value which we call timestarted
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 timestarted
, 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.
print ( "Reaction time: %.3f" % (time()-timestarted) )
%.3f
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.
sleep(uniform(0.5,3))
The uniform
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.
led.blink(0.1,0.4,4,False)
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
editYou 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:
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install python3-gpiozero wget
mkdir –p ~/python
cd python
wget http://www.cotswoldjam.org/downloads/2016-01/reaction-timercode.zip
unzip reaction-timer-code.zip
exit
The dist-upgrade
may take a while – maybe half an hour if your system hasn’t been updated recently. Don’t worry if apt-get
tells you that you already have packages installed.
Raspberry Pi LEGO® Burglar Alarm
editTutorial 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
editThis tutorial shows you how to make a burglar alarm that sounds when a LEGO® door is opened.
Words you will see on the screen, or that you need to type in, are highlighted like this
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
editBe 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
editDon’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
editPower 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 burglar1.py
program in the python/burglar folder.
from gpiozero import Button
button=Button(4)
button.wait_for_release()
print ("Door opened")
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?
editfrom gpiozero import button
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.
button=Button(4)
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.
button.wait_for_release()
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.
print ("Door opened")
This prints a message to the screen.
Looping the program
editLet's add a loop so that we can keep opening and closing the door.
from gpiozero import Button
button=Button(4)
while (True):
button.wait_for_release()
print ("Door opened")
button.wait_for_press()
print ("Door closed")
Alternatively, you can load in the burglar2.py
program if you don't want to type it in.
The while
command repeats a section of the program; the word True
makes it repeat forever.
Indentation matters in Python. For example, you must type the two spaces in the lines after while
. Indentations like these define a block of code.
Python is picky about punctuation and capitals, too. The initial letter of True
must be a capital, and the line while (True):
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
editChange the program to add in the buzzer. Alternatively, load the burglar3.py
file.
from gpiozero import Button, Buzzer
button=Button(4)
buzzer=Buzzer(23)
while (True):
button.wait_for_release()
print ("Door opened")
buzzer.beep(1,0,1)
button.wait_for_press()
print ("Door closed")
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:
buzzer.beep(1,0,1)
This command has three numbers, called parameters:
- . The number of seconds to sound the buzzer (1)
- . The number of seconds to keep the buzzer quiet (0, zero)
- . The number of times to loop through sound and quiet periods (1, once only)
1,0,1
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
editDownload the sample program files from: http://www.cotswoldjam.org/downloads/2016-04
From Bricklink.com or LEGO® parts specialist | From cpc.farnell.com or electronic components retailer |
---|---|
60623 1×4×6 stud door SW01130 | Small neodymium block magnet |
60596 1×4×6 stud door frame SW00757 | Low voltage glass reed switch |
3032 4×6 stud plate LS03804 | Low voltage piezo buzzer |
SC12901 ×4 female-female DuPont jumpers |
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
editburglar1.py
from gpiozero import Button
button=Button(4)
button.wait_for_release()
print ("Door opened")
burglar2.py
from gpiozero import Button
button=Button(4)
while (True):
button.wait_for_release()
print ("Door opened")
button.wait_for_press()
print ("Door closed")
burglar3.py
from gpiozero import Button, Buzzer
button=Button(4)
buzzer=Buzzer(23)
while (True):
button.wait_for_release()
print ("Door opened")
buzzer.beep(1,0,1)
button.wait_for_press()
print ("Door closed")
Raspberry Pi Star Wars lightsaber
editTutorial 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
editFor 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
edit- ×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
editTo 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 lightsaber.py
, ls1.py
, ls2.py
and ls3.py
. Try altering the code and see if you can make your own colour combinations.
The programs
editls1.py
#!/usr/bin/env python
# Pull in the code libraries that the code will need to use.
from __future__ import division
import RPi.GPIO as GPIO
import time
# Set up the GPIO library to use the numbering of the pin on the board
# i.e. 1 - 40 of the main GPIO connector.
GPIO.setmode(GPIO.BOARD)
# Tell the code the red LED is plugged into pin 35, and that pin 35
# is an output, and set the output to low (i.e. red LED is off)
RED_LED = 35
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.output(RED_LED, GPIO.LOW)
# A new pulse starts every second, and half of that time, the LED is on.
pulse_period = 1
on_fraction = 1/2
# This try and the except below allow the code to stop cleanly by
# capturing the exception from a keyboard ctrl-C.
try:
# Store off when the while loop starts.
start_time = time.time()
# Start looping around the code forever.
while True:
# Work out what time it is since we started, and from that, the
# fraction of the pulse period.
time.sleep(1/1000)
clock_time = (time.time() - start_time) % pulse_period
# For the LEDs, check how far through its fraction of the pulse it
# is and turn the LED on if it's less or off if it's more.
#============================= RED =============================#
if clock_time < on_fraction * pulse_period:
GPIO.output(RED_LED, GPIO.HIGH)
else:
GPIO.output(RED_LED, GPIO.LOW)
# The except here needs to do nothing but has to do something; the pass
# statement means do nothing.
except KeyboardInterrupt as e:
pass
# Finally turn off the LEDs and cleanup the GPIO.
GPIO.output(RED_LED, GPIO.LOW)
GPIO.cleanup()
ls2.py
#!/usr/bin/env python
# Pull in the code libraries that the code will need to use.
from __future__ import division
import RPi.GPIO as GPIO
import time
# Set up the GPIO library to use the numbering of the pin on the board
# i.e. 1 - 40 of the main GPIO connector.
GPIO.setmode(GPIO.BOARD)
# Tell the code the red LED is plugged into pin 35, and that pin 35
# is an output, and set the output to low (i.e. red LED is off)
RED_LED = 35
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.output(RED_LED, GPIO.LOW)
# Tell the code the green LED is plugged into pin 33, and that pin 33
# is an output, and set the output to low (i.e. green LED is off)
GREEN_LED = 33
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.output(GREEN_LED, GPIO.LOW)
# Tell the code the blue LED is plugged into pin 37, and that pin 37
# is an output, and set the output to low (i.e. blue LED is off)
BLUE_LED = 37
GPIO.setup(BLUE_LED, GPIO.OUT)
GPIO.output(BLUE_LED, GPIO.LOW)
# A new pulse starts every second, and half of that time, the LED is on.
pulse_period = 1
on_fraction = 1/2
# This try and the except below allow the code to stop cleanly by
# capturing the exception from a keyboard ctrl-C.
try:
# Store off when the while loop starts.
start_time = time.time()
# Start looping around the code forever.
while True:
# Work out what time it is since we started, and from that, the
# fraction of the pulse period.
time.sleep(1/1000)
clock_time = (time.time() - start_time) % pulse_period
# For the LEDs, check how far through its fraction of the pulse it
# is and turn the LED on if it's less or off if it's more.
#============================= RED =============================#
if clock_time < on_fraction * pulse_period:
GPIO.output(RED_LED, GPIO.HIGH)
else:
GPIO.output(RED_LED, GPIO.LOW)
#============================ GREEN =======-====================#
if clock_time < on_fraction * pulse_period:
GPIO.output(GREEN_LED, GPIO.HIGH)
else:
GPIO.output(GREEN_LED, GPIO.LOW)
#============================= BLUE ============================#
if clock_time < on_fraction * pulse_period:
GPIO.output(BLUE_LED, GPIO.HIGH)
else:
GPIO.output(BLUE_LED, GPIO.LOW)
# The except here needs to do nothing but has to do something; the pass
# statement means do nothing.
except KeyboardInterrupt as e:
pass
# Finally turn off the LEDs and cleanup the GPIO.
GPIO.output(RED_LED, GPIO.LOW)
GPIO.output(GREEN_LED, GPIO.LOW)
GPIO.output(BLUE_LED, GPIO.LOW)
GPIO.cleanup()
ls3.py
#!/usr/bin/env python
# Pull in the code libraries that the code will need to use.
from __future__ import division
import RPi.GPIO as GPIO
import time
# Set up the GPIO library to use the numbering of the pin on the board
# i.e. 1 - 40 of the main GPIO connector.
GPIO.setmode(GPIO.BOARD)
# Tell the code the red LED is plugged into pin 35, and that pin 35
# is an output, and set the output to low (i.e. red LED is off)
RED_LED = 35
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.output(RED_LED, GPIO.LOW)
# Tell the code the green LED is plugged into pin 33, and that pin 33
# is an output, and set the output to low (i.e. green LED is off)
GREEN_LED = 33
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.output(GREEN_LED, GPIO.LOW)
# Tell the code the blue LED is plugged into pin 37, and that pin 37
# is an output, and set the output to low (i.e. blue LED is off)
BLUE_LED = 37
GPIO.setup(BLUE_LED, GPIO.OUT)
GPIO.output(BLUE_LED, GPIO.LOW)
# Each pulse period is 1 second, and each colour is on for a different
# number of thirds of this time.
pulse_period = 1
red_fraction = 1/3
green_fraction = 2/3
blue_fraction = 3/3
# This try and the except below allow the code to stop cleanly by
# capturing the exception from a keyboard ctrl-C.
try:
# Store off when the while loop starts.
start_time = time.time()
# Start looping around the code forever.
while True:
# Work out what time it is since we started, and from that, the
# fraction of the pulse period.
time.sleep(1/10)
clock_time = (time.time() - start_time) % pulse_period
# For the LEDs, check how far through its fraction of the pulse it
# is and turn the LED on if it's less or off if it's more.
#============================= RED =============================#
if clock_time < red_fraction * pulse_period:
GPIO.output(RED_LED, GPIO.HIGH)
else:
GPIO.output(RED_LED, GPIO.LOW)
#============================ GREEN =======-====================#
if clock_time < green_fraction * pulse_period:
GPIO.output(GREEN_LED, GPIO.HIGH)
else:
GPIO.output(GREEN_LED, GPIO.LOW)
#============================= BLUE ============================#
if clock_time < blue_fraction * pulse_period:
GPIO.output(BLUE_LED, GPIO.HIGH)
else:
GPIO.output(BLUE_LED, GPIO.LOW)
# The except here needs to do nothing but has to do something; the pass
# statement means do nothing.
except KeyboardInterrupt as e:
pass
# Finally turn off the LEDs and cleanup the GPIO.
GPIO.output(RED_LED, GPIO.LOW)
GPIO.output(GREEN_LED, GPIO.LOW)
GPIO.output(BLUE_LED, GPIO.LOW)
GPIO.cleanup()
lightsaber.py
#!/usr/bin/env python
# Pull in the code libraries that the code will need to use.
from __future__ import division
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# Tell the code the red LED is plugged into pin 35, and that pin 35
# is an output, and set the output to low (i.e. red LED is off)
RED_LED = 35
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.output(RED_LED, GPIO.LOW)
# Tell the code the green LED is plugged into pin 33, and that pin 33
# is an output, and set the output to low (i.e. green LED is off)
GREEN_LED = 33
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.output(GREEN_LED, GPIO.LOW)
# Tell the code the blue LED is plugged into pin 37, and that pin 37
# is an output, and set the output to low (i.e. blue LED is off)
BLUE_LED = 37
GPIO.setup(BLUE_LED, GPIO.OUT)
GPIO.output(BLUE_LED, GPIO.LOW)
# Each pulse period is 1/100 second, and each colour is on for a different
# number amount of time each time round the loop.
pulse_period = 1/100
red_fraction = 1/500
red_on = 0
blue_fraction = 1/300
blue_on = 0
green_fraction = 1/200
green_on = 0
# This try and the except below allow the code to stop cleanly by
# capturing the exception from a keyboard ctrl-C.
try:
# Store off when the while loop starts.
start_time = time.time()
# Start looping around the code forever.
while True:
# Work out what time it is since we started, and from that, the
# fraction of the pulse period.
time.sleep(1/1000)
clock_time = (time.time() - start_time) % pulse_period
# For the LEDs, check how far through its fraction of the pulse it
# is and turn the LED on if it's less or off if it's more.
# In this case, the fraction changes each time round the loop, so
# the LEDs change their brightness.
#============================= RED =============================#
if clock_time < red_on * pulse_period:
GPIO.output(RED_LED, GPIO.HIGH)
else:
GPIO.output(RED_LED, GPIO.LOW)
red_on += red_fraction
if red_on > 1 or red_on < 0:
red_fraction = -red_fraction
red_on += red_fraction
#============================ GREEN =======-====================#
if clock_time < green_on * pulse_period:
GPIO.output(GREEN_LED, GPIO.HIGH)
else:
GPIO.output(GREEN_LED, GPIO.LOW)
green_on += green_fraction
if green_on > 1 or green_on < 0:
green_fraction = -green_fraction
green_on += green_fraction
#============================= BLUE ============================#
if clock_time < blue_on * pulse_period:
GPIO.output(BLUE_LED, GPIO.HIGH)
else:
GPIO.output(BLUE_LED, GPIO.LOW)
blue_on += blue_fraction
if blue_on > 1 or blue_on < 0:
blue_fraction = -blue_fraction
blue_on += blue_fraction
# The except here needs to do nothing but has to do something; the pass
# statement means do nothing.
except KeyboardInterrupt as e:
pass
# Finally turn off the LEDs and cleanup the GPIO.
GPIO.output(RED_LED, GPIO.LOW)
GPIO.output(GREEN_LED, GPIO.LOW)
GPIO.output(BLUE_LED, GPIO.LOW)
GPIO.cleanup()
Raspberry Pi Python GPIO Zero Distance Sensor
editTutorial 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 gpiozero
library to measure distances.
The kit
editIn 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 Raspberry Pi is a 3.3V device, the HC-SR04 is a 5V device, connecting this up wrong can damage the Raspberry Pi. |
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.
Now, no matter how confident you are that you’ve got it all right, call over a tutor and get your wiring checked. Once you’re given the OK continue below to get programming. |
The program
editPower 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.
#!/usr/bin/python
from gpiozero import DistanceSensor
from time import sleep
sensor = DistanceSensor(echo=21, trigger=20, max_distance=2.0)
while True:
distance = sensor.distance * 100
print("Distance : %.1f" % distance)
sleep(1)
What does the program do?
#!/usr/bin/python
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).
from gpiozero import DistanceSensor
from time import sleep
The from
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 DistanceSensor
from the gpiozero
library which it will use to talk to the sensor and the function sleep
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.
sensor = DistanceSensor(echo=21, trigger=20, max_distance=2.0)
We then create an object we call sensor
using the imported function DistanceSensor
. The parameters that we pass say that the trigger
to invoke the sensor will be on GPIO pin 20; the echo
to listen for the reply will be on GPIO pin 21 and that the maximum distance that should be returned is 2.0 metres.
while True:
This while True:
tells the program to run forever in a loop.
distance = sensor.distance * 100
print("Distance : %.1f" % distance)
sleep(1)
Then we get the current sensor reading by calling sensor.distance
, 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 while True:
makes us go around again.
Additional notes
editThese 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
editThe 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.
So substituting in the values for 5V as the Vin and the two resistors we have used, R1 = 680Ω and R2 = 470Ω we get:
This 2.95V is then safe to connect to the Pi.
A program to interface to the HC-SR04 directly
editIn 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 rpigpio_DistanceSensor.py
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 measure()
:
def measure():
# This function measures a distance
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
elapsed = stop-start
distance = (elapsed * 34300)/2
return distance
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 start
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 start
.
Once GPIO_ECHO is 1 (= high) this first look will stop. At this point start
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 stop
.
Finally when the GPIO_ECHO goes low again the loop exits. At this point start contains the time when the Echo went high and stop
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 distance
value in cm.
Files
editrpigpio_DistanceSensor.py
#!/usr/bin/python
import time
import RPi.GPIO as GPIO
# -----------------------
# Define measure function
# -----------------------
def measure():
# This function measures a distance
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
elapsed = stop-start
distance = (elapsed * 34300)/2
return distance
# -----------------------
# Main Script
# -----------------------
# Use BCM GPIO references instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_TRIGGER = 20
GPIO_ECHO = 21
# Set trigger as output and echo as input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Wrap main content in a try block so we can
# catch the user pressing CTRL-C and call the
# GPIO cleanup function.
try:
while True:
distance = measure()
print("Distance : %.1f" % distance)
time.sleep(1)
except KeyboardInterrupt:
# User pressed CTRL-C, reset GPIO settings
GPIO.cleanup()
gpiozero_DistanceSensor.py
#!/usr/bin/python
# -----------------------
# Import required Python libraries
# -----------------------
from gpiozero import DistanceSensor
from time import sleep
# -----------------------
# Main Script
# -----------------------
sensor = DistanceSensor(echo=21, trigger=20, max_distance=2.0)
while True:
distance = sensor.distance * 100
print("Distance : %.1f" % distance)
sleep(1)
Raspberry Pi Web Server & HTML Tutorial
editTutorial by Andrew Oakley
Public Domain 28 Jan 2017
www.cotswoldjam.org
The Terminal
editStart 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:
sudo apt update
sudo apt upgrade
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.
sudo apt install apache2
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 epiphany
and press
↵ Enter. Epiphany is a simpler browser for slower computers.
In the web browser's address bar, type localhost
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:
hostname
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:
hostname.local
… 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:
hostname -I
(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
editBack in the terminal, enter:
cd /var/www/html
ls -lh
/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.
sudo mv index.html index-old.html
sudo leafpad index.html
A text editor program should pop up, with a blank page. Start typing:
<html>
<head>
<title>My first web page</title>
</head>
<body>
<p>
Hello world
<p>
My name is Andrew
</body>
</html>
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?
edit<html> tells the browser this is the start of a web page; </html> is the end
<head> says this is the start of the header, where the title goes; </head> is the end
<body> is the start of the text of a web page; </body> is the end
<p> is the start of a new paragraph; the closing tag </p> is optional in HTML5
index.html
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:
<p>
<a href="pet.html">My favourite pet</a>
Don’t forget to File, Save, then reload browser.
<a> 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):
ls -lh /home/pi/Pictures/pets
cat.jpg | dog.jpg | guineapig.jpg | hamster.jpg |
Pick a pet (cat, dog, guinea pig, hamster) and copy the picture to the web server directory:
sudo cp /home/pi/Pictures/pets/cat.jpg /var/www/html
Create a new web page with:
sudo leafpad pet.html
<html><head>
<title>My favourite pet</title>
</head><body>
<p>
My favourite pet is:
<p>
<img src="cat.jpg">
</body></html>
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:
sudo apt remove apache2 && sudo apt-get -y autoremove
Advanced exercises
editCreate a CSS file for your webpage
editCascading style sheets (CSS) are files used by websites to change the appearance of the content on each webpage.
Create the styles.css
file just like the corresponding index.html
file.
sudo leafpad styles.css
Type this CSS to alter the <p> tags.
p {
font-weight: bold;
font-size: 16px;
}
Now to add the CSS file to the HTML file so that web browser knows to use it.
<html><head>
<link rel="stylesheet" href="styles.css">
<title>My favourite pet</title>
</head><body>
<p>
My favourite pet is:
<p>
<img src="cat.jpg">
</body></html>
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 styles.css
file to add a class:
p.pet {
font-weight: bold;
font-size: 16px;
}
Then declare the class to the <p> tags.
<html><head>
<link rel="stylesheet" href="styles.css">
<title>My favourite pet</title>
</head><body>
<p class="pet">
My favourite pet is:
<p>
<img src="cat.jpg">
</body></html>
You can try other CSS attributes to style your webpage such as:
font-style: italic;
makes the font italic.margin
adds a margin to seperate the tag from other elements on the page. Usingmargin
on its own will add a margin to all four sides of the tag.color: #F00
changes the colour of the text to red.background-color: #000
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.
Colour | Hexadecimal | RGB | HSL |
---|---|---|---|
Black | #000 | 0, 0, 0 | 0, 0, 0 |
Red | #F00 | 255, 0, 0 | 0, 0, 0 |
Green | #0F0 | 0, 255, 0 | 0, 0, 0 |
Blue | #00F | 0, 0, 255 | 0, 0, 0 |
Cyan | #0FF | 0, 255, 255 | 0, 0, 0 |
Yellow | #FF0 | 255, 255, 0 | 0, 0, 0 |
Magenta | #F0F | 255, 0, 255 | 0, 0, 0 |
White | #FFF | 255, 255, 255 | 255, 255, 255 |
Numerical bases
editA binary number is referred to as a "binary digit", which is abbreviated to a "bit". |
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
Decimal | 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
---|---|---|---|---|---|---|---|---|---|
Binary | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
Hexadecimal | 0 | F | F |
For further information: https://www.mathsisfun.com/numbers/bases.html
Public IP Addresses
editTo 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
editFrom the terminal:
sudo systemctl stop apache2
Reload localhost in the browser. Note the error message - the web server has been stopped.
sudo systemctl status apache2
Shows "Active: inactive (dead)" – it’s not running.
sudo systemctl start apache2
Reload the browser. It works again.
sudo systemctl status apache2
Shows "Active: active (running)"
sudo systemctl status bing-bong-bop
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
editReboot 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:
sudo systemctl disable apache2
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:
sudo systemctl start apache2
or you can reenable it to start automatically every reboot with:
sudo systemctl enable apache2
Removing installed programs
editsudo apt remove apache2
sudo apt-get autoremove
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
editsudo apt update
sudo apt upgrade
…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 apt update
, you can install new software with:
sudo apt install packagename
…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
editby Andrew Oakley - Public Domain Jan 2018
www.cotswoldjam.org
Updating your system
editYou will need a working internet connection. Select the Raspberry menu – Accessories – Terminal. A black box should appear.
sudo apt update
sudo apt upgrade
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!
sudo apt autoremove
sudo apt clean
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.
Installing the zip and unzip tools
editsudo apt update
sudo apt install zip unzip
Connect a USB memory stick and find out what it's called on the system
editInsert 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 df
command.
In our instructions, we are using the name USBNAME so you will need to change this to the actual name of your USB stick. Make sure your get capitals and lower case correct. |
Back up all your files to a USB stick
editThese 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.
cd /home
zip -r /media/pi/USBNAME/pibackup-20180127.zip pi/ -x 'pi/.cache/*'
cd
Note how we used cd /home
to move from the /home/pi
directory to the /home
directory.
This allows us to treat the entire pi directory as a subfolder that we can back up.
We also use the -x
option to ignore the .cache
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 cd
command on its own, to return to our home/pi
directory. We could have done cd /home/pi
which would have done the same thing.
Restore all your files from a USB stick
editInsert 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 (-o
) existing files with the older versions.
cd /home
unzip -o /media/pi/USBNAME/pibackup-20180127.zip
cd
Back up just one folder
editcd
zip -r /media/pi/USBNAME/Documents-20180127.zip Documents/
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:
zip -r /media/pi/USBNAME/minecraft-20180127.zip .minecraft/
Restore just one folder
editcd
unzip /media/pi/USBNAME/Documents-20180127.zip
We didn't use -o
, 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
editAlthough you can use the unzip
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 /home/pi
which you can either type in, or click the pi
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
editDon't remove the USB stick until you have ejected it from the desktop – your computer might still be half-way through writing a file. |
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 umount
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
editEvery 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
editIf 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
editTutorial 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
Mouse to look | 0 to select the sword |
W, S, A, D to move | E to reassign blocks 0-9 |
SPACE to jump | SPACE twice to fly |
Left-click to destroy a block | SPACE twice again to stop flying |
Right-click to create a block | SPACE once while flying to go up |
1-9 to select a type of block | LSHIFT while flying to go down |
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:
from mcpi.minecraft import Minecraft
from mcpi import block
mc = Minecraft.create()
x,y,z = mc.player.getTilePos()
# Change the block under the player's feet to Glass
mc.setBlock(x, y, z-1, block.GLASS.id)