0% found this document useful (0 votes)
38 views

161 - EbookThe Python Book - The Ultimate Guide To Coding With Python (PDFDrive)

Uploaded by

hackergenoma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

161 - EbookThe Python Book - The Ultimate Guide To Coding With Python (PDFDrive)

Uploaded by

hackergenoma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

6TF1ZUIPOXJUI1J

Above Left MinecraftPi API works on multiple


languages - look out for Python in this tutorial
Above Right Make use of the module to

Use the setBlocks function to set a program games, movements and more

number of blocks simultaneously


13 getPos
Let’s start out with a simple operation with the API
– finding your location. Knowing exactly where the player
Now, when you activate this script when
playing the game, you should notice that
your character will drop a block of stone
Enter the Kano
If you’ve got a young Minecraft addict
is in the game world is a surprisingly powerful and useful every second at your current location. in your house that isn’t quite ready
ability in Minecraft Pi. You can use it to help you do lots of You should also consider making use of to try out Python scripting, there is
things, including setting blocks near (or under) the player and the setBlocks function to set a number another avenue for you. Kano OS
triggering events (like finding specific locations). Below we’ll of blocks simultaneously using the start is a new operating system for the
find the player location and set it to the variable my_pos and co-ordinates and the end co-ordinates – Raspberry Pi designed for younger
prove that it works by printing to the chat window. this can help you make bigger structures. children. Integrated into the OS is
a modified version of Minecraft Pi,
from mcpi.minecraft import Minecraft
from mcpi import block
import time
15 Teleport Steve
So far we’ve read the location of
the player and used it in the game, let’s
which uses a Scratch-like visual
programming interface. It allows you
to snap blocks together to manipulate
finish off by manipulating the player’s the Minecraft world in much the same
mc = Minecraft.create() location using the setPOS method. In the way as we have demonstrated here.
mc.postToChat(ŎMinecraft API Connectedŏ) following script we’re going to draw the You can learn more at
while True: player back to the origin point, assuming www.kano.me/downloads
my_pos = mc.player.getPos() they’ve wandered off and got lost:
mc.postToChat(ŎMy position is:ŏ + str(my_pos))
time.sleep(1) from mcpi.minecraft import Minecraft
from mcpi import block

14 setBlock
The next most common action is setting a block to a
certain type. You can find the full list of available blocks in the
import time

mc = Minecraft.create()
mcpi folder in a script called ‘blocks.py’. We can append to our mc.postToChat(ŎMinecraft API
script in Step 13 by dropping a particular block type in our wake Connectedŏ)
as we walk around the game world. After the ‘mc.postToChat’
line in our previous script add: mc.setBlock((my_pos), block. mc.player.setPos(0, 10, 0)
STONE) so the while loop section of the script now looks like this:
If you wanted to drop the player from a
mc.postToChat(ŎStone path mode!ŏ) great height instead, you would change
while True: the Y co-ordinate to a large positive
my_pos = mc.player.getPos() number. For example:
mc.setBlock((my_pos), block.STONE) Above The Minecraft Python module allows
time.sleep(1) mc.player.setPos(0, 65, 0). you to create all materials any way you wish

5IF1ZUIPO#PPL161
Resources
Breadboard & wires
16x16 LED Matrix
2x 74HC238
2x 74HC244
16x 220 Ohm Resistor
Source code: FileSilo.co.uk

Build a complex LED matrix


LED Matrix display systems find use everywhere from gaudy
kebab shops to impressive steampunk-styled systems

Driving LEDs in an efficient fashion is a science of its own.


The common availability of single-board computers has put
the necessary technology within reach of everyone.
01 Think about LEDs
Standalone LEDs are primitive – they light up once
current flows through them. Driving a few LEDs is as easy as
When dealing with LED displays, two different systems connecting them to GPIO pins along with a resistor. Sadly, this
must be considered. We will focus on traditional matrix- method becomes wasteful once more than a few of them get
based systems made up of one or more LEDs. Their involved – driving 16 diodes ties up 16 pins.
affordable nature makes them ideally suited to classic display
applications: they communicate currency prices, provide
stock-brokers with updates from the trading floor and have
even been used as basic displays for primitive oscilloscopes.
02 Arrange your diodes
Methods were devised to reduce the number of pins
needed. Matrix-based systems are resilient to individual
Finally, we will also provide you with an overview of diode failures, and provide a pin-to-LED ratio of n=(n/2)^2. The
electronic basics. This tutorial is a bit more advanced than the following steps assume a 16x16 LED matrix which is made
ones we usually run in this section of the magazine, and it’s up according to Figure A. Since LEDs permit current in only
also worth noting that we’re going to be programming with C one direction, you can enable a single LED by bringing the
rather than Python. Follow along using the code listing annos. corresponding pins high and low.

162 The Python Book


Use Python with Pi

Full code listing


Step 12 #include “€œmmapGpio.h”
Our LED model has a #include <unistd.h>
#include <stdio.h>
total of 32 inputs, which GHºQH3,1$

overwhelms older GHºQH3,1$


GHºQH3,1$
GHºQH3,1$
versions GHºQH3,1&6
GHºQH3,1&6
Figure A
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'
GHºQH3,1'

Step 07 void VHW$GGUHVV(unsigned FKDU _which, mmapGpio*BZKHUH


{
if(_which&
{
BZKHUH->ZULWH3LQ+LJK 3,1$ 
}
else
{
BZKHUH->ZULWH3LQ/RZ 3,1$ 
}
if(_which&
{
Above The extended version of this schematic is inside FileSilo.co.uk
BZKHUH->ZULWH3LQ+LJK 3,1$ 
– just sign in and download }
else

03 Harness the MUX {


Our LED module has a total of 32 inputs, which BZKHUH->ZULWH3LQ/RZ 3,1$ 
overwhelms older versions of the RPi. The first way to restrict }
their number comes in the shape of the 74HC238, a component
if(_which&
described as a 3-to-8 line decoder/demultiplexer. Its function is {
described in the Figure B image on the next page. BZKHUH->ZULWH3LQ+LJK 3,1$ 
}
else

04 Separate concerns
Chip two goes by the name of 74HC244, which is
described as an octal buffer with tri-state capability. Tri-State
{
BZKHUH->ZULWH3LQ/RZ 3,1$ 
}
outputs can physically disconnect themselves from the bus
if(_which&
line. This permits you to tie their outputs together without
{
fear of short circuits. As long as all but one chip are in tri-state
BZKHUH->ZULWH3LQ+LJK 3,1$ 
mode, no current can flow between high and low output pins. }
else

05 Round them up
Four GPIO pins control the enabled display ‘line’.
Three pins configure the address which is to be emitted,
{
BZKHUH->ZULWH3LQ/RZ 3,1$ 
}
while the signal emitted from the fourth pin is connected to }
the activity inputs. This ensures that but one IC is active. The
Step 08 void VDIHO\6HW5RZ(unsigned FKDU _which, mmapGpio*BZKHUH
74HC244 ensures that but one of the two groups is active.
{
BZKHUH->ZULWH3LQ+LJK 3,1&6 

06 Configure the pins


We used a library from Hussam Al-Hertani’s
Hertaville blog (hertaville.com/2014/07/07/rpimmapgpio).
BZKHUH->ZULWH3LQ+LJK 3,1&6 
if(_which==
{
The first step involves setting output functions. As the GPIOs BZKHUH->ZULWH3LQ/RZ 3,1&6 
are set to outputs, the tri-state feature might connect the }
internal state to the output pins of the IC. This could lead to else
internal shorting if the output is not turned off. {

The Python Book 163


Use Python with Pi
Figure B
Full code listing
Step 08 _where->writePinLow(PINCS1);
}
}

Step 11 void setData(unsigned char _which, mmapGpio* _where)


{
if(_which&1)
{
_where->writePinHigh(PIND0);
}
else
{
_where->writePinLow(PIND0);
}
if(_which&2)
{
_where->writePinHigh(PIND1);
}
else
{
_where->writePinLow(PIND1);
}

07 Power the MUX


Create a convenience function taking an address
ranging from zero to 15. It is converted into pin outputs for our
if(_which&4)
{
3-to-8-demultiplexer. The effect of this is that all but one of _where->writePinHigh(PIND2);
the sixteen rows is to be supplied with energy. }
else
{
08 Select a row
In the 74HC244, we first disable both units and proceed
to turning on the one which is needed. This sequence prevents
}
_where->writePinLow(PIND2);

if(_which&8)
ghosting during the switching process. {

09 Do the main loop


The outer part of the loop consists of logic that
manages the addressing of the individual rows. Our program
}
else
_where->writePinHigh(PIND3);

must flash the individual LED groups one after another using {
the building blocks described in the next step. _where->writePinLow(PIND3);
}
if(_which&16)

10 Complete the loop


Writing out data is accomplished in a sequence of three
commands. We select the row, configure the column and then
{
_where->writePinHigh(PIND4);
}
write out the data bits that are to be displayed. A small pause else
is observed in order to give the LEDs some time to ‘burn into’ {
the viewer’s eyes.
}
_where->writePinLow(PIND4); LED
if(_which&32) stripes
{
_where->writePinHigh(PIND5);
} Two versions of LED
strips are offered.
else
‘Primitive’ ones are
{ based on analogue
_where->writePinLow(PIND5); technology. In it, an
} entire strip of diodes
if(_which&64) has the colour set
{ by the three input
pins. Systems such
_where->writePinHigh(PIND6); as the mega-display
} shown in the left-
else hand image require
{ the use of the
_where->writePinLow(PIND6); digital version. They
are based on the
} concept of the shift
if(_which&128) register. Your system
{ inputs individual
_where->writePinHigh(PIND7); colour values which
} are then pushed on
Above Digital LED matrices like this one give you far more control over else along the strip.
each individual ‘pixel’ in the display

164 The Python Book


Use Python with Pi

Full code listing Full code


{ schematic&
_where->writePinLow(PIND7); s
} FileSilo.c
o.uk
}

Step 06 int main(void)


{
mmapGpio rpiGpio;
//Set outputs
rpiGpio.setPinDir(PINA0,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA1,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA2,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA3,mmapGpio::OUTPUT);
//TURN OFF ASAP!
rpiGpio.setPinDir(PINCS0,mmapGpio::OUTPUT);
rpiGpio.writePinHigh(PINCS0);
//TURN OFF ASAP!
rpiGpio.setPinDir(PINCS1,mmapGpio::OUTPUT);
rpiGpio.writePinHigh(PINCS1);
rpiGpio.setPinDir(PIND0,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND1,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND2,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND3,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND4,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND5,mmapGpio::OUTPUT);
Above This is the full schematic of the LED matrix that we’re working rpiGpio.setPinDir(PIND6,mmapGpio::OUTPUT);
with here (you can also view it at its full size on FileSIlo) rpiGpio.setPinDir(PIND7,mmapGpio::OUTPUT);

11 Energy control
LEDs light up if current flows through them. SetData pulls
the pins of the 74HC244 low to ensure that the energy supplied Step 13
unsigned char dataStore[2][16];

for(int j=0;j<2;j++)
from the 74HC238 can flow through the diode. {
for(int k=0;k<16;k++)
{
12 Avoid GPIO trouble
The Raspberry Pi Foundation has a tendency to change
the layout of the expansion header regularly, a habit which
}
dataStore[j][k]=64;

}
professional manufacturers of process computers abhor.
It’s recommended to handle the mapping between pins and Step 09 int blockCounter=0;
functions via a set of defines. Our code is optimised for a int rowCounter=0;
Rev2 Raspberry Pi with a ‘short’ header – 40-pin variants will while(1)
require readjustments making sure the physical pin numbers {
correspond to the logical GPIO numbers. blockCounter++;
if(blockCounter==16)
{
13 Add example data
Test the code by setting the datastore to a value of your
choice. Setting 64 to all fields will disable one row in each part
if(rowCounter==0)
{
blockCounter=0;
of the display. rowCounter=1;
}

14 Kick it off
Check all connections between the planar and the
single-board computer, and proceed to starting the compiled
else
{
blockCounter=0;
app. Don’t forget to use the sudo command – direct memory rowCounter=0;
}
access is restricted to root in order to prevent apps from
}
causing havoc in the physical memory. Users are accustomed
to this, so requiring them to put a sudo in front of the Step 10 safelySetRow(rowCounter, &rpiGpio);
command doesn’t cause concern. setAddress(blockCounter, &rpiGpio);
setData(dataStore[rowCounter][blockCounter], &rpiGpio);

15 Notice a flicker
Sharp-eyed readers will notice an occasional flicker
where one line appears brighter than the others. This is
usleep(50);

}
caused by the stalling of the program – if the kernel does
return 0;
other work, the switching routine can’t run. We could solve
}
this problem by using a real-time Linux kernel.

The Python Book 165


166 The Python Book
Use Python with Pi

Raspberry Pi
Car Computer
Make your own touchscreen navigation
system that gives directions, local
weather reports and plays music
Cars are getting clever. These days, with smart navigation
interfaces built into new cars, you don’t need to go out and
buy yourself a TomTom to get help with directions. But if
you’ve got a Raspberry Pi then you don’t even need to buy
that – let alone a new car!
In this project we will show you how to build your own
car computer with your Pi, a quality touchscreen like the
9-inch model from SainSmart that we’re using here, and a
few other bits like a GPS module and USB 3G modem. Your
CarPi will be able to use open source navigation software
Navit to show your route map on screen, plus speech
synthesis to read out directions, and it will also be able to
check your location and give you weather reports. It’ll work
as a music player too, of course.
It’s an ambitious project, but you will gain a solid
understanding of custom-made interfaces, navigation
software and geolocation data, touchscreen calibration,
speech synthesis and more. While you don’t have to use
the same SainSmart screen as us, we do recommend it for
this project as it is one of the few large touchscreens out
there for the Pi. There are more improvements at the end
too, so check the components list, make sure you’ve got
everything and let’s get started!

The Python Book 167


03 Install navigation software
Begin to install the Navit navigation software by entering:

sudo apt-get install navit gpsd gpsd-clients espeak


Above We’re using sudo nano /etc/default/gpsd
Adafruit’s excellent set START_DAEMON=“true”
GPS Breakout kit
here: bit.ly/1G8X2gw
…and set:

DEVICES=”/dev/ttyAMA0”

01 Basic configuration
Boot up your Raspberry Pi and expand the filesystem
using raspi-config. Go to Advanced Options and disable the
Start the GPS daemon with:

Serial connection – you’ll need this to talk to the GPS module sudo /etc/init.d/gpsd start
later. In raspi-config, enable X at boot as the pi user. Say Yes to
reboot. Once rebooted, ensure your packages are up to date with: You can check it’s working by looking at the GPS data with:

sudo apt-get update cgps -s


sudo apt-get upgrade

04 Connect the screen


The SainSmart screen doesn’t come with any written
instructions. Instead there is a YouTube video on their website
with details about how to put it together: bit.ly/1DF6eJJ. The
important part is that the DC power supply should be 12V.

05 Set the screen resolution


We will have to force the correct resolution (1024x600)
for the screen by editing /boot/config.txt with sudo. To do so,
add the following options:

framebuffer_width=1024
framebuffer_height=600
hdmi_force_hotplug=1
hdmi_cvt=1024 600 60 3 0 0 0
hdmi_group=2
hdmi_mode=87

For the changes to properly take effect you will need to reboot
with sudo reboot.

02 Connect GPS module


Solder the pin headers onto the Adafruit GPS module.
06 Download kernel source
To start the touchscreen, you need to compile an
extra kernel module to support it. The program rpi-source
You can also solder the battery connector which is used to keep (github.com/notro/rpi-source/wiki) will find the source of
the device partially active, giving a faster fix. You only need to use your kernel. Install rpi-source with:
4 pins: 3.3V, ground, serial transmit and serial receive. Power the
Pi off again before connecting anything. sudo wget https://raw.githubusercontent.com/notro/
As we are using GPS, the antenna will have to go outside or rpi-source/master/rpi-source -O usr/bin/rpi-source
under a window to gain signal. Connect the antenna to the board && sudo chmod +x /usr/bin/rpi-source && /usr/bin/
and power everything back on. The light on the GPS module will rpi-source -q -tag-update
flash frequently while finding a fix. Once it has one, it will blink
every 15 seconds. Then run rpi-source to get the source of the running kernel.

168 The Python Book


Use Python with Pi

07 Update GCC
Recent Raspberry Pi kernels are
compiled with GCC 4.8. Raspbian only
#!/usr/bin/env python2
comes with 4.6 so you will have to install
4.8 to continue with the following steps.
import os, sys, requests, pygame
Do this by entering:
from gps import *
from pygame.locals import *
sudo apt-get install -y gcc-4.8
g++-4.8 ncurses-dev class WeatherClient:
apikey = “7232a1f6857090f33b9d1c7a74721”
Then you have to set GCC 4.8 as
the default:
@staticmethod
def latlon():
sudo update-alternatives gpsd = gps(mode=WATCH_ENABLE)
--install /usr/bin/gcc gcc /usr/
bin/gcc-4.6 20 # Needs better error handling
sudo update-alternatives try:
--install /usr/bin/gcc gcc /usr/ while True:
bin/gcc-4.8 50 report = gpsd.next()
sudo update-alternatives if report[‘class’] == ‘TPV’:
--install /usr/bin/g++ g++ /usr/ gpsd.close()
bin/g++-4.6 20 return report[‘lat’], report[‘lon’]
sudo update-alternatives except:
--install /usr/bin/g++ g++ /usr/ return None, None
bin/g++-4.8 50
@staticmethod
def usefuldata(j):
08 Pick the module to compile
Rpi-source puts the kernel
source in a folder called ‘linux’. To
# Returns a string of useful weather data from a LOT of json
d = j[‘data’][‘current_condition’][0]
choose the USB Touchscreen Driver,
out = “Now - Temp: {0}C, Feels Like: {1}C, Description: {2}\n”\
enter the following:
.format(d[‘temp_C’],
d[‘FeelsLikeC’],
cd linux d[‘weatherDesc’][0][‘value’])
make menuconfig
Device Drivers -> Input device hourly = j[‘data’][‘weather’][0][‘hourly’]
support -> Generic input layer hour_count = 1
(needed for keyboard, mouse, for h in hourly:
…) -> Touchscreens (press space out += (“+{0}hr - Temp: {1}C, Feels Like: {2}C, Chance of Rain:”
to include) -> USB Touchscreen “ {3}%, Description: {4}\n”)\
Driver (press M to make module) .format(hour_count,
h[‘tempC’],
Once you’ve done that, you then need
h[‘FeelsLikeC’],
to make sure you save your changes as h[‘chanceofrain’],
‘.config’ and run scripts/diffconfig to see h[‘weatherDesc’][0][‘value’])
the differences. hour_count += 1

# Rstrip removes trailing newline


09 Compile and install
the module
Now you need to compile and install the
return out.rstrip()

module. Do so by entering: @staticmethod


def update():
make prepare errstr = “Error getting weather data”
make SUBDIRS=drivers/input/
touchscreen modules lat, lon = WeatherClient.latlon()
sudo make SUBDIRS=drivers/input/ if lat == None or lon == None:
touchscreen modules_install return errstr
sudo depmod
api_req = (“http://api.worldweatheronline.com/free/v2/weather.ashx”
If you unplug and reconnect the “?q={0}%2C{1}&format=json&key={2}”).format(lat, lon,
touchscreen, it should work fine but it WeatherClient.apikey)
will probably need calibrating. r = None

The Python Book 169


Use Python with Pi
SainSmart’s The screen
9-inch HDMI/VGA control panel that
touchscreen (bit. comes with the
ly/1Ciu4H9) has a SainSmart screen
fantastic display enables you to
and is perfect easily change the
for all sorts of display settings
Pi projects (i.e. brightness,
contrast, etc) as
well as the input
(i.e. HDMI, VGA,
AV1, etc)

As well as the main


controller board,
Adafruit’s Ultimate the touch screen
GPS Breakout kit is connected to
provides Navit a four-line USB
and the weather controller which
function with the then plugs into the
location data that Pi’s USB port
they require

10 Calibrate the touchscreen


At this point, you can easily calibrate the touchscreen by
entering the following:
11 Download maps
Navit needs maps; download them from maps.navit-
project.org. You can either use the web browser on the Pi or
download the map from another machine and copy it using
cd /etc/X11 scp. Use the predefined area option to select where you live.
sudo mkdir xorg.conf.d The smaller the area that you pick, the less data you will have to
cd xorg.conf.d process. Here the UK has a map size of 608 MB. Now move the
sudo nano 99-calibration.conf map to the navit folder:

…with the following content: mkdir -p /home/pi/.navit/maps


mv /home/pi/Downloads/$your_map /home/pi/.
Section “InputClass” navit/$country.bin
Identifier “calibration”
MatchProduct “eGalax Inc. USB TouchController” For example:
Embed Option “SwapAxes” “1”
the screen Option “InvertX” “1” mv /home/pi/Downloads/osm_bbox_-9.7,49.6,2.2,61.2.bin
EndSection /home/pi/.navit/maps/UK.bin

We’ve looked at
the PiTFT and the
HDMIPi before,
but the SainSmart
Invert X actually inverts Y because the axes have been swapped
around. Reboot again for these changes to occur. Now the
calibration is roughly correct, download an input calibrator that
12 Navit configuration
Sudo-edit /etc/navit/navit.xml with your favourite
editor. Search for openstreetmaps. Now disable the sample
touchscreen Adafruit have packaged already. map above, enable the openstreetmap mapset and set the
we’re using here is
uniquely suited to data variable to where you just moved your map. In this case
many embedded wget http://adafruit-download.s3.amazonaws.com/ it looks like this:
projects. It’s larger xinput-calibrator_0.7.5-1_armhf.deb
than the PiTFT but
also without the
sudo dpkg -i xinput-calibrator_0.7.5-1_armhf.deb <!-- Mapset template for openstreetmaps -->
large bezels of the DISPLAY=:0.0 xinput_calibrator <mapset enabled=“yes”>
HDMIPi – and it’s <map type=“binfile” enabled=“yes” data=“/home/
incredibly thin –so
it’s the kind of thing
DISPLAY=:0.0 is useful because you can run the program from pi/.navit/maps/UK.bin”/>
that is really useful any terminal (including an SSH session) and have it appear on </mapset>
for installation the touchscreen. Touch the points on the screen as prompted.
projects, whether Once the program is finished, you should get an output that is Then search for osd entries similar to:
that’s something as
simple as a photo similar to the following:
slideshow in a real <osd enabled=“yes” type=“compass”/>
picture frame or a Option “Calibration” “84 1957 270 1830”
home automation
control interface …and enable the ones you want – we recommend enabling
embedded into a Add it to the ‘99-calibration.conf’ file that we created earlier them all. You may want to zoom in closer than the default map
cupboard door. just below the other Option entries. layout. A zoom value of 64 is useful.

170 The Python Book


Use Python with Pi

13 Sound configuration
Before configuring speech
support for Navit, configure the external
Full code listing
try:
sound card. You have to stop the
r = requests.get(api_req)
Broadcom module from loading and
except requests.exceptions.RequestException as e:
remove some Raspberry Pi-specific ALSA
return errstr
(Advanced Linux Sound Architecture).
To do this, sudo-edit /etc/modprobe and
return WeatherClient.usefuldata(r.json())
comment out (i.e. prefix with a #):
class CarLauncher:
snd-bcm2835
def __init__(self):
pygame.init()
Then run:
pygame.mixer.quit() # Don’t need sound
screen_info = pygame.display.Info()
sudo rm /etc/modprobe.d/alsa*
self.screen = pygame.display.set_mode((screen_info.current_w,
screen_info.current_h))
Reboot for the changes to take effect.
pygame.display.set_caption(‘Car Launcher’)
Use alsamixer to set the volume on the
self.titlefont = pygame.font.Font(None, 100)
if it’s too quiet.
self.wfont = pygame.font.Font(None, 30)
self.w_text = None # Weather text
14 Download a voice
The speech synthesis software
needs a voice and a proprietary
def clean_background(self):
background = pygame.Surface(self.screen.get_size())
binary. You can get both by completing
self.background = background.convert()
the following steps:
self.background.fill((0, 0, 0))
sudo mkdir -p /usr/share/
# Render title centered
mbrola/voices/
text = self.titlefont.render(“CarPi Launcher”, 1, (255, 255, 255))
wget http://www.tcts.fpms.ac.be/
textpos = text.get_rect()
synthesis/mbrola/dba/en1/en1-
textpos.centerx = self.background.get_rect().centerx
980910.zip
self.background.blit(text, textpos)
unzip en1-980910.zip
sudo cp en1/en1 /usr/share/
self.screen.blit(self.background, (0,0))
mbrola/voices
pygame.display.flip()
wget http://www.tcts.fpms.ac.be/
synthesis/mbrola/bin/raspberri_
def main_menu(self):
pi/mbrola.tgz
# btns maps Text -> Rectangles we can do collision detection on
tar zxvf mbrola.tgz
self.btns = {‘Music’ : None, ‘NAV’ : None, ‘Weather’ : None}
sudo mv mbrola /usr/local/bin/
item_num = 1
for key in self.btns:
15 Create speech script
Navit supports speech by
running an external script and passing
text = self.titlefont.render(key, 1, (255,255,255))
textpos = text.get_rect()
max_width = self.background.get_rect().width / len(self.btns)
the text to speak as an argument.
center_offset = max_width * 0.5
Create one using:
# This y pos puts buttons just below title
textpos.centery = self.background.get_rect().centery / 2
cd /home/pi/.navit
textpos.centerx = (max_width * item_num) - center_offset
wget http://liamfraser.co.uk/
self.btns[key] = textpos
lud/carpi/chime.wav
self.screen.blit(text, textpos)
touch speech.sh
item_num += 1
chmod +x speech.sh
pygame.display.flip()
Now edit speech.sh:
def select_rect(self, rect, text):
#!/bin/bash
# Colour a rect the user has clicked in green
aplay -r 44100 /home/pi/.navit/
surface = pygame.Surface((rect.w, rect.h))
chime.wav
surface.fill((0, 255, 0))
espeak -vmb-en1 -s 110 -a 150
# Now we have to draw the text over it again
-p 50 “$1”
t = self.titlefont.render(text, 1, (255,255,255))
surface.blit(t, (0,0))
Finally, test it with:
self.screen.blit(surface, rect)
pygame.display.flip()
./speech.sh “Hello World”

The Python Book 171


Use Python with Pi

You will need to write your


own launcher for CarPi

Above The Navit software comes with a host


of options built into its menu hierarchy

Above The pympdtouchgui front-end for the


music player is surprisingly featureful

Make it
mobile
16 Configure Navit for speech
The last part is simple. Edit the Navit config file again (/
etc/navit/navit.xml) and replace the following line:
run sudo passwd to set a password for root. From a computer
with music on, run:

scp -r music_folder root@pi_ip_address:/var/lib/


<speech type=“cmdline” data=“echo ‘Fix the speech mpd/music/
It is definitely best
to put this project tag in navit.xml to let navit say:’ ‘%s’” cps=“15”/>
together in a clean Then on the Pi, change the ownership of the music that
workspace so that …with: you just copied:
you can clearly
see what you’re
working with and <speech type=“cmdline” data=“/home/pi/.navit/ sudo chown -R mpd:audio /var/lib/mpd/music
ensure everything is speech.sh %s” cps=“10” />
correctly wired and
soldered, but the
point of the project
is to make this setup
Now you can run Navit with DISPLAY=:0.0 navit and have
fun experimenting.
19 Update mpd music library
Ncmpcpp is a command line client for mpd. Type
ncmpcpp and press U to update the library. Press 3 to
portable so that you
can put it in your
browse the library and check the music is there, and press
car and use it on
the road. You could
install everything
17 Install the music player
MPD is the music player back-end and pympdtouchgui
is the front-end that needs installing manually:
Q to quit. Pressing 1 will select the help screen if you want
to do more.
into a single, hand-
made enclosure or
customise a large
bought one, or you
sudo apt-get install mpd ncmpcpp
wget http://www.spida.net/projects/software/
20 Install awesome window manager
Now you will need to write your own launcher for
CarPi, which will run full-screen. To ensure every application
could secure the
various parts inside, pympdtouchgui/pympdtouchgui-0.320.tgz is forced to full-screen, use awesome window manager in full-
for example, your tar zxvf pympdtouchgui-0.320.tgz screen mode.
glovebox or car cd pympdtouchgui-0.320/
doors. You’ll also
need to power both sudo python setup.py install sudo apt-get install awesome
the screen and your # Fix hard coded path in software sudo rm /etc/alternatives/x-session-manager
Pi with a power pack sudo ln -s /usr/local/share/pympdtouchgui/ /usr/ sudo ln -s /usr/bin/awesome /etc/alternatives/x-
and ensure that
the GPS antenna is share/pympdtouchgui session-manager
fastened into a good

18
spot for signal. Copy music When changing the default x-session-manager, awesome will
Scp (secure copy protocol) was used here to copy be auto-started at boot instead of LXDE. If you reboot the Pi,
music. First get the Pi’s IP address by running ip addr. Then awesome should then load up automatically.

172 The Python Book


Use Python with Pi

21 Install the requirements


for your launcher
The launcher is going to use a weather
Full code listing
API combined with location data def reset(self):
from the GPS receiver to give weather self.clean_background()
updates when requested. The nicest self.main_menu()
HTTP API for Python is requests, which self.render_weather()
you can install by doing the following:
def execute(self, path):
sudo apt-get install python-pip os.system(path)
sudo pip install requests # os.system blocks so by the time we get here application
# has finished
self.reset()
22 Write the launcher code
Creating the code itself is pretty
self explanatory, but you can use our def render_weather(self):
ready-made version by downloading the if self.w_text == None:
CarPi package from FileSilo.co.uk and return
extracting carlauncher/carlauncher.py.
# Get y starting at the bottom of the nav button
margin = 10
y = self.btns[‘NAV’].bottomleft[1] + margin

for t in self.w_text.split(“\n”):
line = self.wfont.render(t.rstrip(), 1, (255,255,255))
line_rect = line.get_rect()
line_rect.centerx = self.background.get_rect().centerx
line_rect.y = y
23 Start the launcher
automatically
Sudo-edit /etc/xdg/awesome/rc.lua and
self.screen.blit(line, line_rect)
y += margin + line_rect.height
move awful.layout.suit.max.fullscreen
to the top of the layouts list. Add the pygame.display.flip()
following to the bottom of the file:
def handle_events(self, events):
awful.util.spawn_with_shell(“/ for e in events:
home/pi/carlauncher/carlauncher. if e.type == QUIT:
py”) sys.exit()
elif e.type == MOUSEBUTTONDOWN:
Now reboot again and the launcher pos = pygame.mouse.get_pos()
should come up automatically. # Check if it collides with any of the buttons
for btn_text, rect in self.btns.iteritems():
if rect.collidepoint(pos):
self.select_rect(rect, btn_text)
if btn_text == “NAV”:
self.execute(“/usr/bin/navit”)
elif btn_text == “Music”:
self.execute(“/usr/local/bin/pympdtouchgui”)
elif btn_text == “Weather”:
self.w_text = WeatherClient.update()
# Reset will render weather if string is populated
24 Future improvements
There are a number of
improvements that could be made
self.reset()

to the base project at this point: def loop(self):


• Make the launcher switch between clock = pygame.time.Clock()
applications rather than start them self.reset()
again each time
• Make the launcher look better while 1:
aesthetically with icons self.handle_events(pygame.event.get())
• Use Mopidy instead of MPD so you # 5 fps is plenty
can use Spotify clock.tick(5)
• Further Navit configuration to make
it more featureful if __name__ == “__main__”:
• An SSD or USB flash drive for storage cl = CarLauncher()
to make things quicker cl.loop()

The Python Book 173


GGF 
P BM
S
BM DJ
USJ 4QF

&OKPZFE
UIJTCPPL
&YDMVTJWFPGGFSGPSOFX

5SZFT
JTTKVVTU
GPS *
£5
5IJTPòFSFOUJUMFTOFX6,EJSFDUEFCJUTVCTDSJCFSTUPSFDFJWFUIFJSöSTUUISFFJTTVFTGPSb"GUFSUIFTFJTTVFT TVCTDSJCFSTXJMMUIFOQBZbFWFSZ
TJYJTTVFT4VCTDSJCFSTDBODBODFMUIJTTVCTDSJQUJPOBUBOZUJNF/FXTVCTDSJQUJPOTXJMMTUBSUGSPNUIFOFYUBWBJMBCMFJTTVF0òFSDPEF;((;*/NVTU
CFRVPUFEUPSFDFJWFUIJTTQFDJBMTVCTDSJQUJPOTQSJDF%JSFDUEFCJUHVBSBOUFFBWBJMBCMFPOSFRVFTU
5IJTJTBO64TVCTDSJQUJPOPòFS5IF64"JTTVFSBUFJTCBTFEPOBOBOOVBMTVCTDSJQUJPOQSJDFPGbGPSJTTVFTXIJDIJTFRVJWBMFOUUPBUUIF
UJNFPGXSJUJOHDPNQBSFEXJUIUIFOFXTTUBOEQSJDFPGGPSJTTVFTCFJOH:PVSTVCTDSJQUJPOXJMMTUBSUGSPNUIFOFYUBWBJMBCMFJTTVF
%FEJDBUFEUP
BMMUIJOHT-JOVY
8SJUUFOGPSZPV
-JOVY6TFS%FWFMPQFSJTUIFPOMZ
NBHB[JOFEFEJDBUFEUPBEWBODFEVTFST 
EFWFMPQFST*5QSPGFTTJPOBMT
*OEFQUIHVJEFTGFBUVSFT
8SJUUFOCZHSBTTSPPUTEFWFMPQFSTBOE
"CPVU JOEVTUSZFYQFSUT

UIF 'SFFBTTFUTFWFSZJTTVF
'PVSPGUIFIPUUFTUEJTUSPTGFBUVSFFWFSZNPOUIo
NBH MPHJOUP'JMF4JMP EPXOMPBEBOEUFTUUIFNBMM

TVCTDSJCFSTUPy

5SZJTTVFTGPSbJOUIF6, 
PSKVTUQFSJTTVFJOUIF64" 
TBWJOHPGGUIFOFXTTUBOEQSJDF
'PSBNB[JOHPGGFSTQMFBTFWJTJU
XXXJNBHJOFTVCTDPVLMVE
2VPUFDPEF;((;*/
0SUFMFQIPOF6,+PWFSTFBT   
$BMMTXJMMDPTUQQFSNJOVUFQMVTZPVSUFMFQIPOFDPNQBOZhTBDDFTTDIBSHF
YOUR FREE RESOURCES
Log in tofilesilo.co.uk/bks-689and download your great resourcesNOW!

EVERYTHING
YOU NEED
TO BUILD ON
THE AWESOME
SKILLS IN THIS
BOOKAZINE

ENHANCE YOUR PYTHON SKILLS

Inspirational projects YOUR BONUS


RESOURCES
ON FILESILO WITH THIS
BOOKAZINE, FREE AND
EXCLUSIVE FOR THE PYTHON
BOOK READERS, YOU’LL FIND A
WEALTH OF RESOURCES,
INCLUDING THE FOLLOWING…
• A walkthrough on writing good-quality
code with Python
• A series of tutorials on making a PiSnake
game with Raspberry Pi and Python
All the tutorial files you’ll need • A guide to using GUI with GTK
• Everything you need to complete the
tutorials in this book and become a
Python expert
PACKED WITH BRILLIANT
DIGITAL CONTENT, AVAILABLE
ANY TIME, ON DEMAND Hours of free video tutorials

filesilo.co.uk/bks-689
1765IF1ZUIPO#PPL
FILESILO – THE HOME OF PRO RESOURCES
Discover your free online assets
A rapidly growing library No more broken discs
Updated continually with cool resources Print subscribers get all the content
Lets you keep your downloads organised Digital magazine owners get all the content too!
Browse and access your content from anywhere Each issue’s content is free with your magazine
No more torn disc pages to ruin your magazines Secure online access to your free resources

This is the new FileSilo site that replaces


your disc. You’ll find it by visiting the link on
the following page

The first time you use FileSilo, you’ll need to


register. After that, you can use your email
address and password to log in

The most popular downloads are shown in


the carousel here, so check out what your
fellow readers are enjoying

If you’re looking for a particular type of


content, like software or video tutorials,
use the filters here to refine your search

Whether it’s programming tutorials or


video workshops, categories make it easy
to identify the content you’re looking for

See key details for each resource


including number of views and
downloads, and the community rating

Find out more about our online stores, and


useful FAQs, such as our cookie and
privacy policies and contact details

Discover our fantastic sister magazines


and the wealth of content and information
that they provide

5IF1ZUIPO#PPL177
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL REPOSITORY

To access FileSilo, please visit filesilo.co.uk/bks-689


01 Follow the
on-screen
instructions to create an
02 Once you have
logged in, you are
free to explore the wealth of
03 You can access
FileSilo on any
desktop, tablet or
04 If you have any
problems with
accessing content on
account with our secure content available on smartphone device using FileSilo, or with the
FileSilo system, log in and FileSilo, from great video any popular browser (such registration process, take a
unlock the bookazine by tutorials and online guides as Safari, Firefox or Google look at the FAQs online or
answering a to superb downloadable Chrome). However, we email filesilohelp@
simple question resources. And the more recommend that you use a imagine-publishing.co.uk.
about it. You can bookazines you purchase, desktop to download
now access the the more your instantly content, as you may not be
content for free accessible collection of able to download files to
at any time. digital content will grow. your phone or tablet.

NEED HELP WITH


THE TUTORIALS?
Having trouble with any of the techniques in this bookazine’s tutorials? Don’t know
how to make the best use of your free resources? Want to have your work critiqued
by those in the know? Then why not visit the Linux User & Developer and Imagine
Bookazines Facebook pages for all your questions, concerns and qualms. There is a
friendly community of fellow Linux and Open Source enthusiasts waiting to help you
out, as well as regular posts and updates from the team behind Linux User &
Developer magazine. Like us today and start chatting!

facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
1785IF1ZUIPO#PPL
Python
OVER 2 HOURS
OF VIDEO TUTORIALS
The

The ultimate guide to coding with Python

Get to grips with the basics


Learn Python the right way and complete
basic projects with our simple guides

Put Python to work


Supercharge your system and make life
easier with handy coding tutorials

Over
20
projects to
complete

Use Python with Raspberry Pi


Work on any Raspberry Pi model using its
officially recognised language

You might also like