161 - EbookThe Python Book - The Ultimate Guide To Coding With Python (PDFDrive)
161 - EbookThe Python Book - The Ultimate Guide To Coding With Python (PDFDrive)
Use the setBlocks function to set a program games, movements and more
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
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
if(_which&8)
ghosting during the switching process. {
must flash the individual LED groups one after another using {
the building blocks described in the next step. _where->writePinLow(PIND3);
}
if(_which&16)
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.
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!
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:
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.
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
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.
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”
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:
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.
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()
&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
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
5IF1ZUIPO#PPL177
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL REPOSITORY
facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
1785IF1ZUIPO#PPL
Python
OVER 2 HOURS
OF VIDEO TUTORIALS
The
Over
20
projects to
complete