RasPi Magazine - Issue No. 013
RasPi Magazine - Issue No. 013
BUILD
13
CODE
Set up
AirPlay
Speakers
Editor
PiKon
Shooting the Moon with a 3D-printed telescope
Talking Pi
Your questions answered and your opinions shared
Why you need Python 3
Bring your programming skills up to date by finally
letting go of Python 2 and embracing
the better language
Python 3 has been languishing. There have “Momentum is
been many good reasons for this, including a
needed from
lack of dependencies, monolithic code bases
written in Python 2 that are costly to port across, and
the community
also the prevalence of tutorials such as those found in in order to
this magazine that continue to focus on the outdated 2.x successfully
versions, among many other reasons. One of the common make the leap
threads uniting all these reasons not to use Python 3 from Python
is a sense that there aren’t enough people actually 2 to the much,
programming in Python 3 to help spread its adoption. A
much better
few years ago (we’ve had Python 3 for seven now), things
like the lack of dependencies were real inhibiting factors, Python 3”
but the situation has vastly improved since then and some
of these reasons just don’t hold up any more.
So why haven’t people switched yet? Part of the
problem is perhaps down to the dual support of both
Python 2 and Python 3 by its developers, but in any case
there is no real reason nowadays to continue writing code
in the deprecated version of Python. Momentum is needed
from the community in order to successfully make the leap
from Python 2 to the much, much better Python 3, and to
ensure that Python isn’t abandoned altogether in favour of
Ruby or Go, for example.
The adoption of Python 3 by the community is
something that we personally believe in here at RasPi and,
since we regularly write Python tutorials for you, it makes
sense for us practise what we preach. We won’t throw you
into the deep end immediately, but over the coming months
we are going to begin transitioning across to using Python
3 ourselves. When you download your tutorial assets each
issue, keep an eye out for the Python 3 files that we’ll be
adding. For now, though, read through our Python 3 primer
and we’ll get you started with this fantastic programming
language today.
Getting started
Let’s take a look at the new print function
and handling lists
“One of the
There are a load of little changes that have changes made
made their way into Python 3. Depending on the in Python 3
version of Python 2 you’re using, some of these that will cause
changes will be more drastic than others – Python 2.5 and
a stumbling
onwards received some function changes backported to
the code, however there are still some notable differences. block to some
This happened quite a while ago though, so we’ll be is the update
focusing on going from current Python 2 to Python 3. to the print
command”
Say hello
One of the changes made in Python 3 that will cause
a stumbling block to some is the update to the print
command. Before, it was fairly unique as a statement
and not a proper function, allowing you to string together
outputs for debugging or just normal outputs.
You can still do this, but to bring it more in line with the
rest of the way Python works, it’s now a proper function:
print (). You can perform the exact same kind of functions
that you could with the original print, albeit formatted
somewhat differently. To illustrate this, let’s first of all create
a Hello World command. Open up IDLE 3 and type this into
the shell:
print (“Hello World”) Why you need
to change
Very simple. For more complex strings that include variables Python 2 is slowly
and maths, it’s also quite easy to create them as well. For dying. For the past
few years it’s had
the next example we’ll create a variable with a number to very little active
illustrate how it works. Back in IDLE, use the following two development beyond
bug fixes and the odd
commands in the shell: bit of deprecation. We
constantly run into
a = 5 code bits that can be
dealt with very easily
in Python 3, mainly
print (“You should know that ”, a, “ is involved with sorting
lists and databases,
greater than ”, 2*2 , “ every time”, sep=“”) and in general it’s
more in line with the
Python philosophy of
As expected, this creates the sentence: “You should know being easy to read and
that 5 is greater than 4 every time”. We’ve thrown the sep use, as shown with the
changes to things like
argument on the end of the print function; this allows you to print and input.
set what’s used to separate the text and inserted variables. There’s a bit more to
In this case we’ve told it not to add anything, but we could the differences than
what we’ve managed
tell it to add a space and cut down on the length of the line. to show in this article,
however these are
some of the biggest
and most common
functions that are used
in Python, so getting
the very basics down
is important. We’ll
discuss where you can
get more information
about the changes
later on and supply
links to documentation
as well.
Python 3 setup
A few distros will have
Python 3 pre-installed,
but most will have
Python 2.
It’s not difficult to get
the new libraries set
up. In most instances,
you will need to look
for the python3
package in your
On the list system’s software
repos, however in
Standard lists are handled basically the same way in Arch and Fedora it’s
Python 3 as they are in Python 2. The usual list.append() currently listed as
python. You’ll also
and list.remove() commands are still in place, but Python need to install the
3 now includes a couple of new commands to make correct version of
organising them much easier: IDLE, Python’s IDE. This
will be in the repos
under idle3, or failing
list.clear() – this simply removes all the items currently in the that as plain idle if
python3 is python in
list and it replaces del a[:]. your repos.
On some distros, IDLE
list.copy() – this prints out a basic copy of the current list, for both Python 2 and
3 may be installed
similar to if you used print (list). This replaces a[:]. side-by-side. Make
sure you’re using the
right IDLE – it won’t
On the other hand, mappable objects such as dicts work a damage anything, but
bit differently. Common commands such as dict.keys() and it can be frustrating
trying to bug fix code
dict.items() return views instead of lists. These are dynamic when it’s not even
and update as the list’s entries are changed. running properly.
The Code PRINT FUNCTION
#!/usr/bin/env python3 The full function
print(*objects, sep=‘
# The above is a slightly different shebang to let the ’, end=‘\n’, file=sys.
# interpreter know which version of python to use when stdout, flush=False)
# running it from terminal or command line. In previous sep – sep enables
you to change what
# tutorials we have had it end in python2 for just these
is used to separate
# sort of occasions. parts of the output.
By default it’s a space,
but you can change
# Let’s create some variables and lists to play around with:
it to any compatible
character. This can
hello_world = “Hello World!” be used to make
the line shorter, or
include mathematical
hello_list = [“Hello”, “there”, “world”, “!”] operator such as >.
end – how the end of
hello_dict = { “first” : “Hello”, the line is portrayed.
To leave a space rather
“second” : “World”,
than start a new line
“third” : “!” } (which is the default),
use something like
print (x, end = “ ”). Like
# Here’s how we can print them all out, first the normal print:
sep, this needs to be a
string and will not be
print (hello_world) converted into one like
other outputs.
file=sys.stdout – this
# Then print out the entire list in order. The asterisk
completely replaces
# allows for each item to be called individually rather the kind of command
# than the list where you would write
print >>sys.stderr, “an
error”. Construct the
print (*hello_list) string as you would
normally for anything
you’re printing, then
# Finally, print the dictionary
append the file option
like so: print(“fatal
for x in hello_dict: error”, file=sys.stderr).
print (x, “:”, hello_dict[x]) flush – forcibly flushes
the print stream after
execution if True.
Reading input
Now you’ve got the basics down, get up to
speed with using human input and variables
a = input()
“Importing is
Let’s go through this line by line. We import time done in the
so we can run the program at a steadier pace. same way
Importing is done in the same way as Python 2, as Python 2,
and most of the standard modules are still in place:
and most of
import time the standard
modules are
This creates our basic variables – a string for repeating the still in place”
code and a list to store the sentence we’re making in this bit:
repeat = “y”
sentence = []
def textinput():
global sentence, repeat
print (*sentence)
time.sleep(1)
time.sleep(1)
This while loop is the main part of the program, running the
function above and also determining whether to continue
the code or not:
while True:
time.sleep(1)
if repeat == “y”:
textinput()
else:
print (“Goodbye!”)
break
Resources
Want more? Check out these for help and
documentation on Python 3
LinuxQuestions
https://www.linuxquestions.org
Some problems might come down to Linux itself, so as a
last resort you can always check the LinuxQuestions forum
for advice on how to either fix your code or fix your system
to run it properly. Make sure you search for your question
first, in case someone else has come across this problem
(it’s also part of forum etiquette to look it up first before
asking). The folks here will also be able to help you with
your code, but the base of users is slightly smaller than that
of StackOverflow.
PiKon
Mark Wrigley and Andy Kirby take photos of the Moon using
a 3D-printed telescope and the Pi camera module
Tell us how you began your project
Mark Wrigley I run this small company called
Alternative Photonics and like to find out about
new technologies. When Sheffield’s Festival of the Mind
came along I thought of what could we put together in terms
of things that are new and disruptive, and that’s how the
whole project started. The two things I was interested in
were using Raspberry Pis for photography and 3D printing. Mark Wrigley
With 3D printers you’ve got a device in the ballpark of £500, is a member of
putting it amongst the price you’d pay for consumer items, the Institute of
so manufacturing is actually something you can do at home. Physics and holds
There are companies who will print something for you, so a Licentiateship
you send in a design and they’ll produce it. And there are with the Royal
maker communities – Andy runs a group called Sheffield Photographic Society
Hardware Hackers and Makers.
Andy Kirby Sheffield Hardware Hackers and Makers is for
anyone off the street to come along to if they want to hack
and make things. I set it up as part of the original RepRap
project that ran on the Internet quite some years ago [Ed:
RepRaps are 3D printer kits that can print parts for more
RepRaps]. I found that there were quite a few people building
printers who got to a certain point and got stuck, so I set up
this group originally to be a drop-in for people to come along
to and get the help they needed. Andy Kirby was
an early contributor
Andy, what was your role in the PiKon? to the RepRap
Andy I helped Mark pick a 3D printer that was going to be project and runs the
pitched right for his skillset and then, as he was building Sheffield Hardware
up the printer, when he got to bits where he got stuck he’d Hackers and
bring it along to the Hardware Hackers group and say ‘It Makers group
doesn’t do this right’ or ‘I can’t get it to do that’, and we’d
work through the problems together. Once he’d got his
printer going, I worked through the CAD software with
him to see what was available that was open source and
within his capabilities. There are various things you can’t If you like
do with a 3D printer when you design parts, so we had a The Raspberry Pi
conversation about that and I gave him the shortcut to get Foundation website
working parts out quicker. featured a project
that mounts the Pi
How many different parts need to be printed and and camera onto
assembled? a telescope and
Mark There are five printed parts, and then there’s one captures great
piece of white venting duct (which forms the barrel), images:
a couple pieces of Meccano, a small square piece of https://bit.ly/1qTp3Pb
aluminium and the focusing knob. We had a think about
printing the telescope tube but it would take an awful long Further reading
time to print sections that were long enough, so we went If you’re interested
for something that was reasonably available. We had lots in astrophotography
of discussions about cardboard tubes and so on, and we and developing
came across a bit of white venting duct that worked. software for
PiKon, check out
How does the PiKon work? these astronomy
Mark Most telescopes work on the principle that you have packages:
some sort of object lens or mirror which forms an image https://bit.ly/100wj65
and then you use an eyepiece to examine that image,
so it’s usually what’s termed as a virtual image. With the
PiKon, what we’re doing is using the objective device, in
this case a 4.5-inch (335mm) mirror, to form an image and
then placing the Raspberry Pi camera without its lens – so
just a sensor – where the image is formed. So effectively,
instead of using an eyepiece we’re examining the image
electronically by placing the Raspberry Pi sensor there,
and the sensor is suitably small so we’re able to examine
a fairly small area of the image.
“It occurred
01 Order your items to our expert
If you haven’t already got them in your Raspberry Pi that, together
collection, you will need to order all of the items from with Screenly,
the “Project Essentials” list at the top-right. The HDMIPi the HDMIPi
is currently only compatible with Model B of the
would make the
Raspberry Pi, although an upgrade kit that makes
it compatible with the Models B+, A+ and 2B was perfect home-
recently released. Pretty much any USB keyboard brew digital
will work with Screenly, including wireless ones, so you photo frame”
do not need to worry about a mouse for this tutorial
as it will all be done from the command line. Finally, a
speaker is only necessary if you intend to play videos
with sound from the display.
Above The reverse
view of HDMIPi,
02 Assemble your HDMIPi showing GPIO and
The HDMIPi comes as a do-it-yourself kit rather than a connector cutouts
polished product. Not only does this make it cheaper
for you to buy, but it also gives it a more hack-like feel
in its Pibow-esque acrylic layer case. It is not hard to
assemble, but in case you get stuck there is a fantastic
assembly video here: http://hdmipi.com/instructions.
“There is a
01 Set up Wi-Fi way to send
Connect everything to your Raspberry Pi and power it audio from
up. Log in to the Raspbian system with the username PulseAudio
pi and the password raspberry. Then, make sure your to AirPlay
wireless interface is working by typing iwconfig. You
receivers, as
should see an entry there for wlan0. If you look in /etc/
network/interfaces, there should already be a section
well as an
that looks like this: application for
allow-hotplug wlan0 Android called
iface wlan0 inet manual AirAudio. Sadly,
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf the Android
iface default inet dhcp application
If it doesn’t, then add it at the end. This configuration
requires root”
makes the wireless adapter connect once the network
in wpa_supplicant.conf is in range. This means the only
thing left to do is to edit the wpa_supplicant.conf file,
which needs your SSID (wireless network name) and
the passphrase. You can do this with:
sudo bash -c “wpa_passphrase my_network “We need
my_ passphrase >> /etc/wpa_supplicant/wpa_ to compile
supplicant.conf”
Shairport,
…which will result in a wpa_supplicant.conf file that
looks like this: but before
ctrl_interface=DIR=/var/run/wpa_supplicant we can do
GROUP=netdev that we have
update_config=1 to install its
network={ dependencies
ssid=“my_network”
first”
#psk=“my_passphrase”
psk=17661426f1af334010ad2058d8b8f583ec501....
}
The easiest way to get things going is to reboot the Pi
with sudo reboot. Once your Pi is back up, check that
you have an IP address on wlan0 with ip addr.
06 A final reboot
After this reboot, Shairport should start automatically. To
test it out, get your client and see if it can find the PiPlay.
On an iOS device, slide up from the bottom to bring up
Control Center, tap the AirPlay button and select PiPlay.
It might take a couple of seconds to buffer, but once it’s
playing it should be fine.
…and change iface eth0 inet dhcp to iface eth0 inet static.
03 Set up a static IP
Add the following lines under the iface line with your
relevant details:
address 192.168.1.[IP]
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.[Router IP]
04 Ready to install
You’ll need to grab the public keys for the software
we’re going to install by using the following commands.
The first will take just a moment to download the
software, while the other quickly installs it:
$ wget debrepo.krenel.org/raspctl.asc
$ cat raspctl.asc | sudo apt-key add -
“Now the
software is
installed you
06 Access your Raspberry Pi can start to
Now the software is installed you can start to access
your Raspberry Pi from anywhere on your network. To
access your
do this type the following into your address bar, with Raspberry
the IP being the one we set up earlier: Pi from
anywhere on
http://[IP]:8086 your network”
07 Change your password “Go to
The default username and password is admin for both Commands on
fields, and you should make sure to change that before the top bar to
doing anything else. Go to Configuration along the top bar
begin creating
and find the Authentication field at the bottom of the page.
Input the original password (admin), followed by your new commands to
passwords. The username will remain as admin. run. You’ll need
to add a class,
a name for
the command
and the actual
command
itself”
08 First command
Go to Commands on the top bar to begin creating
commands to run. Here you’ll need to add a class – a
user-defined way to filter your commands that won’t
affect the way it’s run – a name for the command
and the actual command itself. The commands won’t
necessarily run from the pi user unless you tweak the
config files.
09 More functions
The web interface has a few extra functions apart from
running commands, such as the ability to view the
webcam and connect to radio services. Play around
to see what suits you. Updating the software every so
often will also help you make sure it keeps working.
Optimising code for
your Raspberry Pi
In any low-resource system, you need to make
maximum use of what is available. Profiling helps
import cProfile
You can now run Python code through the profiler. The call
requires the same format you would use if you were to
‘exec’ some code. The easiest thing to do here is to have
your code packaged as a function. As a quick and dirty
example, let’s write a function that calculates the cube of
all of the integers up to some limit:
def looper(size):
for a in range(size): “You should
a*a*a
notice that the
You can then run this function inside the profiler using time values
this command: are given to
a precision of
cProfile.run(‘looper(1000000)’)
0.001 seconds.
The output you get looks like that in Fig. 01, below. This is because
You get six columns of output from a profile run. The the profiler only
first column is the number of times that particular function records time
is called. The second column is the total amount of time to within the
used by that function, minus any time spent in calls to
nearest clock
subfunctions. You should notice that the time values are
given to a precision of 0.001 seconds. This is because the
tick”
profiler only records time to within the nearest clock tick.
On most machines today, the clock tick is set to 10ms.
In most cases, this should be good enough. If you are
worrying about functions that take less than 10ms to run,
you probably need to be working closer to the metal then
you can get with Python. The third column is the amount
of time used per call. The fourth and fifth columns give
the same times, except they include the amount of time
Fig. 01
4 function calls in 0.878 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.668 0.668 0.878 0.878 <ipython-input-......
1 0.000 0.000 0.878 0.878 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method ‘disable’ of....
1 0.210 0.210 0.210 0.210 {range}
spent in calls to subfunctions. The last column is the
location of the relevant function call. Some of these can get
quite long, so in our example the longer lines have been
truncated a bit for space. You may also see two numbers
for a given line in the first column. These cases are when
a particular function is recursive. In the code listing, you
can see a classic factorial function and the output from a
profiling run.
While this is great when playing around in an
interactive session, what can you do if you want to keep
the profiling data for later analysis? The run function of
cProfile will accept a second parameter containing a
filename where all of the profiling data will get saved off
to. So you could call:
cProfile.run(‘myfunction()’, ‘prof_data’)
The profiler will then save all of the collected data into the
file ‘prof_data’. Now you can have a permanent record
of your progress in trying to optimise your code. You can
use the pstats module to load the data and play around
with it. You could load the data, strip any extraneous path
information from the module names and sort it with:
import pstats
p = pstats.Stats(‘prof_data’)
p.strip_dirs().sort_stats(-1).print_stats()
This will run the profiler on the file ‘myscript.py’ and save
the profiling data to the file ‘prof_data’.
The second popular profiling module is profile. This
module provides the same interface as cProfile, but
is written purely in Python. This means that there is a
good deal more overhead involved, so the run time for a
profiling run may be significant. But, since it is pure Python,
it is open to being modified easily. This is a great help
if you wanted to build more functionality on top of that
provide by profile. Also, profile will work on systems where
cProfile is not implemented. The one that you decide to
use will depend on your specific needs.
With the information that we have covered this issue,
you should have the tools you need to be able to figure
out where to apply your optimisation skills. So now, you
should have no excuses for having slow and bloated
code. Go forth and optimise!
Is the Raspberry
Pi waterproof? Absolutely not! It’s a bare circuit
I want to use it board and it’s very susceptible
outside. to shorts and corrosion from the
Claire via elements. There are solutions you
Facebook can use to waterproof it, such as
special PICE waterproof cases,
and you could build your own rain-proof
enclosure fairly easily (as long as you don’t
plan to submerge it, that is). The Pi camera
can also fit in the PICE if you’re looking to do
video as well.
How durable is
the Raspberry The Raspberry Pis are made
Pi? very well – although the actual
Hywel via cost of them is quite cheap, the
Twitter parts have not been skimped
on. As the Pis are sold by a
charity, they don’t technically
need to make a profit. The board itself, with You can score
a decent amount of care, will be fine for absolutely anything on
Just A Score. We love
many years. As for being in more physical to keep an eye on free/
environments with a lot of movement, it’s libre software to see
physically quite robust and won’t break very what you think is worth
downloading…
easily, but we’d recommend testing before
using it in such strenuous environments. 10
LinuxUserMag scored 10 for
Keybase
PROGRAM