0% found this document useful (0 votes)
481 views240 pages

Programming The Raspberry Pi 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 240

Programming the Raspberry

Pi 4

Learning Python with Raspberry Pi 4 and


Learn it well

Scott O. Robins
Copyright © 2019 Scott O. Robins

All rights reserved. This book is copyright and no part of it


may be reproduced, distributed, or transmitted in any form
or by any means, including photocopying, recording, or
other electronic or mechanical methods, without the prior
written permission of the publisher, except in the case of
brief quotations embodied in critical reviews and certain
other noncommercial uses permitted by copyright law.
Printed in the United States of America

Copyright © 2019 Scott O. Robins


Contents
Introduction ......................................................................................... 1
Chapter 1: Setting up Your New Raspberry Pi 4 .................................. 3
Chapter 2: Setting Up Your SD Card .................................................. 11
Formatting the SD Card ................................................................. 12
Extracting NOOBs from the zip archive ......................................... 14
Chapter 3: Connecting Your Raspberry Pi.......................................... 16
For Raspberry Pi 4 .......................................................................... 18
Chapter 4: Starting Up Your Raspberry Pi 4 ....................................... 21
The First-Time Startup Using The NOOBS...................................... 21
Finishing the Setup ........................................................................ 22
Chapter 5: Raspberry Pi Desktop ....................................................... 25
Keyboard and Mouse Settings ....................................................... 27
Chapter 6: Connecting To the Internet .............................................. 29
Setting up The Sound ..................................................................... 30
Installing Software ......................................................................... 31
Installing a Drawing Application Called Pinta ................................ 34
Chapter 7: Updating and Upgrading Raspbian .................................. 36
Updating your Raspberry Pi ........................................................... 37
Advanced Packaging Tool (APT)..................................................... 40
Upgrading from Jessie to Stretch................................................... 42
Third-Party Solutions ..................................................................... 43
Mender .......................................................................................... 45
Chapter 8: How to Access Your Files ................................................. 46
Chapter 9: Using the Terminal ........................................................... 52
Chapter 10: Configuring your Pi......................................................... 55
Chapter 11: The Chromium Web Browser ........................................59
Chapter 12: Programming With Python ............................................62
Introducing the Thonny Python IDE ...............................................63
Syntax error....................................................................................66
Next Steps: Loops and Code Indentation.......................................69
Chapter 13: Your First Python Projects—Turtle Snowflakes .............71
Chapter 14: Your Second Python Project—Scary Spot the Difference
...........................................................................................................83
Chapter 15: Python Project 3– RPG Maze .........................................93
Chapter 16: Physical Computing with Raspberry Pi 4 ......................110
Introduction to GPIO Header .......................................................110
Reading Resistor Color Codes ......................................................118
Chapter 17: Your first Physical Computing Program: Hello, LED! ....122
LED Control in Python ..................................................................125
Using a Breadboard......................................................................128
Chapter 18: Reading a Button ..........................................................130
Reading A Button In Python .........................................................131
Chapter 19: Make Some Noise: Controlling a Buzzer ......................134
Controlling a buzzer in Python .....................................................136
Chapter 20: Python project: Quick Reaction Game .........................138
Chapter 21: Physical Computing With Sense HAT ...........................147
Chapter 22: PROGRAMMING EXPERIENCE .....................................154
Python Line Change .....................................................................155
Drawing with Light .......................................................................160
Pictures in Python ........................................................................162
EMULATING THE SENSORS...........................................................171
Environmental Sensing In Python ................................................171
Changing Values ........................................................................... 173
Chapter 23: Inertial Sensing............................................................. 177
Inertial sensing in Python ............................................................ 178
JOYSTICK CONTROL ...................................................................... 185
Joystick control in Python ............................................................ 185
Chapter 24: Python project—Getting started with the Camera
Module............................................................................................. 189
How to control the Camera Module using Python code ............. 196
How to change image settings and add image effects ................ 201
Change the brightness of the preview......................................... 204
Change the contrast of the preview ............................................ 205
Change The Image’s White Balance............................................. 210
Chapter 25: Python project—Make a Push Button Stop Motion .... 211
Test the camera ........................................................................... 213
Take a picture with Python .......................................................... 214
Connect a Hardware Button ........................................................ 217
Take a selfie ................................................................................. 218
Generate the video ...................................................................... 221
Chapter 26: Python project—Minecraft Photobooth...................... 223
Connect the Camera .................................................................... 224
Connect a Raspberry Pi Camera Module ..................................... 224
Importing the Minecraft and PiCamera Modules ........................ 226
Building a Photo Booth ................................................................ 229
Testing Whether You Are In The Photo Booth ............................ 231
Introduction
The Raspberry Pi 4 has been designed to run a wide range
of software as well as operating systems. It can run the core
software that makes the computer run as well. The official
operating system that is run by Raspberry Pi is referred to
as Raspbian.

The Raspbian is specifically designed to run on the


Raspberry Pi and this is based on Debian Linux. The
Raspberry Pi has the Raspbian pre-installed on it and ready
to use as soon as it’s purchased. The Raspbian is designed
similarly to the traditional windows, icons, menus and
pointed principles (WIMP), as a result, any Microsoft
Windows or Apple macOS won’t have a problem handling
this OS.

The best part is that you do not need experience in coding


(creating your programs) to explore, create and experiment
with the Raspberry Pi 4. All you need to optimize this
platform is a certain visual programming language known
as python—Python, a word that is now associated with
computer programming was coined from the Monty
Python comedy troupe.
1
Believe it or not, Guido van Rossum’s Python has grown
from a pastime obsession when it became a project
released to the public in 1991. Currently, Python is among
the favorite programming languages, used to create
dynamic applications and solutions around the world. It is
not a visual environment common with Scratch. You will
find Python's text based simulation handful and practical.

The text based layout allows you to write instructions with


a specific language and syntax which your computer
interprets. If you have dabbled with Scratch for some time,
Python is a great next step for you since it offers you
increased flexibility where you enjoy a traditional
programming adventure. At this point, you might be
thinking that it is difficult to learn, it is not.

With practice, you can start writing simple programs like


basic calculations. When your confidence is high, and you
have mastered this programming language, you can start
designing applications like complex games and 3D
environments. In this book, you will understand the
terminologies and concepts introduced.

2
Chapter 1: Setting up Your New
Raspberry Pi 4

● There are different models of the Raspberry. The


new Raspberry Pi 4 Model B is the choice of most
users because of the faster speed and the ease of
usage.
● They come with 1GB, 2GB or 4GB RAM. The 1GB of
RAM version will be good enough for educational
purposes as well as other projects while the 2GB of
RAM will work fine when you decide to use the Pi 4
for tour desktop computer.

3
● Unlike the Raspberry Pi 4, the Raspberry Pi Zero
and Zero are known to be smaller requiring less
power which makes them useful for carrying out
portable projects like robotics.

● Projects can be easily started on the Raspberry Pi 4


and navigating to Pi Zero when there is a working
prototype, one which the smaller Pi is useful for.

Power Supply

● It is to be noted that all Raspberry Pi models have a


USB port similar to the ones available on mobile
phones. We have the USB-C which is available in
Raspberry Pi 4 and for the Raspberry Pi 3,2 and 1,
there is a micro USB
● To connect to the power socket, a power that
provides at least 3.0 amps will be needed for the
Raspberry Pi 4.

4
● It is also advisable to make use of your official
universal power supply.

MicroSD card

● The SD card is used by the Raspberry Pi 4 for storing


its files as well as the Raspbian operating system.
5
● The MicroSD must have a capacity of at least 8GB
● In most cases, the SD cards sold by sellers are
already set up with Raspbian which makes them
ready for use.

Keyboard and Mouse

● You will need a USB keyboard as well as a USB


mouse to get started with the Raspberry Pi.
● A USB keyboard will be needed for the initial set up.
Once you have the Pi set up, it will be ready to be
used with the mouse and Bluetooth keyboard.

TV Or Computer Screen

● A screen, as well as a cable in linking the screen and


the Pi, will be needed to view the Raspbian desktop
environment.

6
● The computer monitor or TV can be used as a
screen.
● The Pi can be used to play sounds as long as the
screen is linked to have built-in speakers in it.

HDMI

● The Raspberry Pi is made up of HDMI output port


which is compatible with the HDMI port found in
the most modem, computer monitors as well as
TVs. The DVI and VGA ports are also available in
many computer monitors.
● The Pi 4 is made up of two micro HDMIs that
enable you to connect two separate monitors.
● Either HDMI-to-HDMI cable or micro HDMI-to-
HDMI cable with an HDMI-to-HDMI adapter is
needed in connecting the Raspberry Pi 4 to a screen.

7
● There is a single full-size HDMI port that is useful in
connecting the Raspberry Pi 1,2, and 3 to the screen
by making use of an HDMI-to-HDMI cable.

DVI

If the DVI port is available on your screen, the Pi can be


connected with the use of HDMI-to-DVI cable.

8
VGA

In some cases, the only port available in screens is the VGA


port so that when you are connecting the Pi to such a
screen, you will need the use of an HDMI-to-VGA adapter.

OPTIONAL EXTRAS

Case

It is optional to securely place your Raspberry Pi in a case


to help in protecting your Pi.

Headphones or Speakers

The bigger Raspberry Pi models are made up of a standard


audio port which is similar to the ones available on the
smartphone or MP3 player.
9
This feature is not available in the Pi Zero/Zero W models.
Though optional, you can get to connect your headphones
or speakers which enable the Raspberry Pi to play sounds.
The Raspberry Pi can also make use of speakers in playing
sound if you have the built-in speakers on your screen.

Ethernet Cable

● The large Raspberry Pi is made up of a standard


Ethernet port which is used for getting them
connected to the internet. This feature is, however,
missing in the Pi Zero/Zero W.
● The USB-to-Ethernet adaptor is needed in
connecting Pi Zero to the internet.
● The Raspberry Pi 4, 3 and Pi Zero W can also be
connected to the internet wirelessly.

10
Chapter 2: Setting Up Your SD Card
If your SD card is yet to have the Raspbian operating
system or if you want to reset your Raspberry Pi 4, you can
simply install the Raspbian yourself.

To do this, you will need a computer that contains an SD


card port in it and luckily most desktop computers and
laptops are known to have this.

Raspbian Operating system via NOOBS

● The use of the NOOBS is the easiest way of


installing the Raspbian operating system on your SD
card.
● Download NOOBS by visiting the Raspberry Pi
downloads page

(To access the above link, get the ebook version free via
matchbook if you are reading from the Paperback version
of this book)

11
● Click on the box that links to the NOOBS files.

● Downloading the zip archive of the files is the


simplest option and make sure you note where the
archive is saved to have access to it quickly.

Formatting the SD Card


During the process of formatting the SD card, anything
stored on the SD card will be overwritten which is why you
will need to back up files on your SD card on which you
want to install the Raspbian. This will save you from losing
any of your files permanently.

12
i. Download SD Formatter for your Windows or Mac by
visiting the SD Association’s website.

ii. You will be prompted by on-screen instructions you will


need to follow to get the software installed.

iii. Get the SD card installed into the laptop or computer’s


SD card slot.

iv. Go to the SD formatter and select your SD card.

13
v. Format the card

Extracting NOOBs from the zip archive


To get files extracted from the NOOBS zip archive that was
downloaded from the Raspberry Pi website, you will need
to take the following steps:

i. Search for the downloaded archive which should be in


your downloads folder by default.

ii. To extract the files, double-click the downloaded


archive and store the Explorer/Finder window open.

14
Have the Files Copied

1. Open another Explorer/Finder and navigate to the SD


card afterward.

2. It is advisable to position both windows side by side.

3. Go to the NOOBS folder and select all the files.

4. Drag them into the SD card window to copy them to the


card.

15
5. After copying all the files to the SD card, you can now
have your SD card ejected.

Chapter 3: Connecting Your Raspberry Pi


To make optimal use of your Raspberry Pi, you will have to
connect components you will need to it and most
importantly it must be done in the right order to keep all
your components safe.

● Insert the SD card, which already has the Raspbian


installed on it using the NOOBS, into the microSD
card slot positioned on the underside of the
Raspberry Pi.

16
● It is, however, important to note that most microSD
cards come inside a larger adapter, so you can make
use of the lip at the bottom in sliding your smaller
card out.

● Search for the USB connector of your mouse’s cable


and have the mouse connected to a USB port on the
Raspberry Pi irrespective of the port that is used.

17
● The keyboard can also be connected in the same
way.

● Ensure that you have your screen plugged into a


wall socket, and then switch it on.
● On the HDMI ports available on the Raspberry Pi,
you will notice a flat side on the top.
● You can then make use of a cable in connecting the
screen to your Raspberry Pi’s HDMI port or make
use of the adapter if the need arises.

For Raspberry Pi 4

● Connect your screen first via the ports labeled


HDMI0 on your Raspberry Pi 4.

18
● The second screen should be connected similarly.

Raspberry Pi 1, 2, 3

● Get your screen connected to the single HDMI port.

● It should be noted that nothing will show up on


your screen simply because the Raspberry Pi is not
running yet.
● In a situation where you like to connect your
Raspberry to the internet making use of the
Ethernet, make use of the Ethernet cable in

19
connecting the Ethernet port on the Raspberry to an
Ethernet socket on the wall or using a router.
● On the other hand, if you are making use of wireless
connectivity you won’t need to go through the steps
above.

● If there are in-built speakers available on your


screen, you will get to play sounds but if not, you
can get headphones or speakers connected to the
audio port.

20
Chapter 4: Starting Up Your Raspberry Pi
4
There is no power switch available on your Raspberry Pi, so
anytime it is connected to a power outlet it will be turned
on automatically. Once the Raspberry Pi 4 is turned on, a
red LED light will come up to indicate that it is connected
to power.

While booting, the raspberries will come up in the top left


hand of the screen.

The First-Time Startup Using The NOOBS

i. If you are starting up your Raspberry Pi for the first time


with the SD card containing NOOBS, you will be prompted
with the NOOBS installer.

ii. The installer will walk you through on getting the


Raspbian operating system installed.

21
iii. Once the installer has been loaded, you will be
prompted to select the OS you like to install.

iv. Check the box for Raspbian.

v. Select install.

Finishing the Setup

● The welcome to Raspberry Pi application will come


up and lead you through initial setup if you are
starting up your Raspberry for the first time.
● Select “Next” to start the setup process.
● Set your Country, Language as well as Timezone.

● Select “Next” again.

22
● Enter a new password for your Raspberry Pi and
select “Next.”

● Get connected to your Wi-Fi network by selecting


its name and also inputting your password and click
Next. It is to be noted that if your Raspberry model
does not have wireless connectivity, this will not
come up on your screen.

23
● Select “Next” for the wizard to check for updates to
Raspbian and get them installed. It should be noted
that this can take some time.

● Select “Done” or Reboot to complete the setup. It is,


however, advisable to reboot to help complete the
update process.

24
Chapter 5: Raspberry Pi Desktop
Recall that the Raspberry Pi runs Raspbian which is a
version of an operating called the Linux

The desktop will be displayed after the Raspbian starts up.

You will see the Raspberry Pi icon at the top left-hand


corner. This is where you can access the menu.
● Click on the icon to help you in accessing lots of
applications as well as Programming and office
applications.
● Click on Accessories and select the Text Editor to
launch a text editor.

25
● Click on the x sign located at the top right-hand
corner of the window to close the text editor.
● You can also get to explore other available
applications on the menu such as the Python games.

26
Keyboard and Mouse Settings
Select “Preferences” and then the Mouse keyboard settings
from the menu to have access to set up your mouse and
keyboard.

Mouse

The mouse speed can be changed here as well as the


double-click time. You can also get to swap the buttons in
a situation where you are left-handed.

27
Keyboard

● The Key repeat delay, as well as the interval values


can be adjusted here.

● Select the Keyboard Layout and choose your layout


form from the list of countries to help in changing
the keyboard layout.

28
Chapter 6: Connecting To the Internet

To get your Raspberry Pi 4 connected to the internet, you


can connect an Ethernet cable into it. On the other hand, if
you are using the Pi Zero, there will be a need for a USB-to-
Ethernet adaptor too. If you have Pi 4, 3, or Pi Zero W, you
can connect to the internet to them using the wireless
network.
Connecting To a Wireless Network

● On the top right-hand corner of the screen, click on


the wireless network icon and then select your
preferred network from the drop-down menu.

● Input in your wireless network password and click


“OK”

29
● Once your Pi has been connected to the internet,
you will be prompted with a wireless LAN symbol
instead of the red crosses.

● To test your connection, click on the web browser


icon and browse the web for Raspberry Pi.

Setting up The Sound


The Raspberry Pi is capable of sending sound to the built-
in speakers available on the screen using the HDMI
connection. They can also send sounds to the analog
headphone jack.

30
Go to the top right-hand corner and right-click on the
speaker icon to choose if your Pi should make use of the
HDMI or the analog connection of sound.

● Select the speaker icon and move the slider up or


down to help in adjusting the volume of the
speaker.

Installing Software

● It is important to note that your Raspberry Pi must


be connected to the internet before you can get to
install software programs and applications.
● Go to the menu and select “Preferences”
● Select “Recommended Software”

31
● You will then be prompted with the recommended
software from which you can browse and you can
also get to filter it by category.

32
● Click to mark a software checkbox to the right to
install it.

● Click “OK” to have the selected software installed.


● Apart from the software recommended in the
Raspberry Pi, there are also other available
programs and applications in the library.
● Click on “Preferences”
● Select Add/Remove software option on the menu.

33
● Select and browse a category from the menu located
on the left to search for software.

Installing a Drawing Application Called Pinta

i. Type ‘pinta’ into the search box.

34
ii. Select Enter.

iii. A list will appear from which you will select “Simple
drawing/paint program”

iv. Select “OK” to begin the installation process.

v. Enter a password when prompted.

vi. Once you type in the right password, pinta will get
downloaded and installed.

vii. After the installation process is complete, launch Pinta


by selecting Graphics and go to the menu to select Pinta.

35
Chapter 7: Updating and Upgrading
Raspbian
This section explains how to get software updates deployed
to devices running Raspbian. It is important to keep your
devices updated due to the following reasons:

● Getting your device updated helps in keeping it


secured.
● Once your device gets updated with Raspbian, you
will get access to millions of lines of codes that you
will need.
● These million lines of codes will, in turn, expose you
to well-known vulnerabilities which are known as
Common Vulnerabilities and Exposures (CVE).
● These codes are easy to exploit since they are made
available and documented in publicly available
databases.
● By making sure that your software is up to date as a
user of the Raspbian, you will be able to mitigate
these exploits. The upstream repositories do track
the CVEs closely to mitigate them quickly as well.

36
● By keeping your software up to date will also help in
limiting the chances of hitting bugs which can end
up affecting the desired functionality.

Updating your Raspberry Pi


● The Add/Remove software application can be used
in updating your Pi.
● Select the Preference section of the menu to gain
access to the Add/Remove software application.

37
● Make sure you get the software package lists
refreshed on your Pi before checking and installing
updates.
● Go to the top left-hand corner to click Options
● Select “Refresh Package Lists”

● Your Raspberry Pi will then update all the lists of


your packages.

● As soon as the update is complete, click on Options


then select the Check for updates option.

38
● The Package Updater will get opened automatically
and also check if there is another update available.
Anything that is found on the list will be displayed.

● Select the Install Update option to help install all


the available updates.

39
● Input in your password as soon as you are
prompted.

● All updates available will be downloaded and


installed. You will get to see your installation by
going to the bottom left-hand corner to check the
progress bar.

Advanced Packaging Tool (APT)

The Apt tool can be used in a terminal to help update your


software in Raspbian.

i. From the application menu or taskbar, open a terminal


window.

ii. Enter the command “sudo apt-get update” to get your


system’s package updated.

40
iii. Enter the command “sudo apt-get dist-upgrade” to get
all your installed packages upgraded to their latest
versions.

Doing this regularly will help keep the installations in the


Raspbian up to date for a major release such as the Stretch
but won’t update for a major release to another such as for
Stretch to Buster.

It is important to note that occasional changes are made in


the foundation’s Raspbian image which will require manual
intervention such as the newly introduced package. This is
because they are not installed with an upgrade.

Also, note that the command mentioned above are only


used to upgrade packages that have been installed already.

Updating the Kernel and Firmware

Since the kernel and firmware are both installed as a


Debian package, they will automatically get updated when
you use the commands above. They get updated frequently
after extensive testing.

41
Running Out Of Space

● The amount of data to be downloaded including the


space it will take up in the SD card will be displayed
when running the command “sudo apt-get dist-
upgrade.”
● It is advisable to check if you have enough free disk
space using df-h because the apt will not be doing
this for you.
● All downloaded packages files (.deb files) are stored
in the /var/cache/apt/archives. Nevertheless, this
can be removed to free up space by using the
command sudo apt-get clean.

Upgrading from Jessie to Stretch


It is possible to upgrade an existing Jessie image but note
that this will not work in every circumstance. It is therefore
advisable to back up your data first before upgrading a
Jessie image to stretch to avoid the loss of data in a
situation where there is a failed update.

i. Before upgrading, modify the files /etc/apt/sources.list as


well as /etc/apt/sources.list.d/raspi.list.

42
ii. Change everywhere you have Jessie to stretch and it is
to be noted that sudo will be required to edit in both files.

iii. Launch the terminal window and run the command;


sudo apt-get update and sudo apt-get –y dist-upgrade.

iv. For any prompt that comes up, reply with “yes.”

v. At some point, the installation might pause while page


information is shown on the screen, when this happens;
hold the space key to scroll through and press “q” to
continue.

vi. If the PulseAudio is only used for Bluetooth and


nothing else, remove it from the image by entering the
command sudo apt-get –y purge “pulseaudio”

If you are changing to a new Pi model such as the Pi 3B+,


the kernel and the firmware may need to be updated as
well by following the instructions above.

Third-Party Solutions
For any device running the Raspbian, Apt is a convenient
way for updating the software, but this method is limited
when you have a larger pool of devices to update especially

43
when there is no physical access to your devices and are
distributed geographically.

In a situation where you don’t have physical access to your


device and you need to deploy an unattended Over-The-
Air (OTA), the following requirements should be put into
consideration:

i. Updating must not break the devices under any


circumstances, for instance, when the update is being
interrupted due to network or power loss, the system
should fall back into a working state.

ii. The updating must be atomic. And either the update


succeeded or failed, nothing in between can result in a
device still functioning but it will exhibit undefined
behavior.

iii. The updating process must be able to have images or


packages that are cryptographically signed installed
thereby preventing third parties from gaining access to
install software on your device.

iv. The updating process must be able to have updates


installed using a secure communication channel.

44
Generally, apt is lacking in terms of robustness features
that are atomicity and fall-back.

This is the reason third-party solutions have been creating


solutions to problems that need attention for deploying
unattended updates OTA.

Mender
This can be referred to as an end-to-end, open-source
update manager. The atomic dual system update helps in
providing a robust update process with the availability of a
working system partition. The Mender then updates the
one that is not running

45
Chapter 8: How to Access Your Files
The MicroSD card is responsible for storing all your
Raspberry Pi files including the ones that were created by
you. Select “Accessories” and Go to the menu and select the
File Manager or go to the menu bar to select the File
Manager.

As soon as the File manager comes up, it will display the Pi


directory where your files can be stored as well as creating
a new subfolder.

46
The following are the main subdirectories:

Desktop: This is the folder you will see when you load the
Raspbian. In a situation where you have a file saved here, it
will be displayed on the Raspbian desktop for easy access
and loading.

Documents: This is the home to most of the files that you


will create such as recipes, short stories, etc.

Download: Any file that is downloaded from the internet


via your Chromium browser will be automatically saved in
the Downloads.

MagPi: This is referred to as the official Raspberry Pi’


magazine and it contains an electronic copy of the MagPi.

47
Music: Music that is created and kept on the Raspberry Pi
is saved here/

Pictures: In technical terms, pictures are referred to as


image files and they are saved here.

Public: However, it is to be noted that most of your files are


private but any file that has been designated as public will
be made available to other Raspberry Pi users even if there
are username and password attached.

Videos: This is the first location for most video-playing


programs and it is the folder where videos are kept.

Generally, the file manager window can be split into two


panes: which are the left and the right pane.

i. The left pane will display the directories available on


your Raspberry Pi

ii. The right pane will display the files and subdirectories of
the directory which are selected in the left pane.

In case a removable storage device is plugged into the USB


port of the Raspberry Pi, you will be prompted by a pop-up
window asking if you would like to have it open in the File

48
manager. Once this pop up comes up, select OK for you to
view the files and directories.

To open the directory and view the files available in it,


double-click on the Documents icon.

To get a file opened, double click on the file’s name. You


can alternatively right-click the file to open the file menu
for more options.

49
The Raspberry Pi supports the use of USB drives and sticks
which make backups and copying of files to another
computer easy.

Once you get a USB stick inserted into your Raspberry Pi,
you will be prompted on the screen by a window asking
what action you would love to perform. Open the File
Manager by clicking OK.

50
The File Manager will be automatically opened showing
you the available files on your USB stick.

Keyboard Shortcuts

Keyboard shortcut such as the CTRL+C means having the


first key which is CTRL on the keyboard held down and
then pressing C which is the second key and then, finally
releasing both of the keys.

Once you are done with the File Manager, select the close
button at the top left to close the window. In a case where
you have multiples window opened, close them all.

If a removable storage device is connected to your


Raspberry Pi, you can get it ejected by selecting the eject

51
button located at the screen’s top right, select it from the
list and click on it before getting it unplugged.

Ejecting Devices

Before unplugging an external storage device, always


remember to make use of the eject button to avoid your
files from getting corrupted and unusable.

Chapter 9: Using the Terminal


The terminal application is very useful in different ways. It
helps you in the navigation of file directories as well as the
control of your Pi with the use of commands instead of
having to click on the menu options.

● To get the terminal window opened, select the


Terminal icon located at the top of the screen.
Alternatively, you can select the Accessories then go
to the menu to select Terminal.

52
● Commands can be inputted into the terminal
window. Press enter on your keyboard to run the
command entered.
● Type “Is” in the terminal window and select Enter
on the keyboard.
● The command ‘Is’ will have all the files and
subdirectory in the current file directory listed. The
File directory that is accessed by the terminal when
it is opened is called Pi and it opens up by default.

● Type in the command “cd Desktop” to help in


changing directory to the Desktop. And remember
to press enter on the keyboard to run your
command.

53
● The command ‘Is’ can be used in listing the files that
are available in the Desktop directory.

● The terminal is a very powerful tool that enables


you to interact with your Raspberry Pi.
● For example, by typing the command pinout, a
labeled diagram of the GPIO pins will be displayed
including some additional information about your
Pi.

● Click on the x sign or use the command exit to close


the terminal window.
54
Chapter 10: Configuring your Pi
The Configuration application of the Raspberry Pi which is
found in the Preferences option of the menu can be used in
controlling most of the settings of your Raspberry Pi.

System Tab: This tab enables you to change the basic


system settings of your Pi.

55
Password: It is advisable to make sure you change the
password from raspberry which is the factory default
password. All you need to do is set the password of the pi
user.

Boot: Select this to display the Desktop or the Command


Line Interface when starting up your Raspberry Pi.

Auto Login: With this option enabled, you will be


automatically logged in by the Raspberry Pi whenever it
starts up.

Network at Boot: Once this option is selected, your


Raspberry Pi will wait before starting up until there is a
network connection available.

Splash screen: This option enables you to choose whether


or not to show the splash or startup screen when the
Raspberry Pi boots up.

Interfaces

Devices and components can get linked up to the


Raspberry Pi by making use of different connection types.

56
These different connections can be turned on or off using
the Interfaces tab thereby enabling your Pi to recognize if
it has been linked to through some type of connection.

Camera: This enables the Raspberry Pi Camera Module.

SSH: This allows remote access to your Raspberry Pi with


the use of SSH from another computer.

VNC: This makes use of the VNC in allowing remote access


to your Raspberry Pi Desktop from a different computer.

SPI: This activates the SPI GPIO pins.

12C: This is used in enabling the 12C GPIO pins.

Serial: This enables the Serial (Rx, Tx) GPIO pins.

1-Wire: This helps in enabling the 1-wire GPIO pin.


57
Remote GPIO: This allows you to access the GPIO pins of
your Raspberry Pi from a different computer.

Performance

The performance settings of your Raspberry Pi can be


changed using this tab if you have a particular project to
work on. Nevertheless, it is important to note that
changing the performance of your Raspberry Pi’s setting
can cause it to behave irregularly or not working.

Overclock: This helps in changing the speed and voltage of


your CPU to increase performance.

GPU Memory: This changes the allocation of memory that


is given to the GPU.

Localization

With this tab, you can easily change the settings of your
Raspberry Pi into a specific country or location.

Locale: This is used to set your Raspberry Pi’s language, the


country as well as the character set.

Time zone: With this, you can set the time zone of your Pi.

58
Keyboard: This is used in changing the layout of your
keyboard.

Wi-Fi Country: This is used in setting the country code of


your Wi-Fi.

Chapter 11: The Chromium Web Browser


The Chromium browser is a web browser that allows you to
visit websites, play video games and get to interact with
people far and wide on forums as well as chat sites. You can
start to use your Chromium by simply maximizing its
window to take up the screen.
i. Load the Chromium browser to start up with
practicing the use of your Raspberry Pi.
ii. Go to the top left and click on the raspberry icon to
display the menu.
iii. Select the internet category using your mouse
pointer.
iv. Select the Chromium web browser to get it loaded.

59
● Go to the top right of the chromium window title
bar, where you will find three icons. Select the
middle one denoted by an up-arrow icon. This will
help in maximizing the window such that it will fill
up the screen.
● Next to the maximize button to the left, is the
minimize button that helps in hiding a window
until you select it on the taskbar located at the top
screen to have it opened again.
● The icon to the right of the maximize button is the
close button, as the name implies, it will close the
window.

CLOSE AND SAVE

60
While most programs will warn you to save before closing
your work whenever you select the close button, some will
not warn you. So, it is advisable to make sure you save your
works before closing it.

To start exploring your chromium-browser:

i. Go to the address bar which is located at the top of


the Chromium window which is the big white bar
having a magnifying glass on the left-hand side.
ii. Type in a website address and tap the ENTER key on
your keyboard. This will load the website.
iii. Several tabs might come up at the top of the
window if you are loading chromium for the first
time.
iv. To go to a different tab, select the tab in question.
v. Click on the cross icon which is located at the right-
hand edge of the tab you like to close to get it
closed.
vi. Click on the tab button located at the right of the
last tab on the list to open a new tab alternatively,
you can have the CTRL key on the keyboard held
down and press the “T” key before releasing your
finger on the CTRL.

61
vii. As soon as you are done exploring your Chromium
web browser, click on the close button which is
located at the top right of the window.

Chapter 12: Programming With Python


Python, a word that is now associated with computer
programming was coined from the Monty Python comedy
troupe. Python is among the favorite programming
languages, used to create dynamic applications and
solutions around the world. It is not a visual environment
common with Scratch. You will find Python's text based
simulation handful and practical.

The text based layout allows you to write instructions with


a specific language and syntax which your computer
interprets.

If you have dabbled with Scratch for some time, Python is a


great next step for you since it offers you increased
flexibility where you enjoy a traditional programming
adventure.

At this point, you might be thinking that it is difficult to


learn, it is not.

62
With practice, you can start writing simple programs like
basic calculations. When your confidence is high, and you
have mastered this programming language, you can start
designing applications like complex games and 3D
environments.

In this chapter, you will understand the terminology and


concepts introduced in the previous chapter.

Introducing the Thonny Python IDE

Toolbar— the simple mode module of Thonny Python


comes with attractive icons on its menu bar. The icons are
pretty straightforward, representing different functions
that allow you to save, create, load, and run your programs

63
in various ways. Script area—your python programs are
implemented at the script area which is usually split into
two–major and supplementary.

The major area takes the bulk of space, serving as a canvass


for your programs including a complementary side margin
that displays line numbers.

Python shell—running your codes are usually done here as


well as options about how your programs should run.

In addition, you can input individual instructions that are


quickly implemented as soon as you press the ENTER key.

Variable area—for convenience and easy tracking, all


changes–either intentional or unintentional are accessible
in this section. Think of this area as a log of your sessions
when you create and run programs.

YOUR FIRST PYTHON Program: Hello, World!

If you want to access Thonny from the menu, you should


go to its icon directly. Just like other pre–installed
applications on the Raspberry Pi, Thonny is quite visible
with its unique icon. Click on the Raspberry icon, move the
cursor to the programming section, and click on Thonny

64
Python IDE. Wait for a few seconds as the program—
usually the simple mode loads, welcoming your eyes to its
user interface.

Basically, Thonny is an integrated development


environment (IDE). And what it does is to bring together
the tools that are required to design, write or develop
software into a holistic user-interface experience. Think of
Thonny as a hybrid with a capability for supporting one
programming language unlike others that clearly supports
various languages.

The biggest takeaway from using Python is the absence of


visual feedback as you create programs unlike Scratch with
real-time graphics.

You will enjoy this traditional programming language of


hard line codes better than modern iterations available on
other IDEs. To start your first program, click on the Python
shell area at the bottom-left of the Thonny window; type
this instruction and press ENTER:

print("Hello, World!")

After hitting the ENTER key, your program runs instantly.


When you see 'Hello, World!' your program was run
65
successfully. In addition, your program runs immediately
in the shell area because the interpreter clearly examined
your codes and instructions, found it valid and interpreted
it. The whole parsing process that is displayed in the shell
area is known as the interactive mode, more like a face-to-
face interaction with your friend where communication is
enriched by sending, processing and receiving information.

Hello World!

Syntax error
Coding is interesting when your programs are
implemented just the way you created it. It can be
frustrating when you cannot fathom the incidents that
surround a 'syntax error' message. Usually, a syntax error
message is displayed at the shell area which means that
your codes are not properly written.
66
Remember that when you omit a bracket and a quotation
mark, or misspelled 'print' with extra symbols; your
program will not run. To salvage the situation, type the
instruction again, and ensure that the codes are an exact
replica of the example provided in this book. Then press
the ENTER key.

Click on the script area at the left-hand side of the Thonny


window and type your program again.

print("Hello, World!")

After you click the ENTER key, there are no changes except
a visible blank line in the script area. If you want to try this
out, click the Run icon on the Thonny toolbar. A prompt
appears immediately, asking you to save your session.

Use a descriptive name like "Hello World" while using the


save button. When your program has been stored on your
system, two messages appear in the shell area.

67
While the first message is clearly a command from Thonny,
asking the interpreter to load the program you just saved;
the other one is an output of the program.

Congratulations!

You can call yourself a coder as you have executed your


first program using interactive and script models.

Challenge: New message

Now that you can run programs using interactive and


script methods, you may face some difficulties changing
the message executed by the Python program.

68
In addition, you may be confused when choosing the best
method to support the addition of new messages and
perhaps you wonder what happens when you remove the
brackets or quotation marks from the codes and
consequently run it.

Next Steps: Loops and Code Indentation


Python controls how functions and strings are arranged
and connected with a technology known as indentation.
This system ensures that your programs are interpreted
smoothly.

Create a new program by clicking on New icon in the


Thonny toolbar. A new tab is created just above the former
one where you can run new programs while working on the
other program. You may commence with the following
instruction:

print("Loop starting!") for i in range (10):

What you see on the first line as an output in the shell area
resembles the earlier feedback from the Hello world
program.

69
The second output kick-start a definite loop, similar to
Scratch where (I) is assigned to the loop with a series of
numbers. The numbers in the loop begin at 0 oscillating
between 0 and 10 but never quite reaching 10. The colon
symbol (:) means that subsequent instruction after the
symbol is invalid and will not be parsed by the interpreter.

Python has a similar function too, utilizing a different


method evident with indenting codes.

Indenting your code on python is present by default and


makes your lines clear with serial numbers attached to
each instruction. Failure to implement and understand this
concept leaves you with blank spaces and a headache.

CHALLENGE: ALTER THE LOOK

To create content that engages your end users, employ


images to create fun just like other popular culture with
Halloween costume. Here, you will create a prank using
colors and image where you create a wonderful experience
with a picture.

You can go about this by drawing your own spot-the-


difference and scary images (using a graphics editor such
as GIMP).
70
Similarly, you could also raise the credibility of this
challenge, putting in place tracking measures to ascertain
users who correctly spotted the difference.

Chapter 13: Your First Python Projects—


Turtle Snowflakes
Now that you understand how Python works, it’s time to
infuse graphics and create a snowflake using a tool known
as a turtle.

Physical robots imitate the natural order of things in the


environment, especially animals. A turtle in the wild just
like its digital companion moves in a straight line, make
turns, with minimal limb coordination.

Think of that motion on your screen where the turtle


draws a line from a point to another. Unlike some other
languages, namely Logo and its many variants, Python
doesn’t have a turtle tool built into it. However, a huge
library of add-on codes allows the motion of the turtle to
be quite practical.

71
Libraries are arrays of code that adds new instructions and
variables stretching Python's realm of possibilities further.
Using an import command, you can start creating awesome
content with this skill.

To create a new program to test your skill in this area, click


on the New icon, and type the following: import turtle

When you use a data from a library, it is expedient that you


use the name of the data followed by a syntax arrangement.

You are required to use the library name followed by a full


stop, and then the instruction follows.

That can be annoying to type out every time, so you can


assign a shorter variable name instead –preferably one
letter which doubles as a pet name for the turtle. Type the
following:

pat = turtle.Turtle()

To test your program out, you’ll need to give your


turtle something to do. Type:

pat.forward(100)

72
Click the Run icon, and save your program as Turtle
Snowflakes. After doing this, a new window called ‘Turtle
Graphics’ will appear where you get a taste of your
program: your turtle, Pat, will move forwards 100 units,
drawing a straight line.

Matt drawing a line!

When switching back to the Thonny window from the


graphics canvas, you may not easily find it because it is
usually at the background. Take your cursor to the
minimize function and click it or you move to the task bar
directly at the top of the screen where you can also hit the
stop button to collapse the Turtle Graphics window.

73
Typing out every single movement instruction by hand
would be tedious, so delete line 3 and create a loop to do
the hard work of carving out shapes:

for i in range(2):

pat.forward(100)

pat.right(60)

pat.forward(100)

pat.right(120)

Run your program, and Pat will draw a single parallelogram

To transform this into a snowflake-like shape, click the


Stop icon in the main Thonny window and create a loop
around your loop by substituting this instruction in line 3:

for i in range(10):

74
…and the following at the bottom of your program:

pat.right(36)

Your program won’t run as it is, because the existing loop


isn’t indented correctly. To fix that, click on the start of
each line in the existing loop – line 4 through 8 – and press
the SPACE key four times to correct the indentation. Your
program should now look like this: import turtle

Click the Run icon, and watch the turtle: it’ll draw a
parallelogram, as before, but when it’s done it’ll turn 36
degrees and draw another, then another, and so on until
there are ten overlapping parallelograms on the screen –
looking a little like a snowflake

75
While a robotic turtle draws in a single color on a large
piece of paper, Python’s simulated turtle can use a range of
colors.

Add a new line 3 and 4, pushing the existing lines down:

You can also have the colors chosen randomly from a list,
using the random library. Go back to the top of your
program and insert the following as line 2: import random

In your line 4, change the background color from ‘blue’ to


‘grey’, then create a new variable called ‘colors’ while
inserting a new line 5:

colours = ["cyan", "purple", "white", "blue"]

U.S. SPELLINGS

76
Many programming languages use American English by
default, especially spellings. Python is no exception. The
earlier command in line 5 ought to be spelled color rather
than color. When you use British spellings, your program
will fail to run.

This rule does not overlap to words associated to Variables


where you exercise freedom with semantics.

Using the line 5 example again, this type of variable is


called a list, and is marked by square brackets where the
snowflake appears in specific colors but you still need to
tell Python to choose one each time the loop repeats itself.
At the very end of the program, enter the following –
making sure it’s indented with four spaces so it forms part
of the outer loop, just like the line above it:

pat.color(random.choice(colours))

Click the Run icon and the snowflake-stroke-ninja-star will


be magically drawn. This time around, Python will choose
a random color from your list as it draws each petal –
giving the snowflake a pleasing, multicolor finish.

77
Using random colors for the ‘petals’

Now that you can create a ninja star, you should write
codes that will bring to life a benign snowflake, which
looks closely like real life. To make this happen, add a new
line 6 directly below your colors list with the following
instruction:

pat.penup() pat.forward(90) pat.left(45)


pat.pendown()

The penup and pendown instructions moves a simulated


pen off and on the graphics page just like what obtains
with a paper surface. Rather than using a loop, like you
have been doing, you’re going to create a function that can

78
be recalled when you need it. And the function remains in
your portfolio.

Start by deleting the code for drawing your parallelogram-


based snowflakes: that’s everything between and including
the pat.color("cyan") instruction on line 10 through to
pat.right(36) on line 17.

Don't tamper with pat.color(random.choice(colours)) code


but inject a hash symbol (#) at the start of the line. Using a
hash creates an emphasis known as commenting which can
follow the instructions which Python ignores when
interpreting the lines of code. You can also add
explanations to your code with comments for clarity where
you come back to it after some time or share it.

Function is created by first defining it. Define your


function with ‘branch’, by typing the following instruction
in line 10, just below pat.pendown():

def branch():

This instruction defines your function, using the choice of


values you want in the branch container. When you press
the ENTER key, Thonny will include an indentation for the
function’s instructions.
79
Type the following while paying close attention to
indentation because a misplaced blank space would affect
your nesting efforts sooner, rather than later.

for i in range(3):

for i in range(3):

pat.forward(30)

pat.backward(30)

pat.right(45)

pat.left(90)

pat.backward(30)

pat.left(45)

pat.right(90)

pat.forward(90)

Make sure that the new loop you create remains above the
commented-out color line.

You should as well run and call your new function:

for i in range(8):

80
branch()

pat.left(45)

Your finished program should look like this:

import turtle
import random
pat = turtle.Turtle()
turtle.Screen().bgcolor("grey")
colours = ["cyan", "purple", "white", "blue"]
pat.penup()
pat.forward(90)
pat.left(45)
pat.pendown()
def branch():
for i in range(3):
for i in range(3):
pat.forward(30)
pat.backward(30)
pat.right(45)
pat.left(90)
pat.backward(30)
pat.left(45)
pat.right(90)
81
pat.forward(90) for i in range(8):
branch()
pat.left(45)
# pat.color(random.choice(colours))
Click on Run and watch the graphics window as Pat
implements your instructions.

Congratulations: your snowflake now looks a lot more like


a snowflake than anything else.

Finally! A snowflake to remember.

CHALLENGE: WHAT NEXT?

Can you use your commented-out instruction to have the


branches of the snowflake drawn in different colours? Can
you create a ‘snowflake’ function, and use it to draw lots of
snowflakes on the screen? Can you have your program
change the size and colour of the snowflakes at random?
82
Chapter 14: Your Second Python
Project—Scary Spot the Difference
This project will demonstrate to you the capability of
Python to scale pictures and sounds as well as turtle-based
graphics, which will be used here as a prank on your
friends. This project requires two images–your spot-the-
difference image with a ‘scary’ surprise image and a sound
file.

To start, click on the raspberry icon to load the Raspbian


menu, choose the Internet category, and click on
Chromium Web Browser. When it has loaded, type
rpf.io/spot-pic into the address bar followed by the ENTER
key.

After you have chosen your preferred picture, Right-click


on the picture and click on ‘Save image as...’, choose the
/home/pi folder, then click Save. Click back on
Chromium’s address bar, then type rpf.io/scary-pic
followed by the ENTER key.

As before, right-click the picture, click ‘Save image as…’,


choose the /home/pi folder, then click Save.

83
For the sound file, you’ll need to type rpf.io/scream into
the address bar followed by the ENTER key. While it
downloads, think of where you will move it to because you
may not be able to use it without moving it to an accessible
folder.

Click on the raspberry icon, find the Accessories category,


and click on File Manager. In the folder list, double-click
on Downloads. Find the file scream.wav within this folder,
right-click on it, and then click Cut. Click on pi in the
folder list to the left, then right-click on a blank space in
the main window area before clicking Paste. You can now
close the File Manager and Chromium.

After you have moved the image, Click the New icon in the
Thonny toolbar to begin a new project. The best way to
experience the dynamic use of Python's capabilities is
through the appreciation of a resource like Pygame that is
created for games. Type the following:

import pygame

To use data from other libraries, including a part of the


Pygame library. Import them by typing the following:

84
from pygame.locals import * from time
import sleep

from random import randrange

You want to use a specific data from a library rather than


the whole bank of data. Thereafter, you create a Pygame
setup, which is a concept known as initialisation. In order
to improve the validity of the Pygame framework, set the
resolution of your TV and monitor.

Type the following:

pygame.init()

width = pygame.display.Info().current_w
height = pygame.display.Info().current_h

The final step in setting Pygame up is to create its window,


which Pygame calls a screen. Type the following:

screen = pygame.display.set_mode((width,
height))

pygame.quit()

85
Take note of the blank line in the middle because your
program will stay there. For immediate action, click on the
Run icon and save your program as Spot the Difference.
Pygame will then create a window or a box with a black
background that contains the pixel spatial measurements.
Conversely, the variables area fill up with unique values
that Pygame has automatically created, you can safely
ignore these.

To open and display your desired spot-the-difference


image, put the following line in the space above
pygame.quit():

difference = pygame.image.load('spot_the_diff.png')

86
Scale and adjust the width and height of the pixel to make
sure the image fills the screen with ease. Then type the
following:

difference = pygame.transform.scale(difference,
(width, height))

Now the image is in memory, you need to tell Pygame to


actually display it on the screen – a process known as
blitting, or a bit block transfer. Type the following:

screen.blit(difference, (0, 0))


pygame.display.update()

The first of these lines copies the image onto the screen,
starting at the top-left corner; the second tells Pygame to
redraw the screen. Without this second line, the image will
be in the correct place in memory but you’ll never see it!

Click on the Run icon, and the image will briefly appear on
screen.

87
Your spot-the-difference image

To prolong the visibility of the image before it disappears,


add the following line just above pygame.quit():

sleep(3)

By Clicking Run again, the image stays on the screen for a


longer period. So you can stick your surprise image by
typing the following just below the line
pygame.display.update():

zombie =
pygame.image.load('scary_face.png')

zombie = pygame.transform.scale (zombie,


(width, height))

88
Add a delay, so that the zombie image doesn’t appear right
away:

sleep(3)

Thereafter, blit the image to the screen and update so that


it reflects to the player:

screen.blit(zombie, (0,0))
pygame.display.update()

When you Click on the Run icon, you may start wondering
about what will happen; Pygame will basically load your
spot-the-difference image, giving you something to be
cheerful about. But after three seconds it will be replaced
with the scary zombie.

It’ll give someone a scary surprise

89
Having the delay set at three seconds encourages a
predictable behaviour that may spoil the fun you intend to
have with your friends. You had better change the line
sleep(3) above screen.blit(zombie, (0,0)) to:

sleep(randrange(5, 15))

This picks a random number between 5 and 15 while other


line of action remains valid. Next, add the following line
just above your sleep instruction to load the scream sound
file:

scream = pygame.mixer.Sound('scream.wav')

Move below your sleep command and enter the following


instruction on a new line to start the sound in a way that it
is heard before the ominous image bursts out on the
screen:

scream.play()

Finally, tell Pygame to stop playing the sound by typing the


following line just above pygame.quit():

scream.stop()

When you hit the Run icon with a wide grin on your lips in
anticipation of what you want to do, you will discover that
90
hitting that icon could lead to a scary destination where
your scary zombie will appear with a backbreaking shriek
which would give your friends the shiver!

If the zombie picture appears before the sound starts


playing, you can adjust it by adding a small delay just after
your scream.play() instruction and before your screen.blit
instruction with this line:

sleep(0.4)

Finally! Your lines of instruction and codes appears like


this:

import pygame
from pygame.locals import *
from time import sleep
from random import randrange
pygame.init()
width = pygame.display.Info().current_w
height = pygame.display.Info().current_h
screen = pygame.display.set_mode((width,
height))
difference =
pygame.image.load('spot_the_diff.png')

91
difference =
pygame.transform.scale(difference, (width,
height)) screen.blit(difference, (0, 0))
pygame.display.update()
zombie =
pygame.image.load('scary_face.png')
zombie = pygame.transform.scale (zombie,
(width, height)) scream =
pygame.mixer.Sound('scream.wav')
sleep(randrange(5, 15))
scream.play()
screen.blit(zombie, (0,0))
pygame.display.update()
sleep(3)
scream.stop()
pygame.quit()
What are you waiting for, invite your friends to play spot-
the-difference while the speakers are turned up to the
highest volume for sheer excitement.

92
Chapter 15: Python Project 3– RPG Maze

By now, you are getting the hang of this programming


language. Using the Pygame, you can attempt to create an
advanced program. Creating more complex than simple
programs allows you to enjoy the beauty of this language.

For this advanced program, you can create a fully-


functional, text-based maze game. Let us take a classic
role-playing exciting game known as interactive fiction
which dates back to a period when computers had poor
graphics capability. During this period, arcade games plays
on the imagination where the simplicity of the characters
and missions leaves you amazed.

A fully-functional program is quite complex than the


others in this chapter and to introduce this advanced
concept to you in a way that you will appreciate and
understand, you will commence with a standard version.

1 Open the Chromium Web Browser and go to the


following address: rpf.io/rpg-code.

93
2. The Chromium Web Browser will automatically
download the code of the program to your Download
folder.

3. Move the cursor on Thonny and click the Load icon.


Find the file, rpg-rpg.py, in your Download folder and click
on the Load button.

4. To run the downloaded package, Start by clicking the


Run icon to familiarise yourself with how a text adventure
works. And you can trace the output in the shell area at the
bottom of the Thonny window too.

5. For convenience, enlarge the Thonny window by clicking


on the maximise button.

The game is quite simple: two rooms and no objects are the
available elements. The player hits the ground running in
the Hall, busting into the first room of the two rooms.

To enter the Kitchen, type ‘go south’ followed by the


ENTER key.

When you’re in the Kitchen, you can issue this command


‘go north’ to return to the Hall. You can also try typing ‘go

94
west’ and ‘go east’, but as there aren’t any rooms in those
directions the game will show you an error message.

There are only two rooms so far

When you click the Stop icon, and look in the variables
area for the rooms variable, you will find the roadmap of
the game. This type of variable is essentially a dictionary
which provides data about the rooms, their exits, and
which room a given exit leads to. If you scroll down to line
29 of the program in the script area, you’ll see where this
variable is created and how it’s laid out.

To make the game more interesting, include another room:


perhaps a Dining Room would find a place at the east of
the Hall.
95
Find the rooms variable in the scripts area, and extend it by
adding a comma symbol (,) after the } on line 38, then type
the following (exact indentation isn't essential in a
dictionary):

'Dining Room' : {

'west' : 'Hall'

After you have finished this, You need a new exit in the
Hall, as one isn’t automatically created for you. Go to the
end of line 33, add a comma, then add the following line:

'east' : 'Dining Room'

Click on the Run icon, and see for yourself the magic that
just happened in your new room: type ‘go east’ while in the
Hall to enter the Dining Room, and type ‘go west’ while in
the Dining Room to enter the Hall.

Congratulations: you’ve made a room of your own!

96
You have added another room

Empty rooms can be quite bored without items. To add an


item to a room, the first step is to modify that room’s
dictionary. Stop the program by clicking the Stop icon.
Find the Hall dictionary in the scripts area, then add a
comma to the end of the line 'east' : 'Dining Room' before
pressing ENTER and typing the following line:

'item' : 'key'

Click on Run again. This time, the game will tell you that
you can see your new item: a key. Type ‘get key’ and you
can pick it up, adding it to the list of items you have
created – known as inventory. Your inventory remains
with you as you travel from room to room.

97
Click the Stop button, and make the game more interesting
by adding an obstacle—a monster will do. Include the
monster item in the Kitchen dictionary just like you
created a value for the key item, add a comma to the end of
each line.

'item' : 'monster'

To carry the monster along where it is directly involved in


the game, attacking the player or creating problems for the
hero; you’ll need to add some logic to the game in order to
introduce this narrative. Do this by Scrolling to the very
bottom of the program in the script area and add the
following lines with proper indentation. You could attach
the comment too, marked with a hash symbol, which will
help you understand the program if you come back to it
another day.

# player loses if they enter a room with a


monster

if 'item' in rooms[currentRoom] and


'monster' in rooms[currentRoom]['item']:

print('A monster has got you... GAME


OVER!')
98
break

Click Run, and try going into the Kitchen room– the
monster won’t be too impressed when you do!

A
monster has got you!

To turn this adventure into a proper game, you’re going to


need more items, another room, and the ability to ‘win’ by
leaving the house with all the items safely in your
inventory. Start by adding another room, just as you did for
the Dining Room – only this time, it’s a Garden. Add an
exit from the Dining Room dictionary, remembering to add
a comma to the end of the line above:

'south' : 'Garden'
99
Then include your new room to the main rooms dictionary,
remember to add a comma after the } on the line above as
before:

'Garden' : {

'north' : 'Dining Room'

Add a ‘potion’ object to the Dining Room dictionary while


including the necessary comma to the line above:

'item' : 'potion'

Finally, scroll to the bottom of the program and add the


logic required to check that the player has all the items
and, if so, tell them they’ve won the game:

# player wins if they get to the garden with a


key and a potion

if currentRoom == 'Garden' and 'key' in


inventory and 'potion' in inventory:

print('You escaped the house... YOU WIN!')

Click Run, and try to finish the game by picking up the key
and the potion before going to the garden. Avoid the
Kitchen room because that’s where the monster is!

100
As a last tweak for the game, providing suggestions to the
player about the game and how to go about it has nothing
to do with breaking rules. You might want to scroll to the
top of the program, where the function showInstructions()
is defined, and add the following:

Get to the Garden with a key and a potion.

Avoid the monsters!

Run the game one last time, and you’ll see the changes
your new lines has created, usually at the very start.
Congratulations! you’ve made an interactive text-based
maze game!

Your text-based game is looking good

101
CHALLENGE: EXPAND THE GAME

Continue to think about ways to make your adventure


more daring. Ask yourself! Can you add more rooms to
make the game last longer? Can you include an item to
reduce the impact from the claws of the monster? How
would you add a weapon to slay the monster? Can you add
more rooms that will be above and below the existing
rooms, accessed by stairs?

COUNT FROM ZERO

Python is a zero-indexed language which means that it


starts counting from 0, not from 1. Whenever you run
programs and instructions, Python prints the numbers
from 0 through 9 instead of 1 to 10, especially when you are
dealing with loops. But you can change this behavior by
switching the default range (0, 10) to (1, 11). You can also
create wider ranges.

As you are already aware, Indentation is the powerhouse of


Python, so you really want to take it serious when you are
running your code.

102
Looking for errors in your code can become daunting, but a
process called debugging can lift the burden off your
shoulders.

Anyway, a professional tip is that you should not take


chances and make a habit of double-checking indentation
most especially when you are dealing with nesting loops.

Python also supports infinite loops, which is basically a


continuous activity or command. To change your program
from a definite loop to an infinite loop, edit line 2 to read:
while True:

If you click the Run icon now, your programs will end up in
an error feedback because 'i' is not defined and you have
also removed the line that created and assigned a value to
the variable i. To fix this, simply edit line 3 so it no longer
uses the variable:

print("Loop running!")

Click the Run icon where you will see the ‘Loop starting!’
message followed by a never-ending string of ‘Loop
running’ messages. As a result of the infinite nature of
loop,

103
The ‘Loop finished!’ message does not print. A takeaway
from this section is that whenever Python executes the
‘Loop running!’ message, it reverts to the beginning of the
loop and prints it again.

Clicking the Stop icon on the Thonny toolbar drags the


program to a halt, a process called interrupting the
program. This process is activated when a message appears
in the shell area, stopping the instructions from reaching
line 4.

CHALLENGE: LOOP THE LOOP

You ought to know how to use loops, including the


interplay of definite loops and indefinite loops. And
perhaps know how to use loops in very interesting ways.

104
Mastering loops also gives you the ability to add different
loops that perform complex functions as a standalone or
within a loop. Knowing how and when to use definite and
indefinite loops goes a long way in your programming
career.

Conditionals and variables

Variables are the bedrock of programming languages,


controlling more than just loops. To Start a new program,
click on the New icon on the menu bar and type the
following into the script area:

userName = input ("What is your name? ")

Click the Run icon, save your program as Name Test, and
pay close attention to the shell area: A prompt appears
requesting your name. Proceed by typing your name into
the shell area, and press ENTER. When you take this
action, the variable section close to the right of the Thonny
window displays the variable and its value. The variable
area remains passive and open regardless of active work in
progress, making it convenient to know your program
activities.

105
Conditionals allow your program to have a unique
narrative. Using conditional statements moves your
program in a particular direction. You can use conditionals
with a name to create a meaningful program. For example,
add a conditional statement by typing the following:

if userName == "Clark Kent":

print("You are Superman!") else:

print("You are not Superman!")

The rules of indentation still applies here with


conditionals, so you might want to hit the BACKSPACE key
often to reduce spaces yourself in order to prevent error
feedback. Click the Run icon and enter your name into the
shell area. Unless your name happens to be Clark Kent,
you’ll see the message ‘You are not Superman!’. When you
click Run again while entering the name ‘Clark Kent’,
106
endeavor to write it exactly like the program, with an
upper case C and upper case K. After doing this, the
program recognizes that you are, in fact, Superman.

The == symbols instructs Python to do a direct


comparison, looking to see that the variable userName
matches the text – known as a string – in your program. If
you’re working with numbers, you can make comparisons
with certain symbols known as comparison operators.

> indicates that a number is greater than another


number,

< indicates that a number is less than another


number.

107
=> indicates that a number is equal to or greater
than another number.

=< indicates a number is equal to or less than


another number.

!= indicates that a number is not equal to another


number; the exact opposite of ==.

USING = AND ==

Knowing Python's variable is not as important as using


them when it counts. = means ‘make this variable equal to
this value’, while == means ‘check to see if the variable is
equal to this value’. Using both variables lead to a dead end
because they simply do not go together.

Comparison operators can also be used in loops. Delete


line2 through 5, then type the following in their place:

while userName != "Clark Kent":

print("You are not Superman - try again!")

userName = input ("What is your name? ")


print("You are Superman!")

108
Click the Run icon again. This time, rather than quitting,
the program will keep asking for your name until it
confirms that you are Superman– sort of like a very simple
password. To get out of the loop, either type ‘Clark Kent’ or
click the Stop icon on the Thonny toolbar.

Congratulations: you now know how to use conditionals


and comparison operators!

CHALLENGE: ADD MORE QUESTIONS

Can you change the program to ask more than one


question while storing the answers in multiple variables?

109
Can you create a program with a bunch of conditionals and
comparison operators to print a random number typed in
by the end user which is higher or lower than 5.

Chapter 16: Physical Computing with


Raspberry Pi 4
Like the name, physical computing is when you write some
programs that work with hardware to give a physical
action, like move, jump, and so on. Best example is your
washing machine. You switch it on and set the temperature
or the spinning rate to your desired level. The washing
machine starts working and performs a physical action
with the press of buttons. That is Physical Computing at
work.
Learning about physical computing can get a lot easier
with the help of Raspberry – a cool tool to learn physical
computation better. Its key component is the general-
purpose input/output (GPIO) header.

Introduction to GPIO Header

The GPIO header is located at the top edge of the Pi circuit


board that looks like 2 rows of iron pin.

110
It is the way to connect the light-emitting diodes (LEDs)
and switches which are the hardware to the Pi for the
programs you have written in order to give you a physical
computing output.
The name, even though sounds confusing but defines its
features well. You can use the pins for input and output, as
they serve more than one purpose. When pins are in the
open such as this, they are called Header which brings us
back to the initial name: General-purpose input/output
header

There are 40 male pins of which the Raspberry Pi GPIO


header consists of some of which are accessible to use for
physical computation while some produces power and
others are reserved for add-on hardware communication
such as the Sense HAT.
Pin types are categorized into several ways with each
having a defined function:

111
WARNING!
You have to be careful with dealing with Raspberry Pi’s
GPIO header.
Do not bend the pins in the connecting and disconnecting
process of the hardware. Two pins should never be
connected one at a time or except you are instructed to do
so in a project. Connecting two pins at a time is called
short circuit and it can destroy the PI permanently.
Electronic Components
What you need to commence your physical computing
consist of the GPIO header and other electrical features
that will be controlled from the GPIO header. There are
lots of components but GPIO projects are mostly done with
the use of these common parts.
112
Breadboard: This make your physical computing way
easier. You will need not to go through connecting several
components wires with Breadboard; it lets you do that
easily with the metal tracks below its upper surface.
Breadboards also have power distributions that let you
create your circuit easily.
Even though it is not a must to have, but you will save
yourself some stress using Breadboard. It can also be called
Solderless.
Jumper Wires: This connects your electrical components
with the Raspberry Pi. There are three versions of Jumper
wires; M2F (male-to-female), it is needed to connect your
solderless to the GPIO pins; F2F (female-to-female), it

113
makes it possible to connect component individually when
you are not using a solderless; M2M (male-to-male).
This is a tool for connecting across the solderless. You will
need these three types of Jumper wire depending on your
project. M2M and M2F can be avoided when you are using
a Solderless.

Push Button Switch: It can also be called a momentary


switch. This is the kind of switch that is used in the
controller of game consoles. It usually comes with 2 or 4
stands, whichever one will do just fine with the Raspberry’s
Pi. The push button serves as an input device that lets you
command your program to perform a certain action.

114
Other types of switch is Latching switch, where you will
have to hold down the push button before it becomes
active. Latching switch can be activated at one toggle and
can be deactivated when toggled again.

Light-emitting diode (LED): Unlike the Push-button,


LED serves as an output device and can directly be
controlled from your program. It comes up when on, and
can be found all around your building, from the small one
to the big ones.
They come in various shapes, sizes and colors. However,
not all LED are compatible to use with Raspberry PI. Some
are designed for 12 V or 5 V power supplies, please avoid
them.

115
Resistors: This is the component that is in charge of
controlling the current flow and is in different values
which can be measured in ohms (Ω).
The resistance provides resistors based on the number of
ohms. In Raspberry Pi physical computing projects, the
resistor is usually used to safeguard the LEDs from
attracting excess electric current and destroy one another.
You will need a resistor of 330 ohms to create more
flexibility.

Piezoelectric buzzer: also called a sounder is an output


device but not like an LED that produces light. Buzzer is an
output device that produces a buzzing noise. Piezoelectric
buzzer contains two metal plates that vibrate opposing
each other when activated. Buzzer has two types which are
active and passive. An active buzzer is the perfect choice
on your physical computing.

116
Motor is another recognized component that requires a
special control board to get tit connected to the Pi.
Infrared sensors are a device that detects the temperature,
humidity sensors and movement. Also the LDRs which
mean light-dependent resistors are an input device that
works like reverse LED.

Sellers all over the world provide components for physical


computing with the Raspberry Pi, either as individual parts
or in kits which provide everything you need to get started.
Some of the most popular retailers are:
Retailers’ worldwide stock electrical components for
physical computing along with the Raspberry Pi, they sell
in bit or in kit that gets you started. These are some of the
notable sellers around the world:

117
● RS Components – uk.rs-online.com
● CPC – cpc.farnell.com
● ModMyPi – modmypi.com
● Pi Hut – thepihut.com
● PiSupply – uk.pi-supply.com
● Adafruit – adafruit.com
● Pimoroni – pimoroni.com
To complete the projects in this chapter, you should have
at least:
● 3 × LEDs: green, yellow, and red or amber
● 2 × push-button switches
● 1 × active buzzer
● Male-to-female (M2F) and female-to-female (F2F)
jumper wires
● Optionally, a breadboard and male-to-male (M2M)
jumper wires

Reading Resistor Color Codes


There is a spectrum of values for resistor starting from
zero-resistance version that is made up of just small pieces
of wire to the high-resistance versions of the size of which
can be compared to a human leg.

118
However, you can only see the value written on only a few
of these resistors which are usually in stripe color on the
resistor

You can read the value of a resistor by positioning the


bands to the left and lone band to the right. Now the first
thing to look out for in the first band is the color which can
be found in the 1st/2nd Band’ of the table to acquire the 1st
and 2nd figure.

119
There are two orange bands in this example with both
having the same value ‘3’ and makes a total of ‘33’.
Your band may have more than 3 bands; you will have to
write down what the value of the third band is (for five/six-
band resistors, see rpf.io/5-6band).
Now go to the last group of bands and check for the color
of either the third or fourth band, it can be found in the
‘Multiplier’ section.
It informs you about the number you will multiply the
present number by to get the right value of your resistor.
There is a scientific notation ‘x101’ that stands as a brown
band in this example which translates to ‘include a 0 to the
last number’. For blue, it is x106 which means to add six 0s
to end of the number.
The orange band is 33 with the addition of the 0 from the
brown band, it will make it 330: The resistor’s value that is
measured in ohms.
On the right is the final banding that serves as a tolerant
for the resistor. It is likely to be near its value this way:
Since cheaper resistors are bound to have a silver band,
when trying to figure out its exact value, it may go 10%
higher or lower than the actual value.

120
There is no band which indicates that it can go 20% higher
or lower, this is because resistors that are the most
expensive comes with grey bands which means that it is
just in between 0.05% of actual rating. You really need no
precision if you are on hobbyist projects.
Values of resistors that are over 1000 ohms are measured in
kiloohms (kΩ) and if it is over 1 million ohms they are
called megohms (MΩ). You have 2200 Ω resistor indicated
as 2.2 kΩ while 2200000 Ω would be indicated as 2.2 MΩ.

121
Chapter 17: Your first Physical
Computing Program: Hello, LED!

Creating the LED light is the beginning of the journey to


learning physical computing just as writing ‘hello world’ to
the screen is the traditional start to learning programming.
On this project, an LED with a 330 ohm resistor will be
needed or any rating close to 330 ohm with a F2F (female-
to-female) jumper wires.
RESISTANCE IS VITAL
The resistor plays an important role in the circuit because
it serves as a protection for the LED and the Raspberry Pi
by giving a limit to the electrical current flow that the LED
draws. Without the resistor, the electrical current can
become excessive for the LED which could lead to burning
itself or even the PI.
When it is utilized this way, it serves as the current-
limiting resistor. The precise value of resistor you will use
will be determined by the LED in use. However, the
resistor whose value is 330 ohm works for most LEDs.

122
The effects of the resistors value work like this on the LED:
When a resistor value is higher, the LED becomes dimmer
and when the value is lower, the LED is brighter. Do not
connect the Pi and the LED together without the
interference of the current-limiting resistor only if the LED
comes with a built-in resistor of the required value.
1. Begin your work by confirming if your LED is
functioning.
2. Position the Raspberry Pi in a way that will separate the
GPIO header into 2 vertical stripes off to the right.
3. Make a connection of Raspberry Pi with first 3.3 V pin.
4. With the use of a F2F jumper wire.
5. Join the other end to the log leg to either the anode or
positive of your LED using yet another F2F jumper wire.
6. Pick the last F2F jumper wire and join the short leg with
either the cathode or negative of the LED to the first
ground pin.

123
7. Connect your LEDs to these pins and do not forget the
resistor.
8. In as much as you have your Raspberry Pi on, the LED
light will be up.
9. And if in case it does not, cross check your circuits to
confirm whether you are doing it exactly as you are being
taught.
10. Check the connections and ensure that the resistor
value is not too high for your LED and the Raspberry Pi.
After you have confirmed that your LED is working, now it
is time to do the programming.
1. Disconnect the 3.3 V pin from the jumper wire and
connect a jumper wire to the GPIO 25 pin. This will make
the LED go off, when it happens, do not fret, it is okay.

124
11. After you have confirmed that your LED is working, now
it is time to do the programming. Disconnect the 3.3 V pin
from the jumper wire and connect a jumper wire to the
GPIO 25 pin. This will make the LED go off, when it
happens, do not fret, it is okay.

Now it is time to create a Python to control the power


switch of the LED.

LED Control in Python


Thonny can be loaded from the programming area of the
Raspberry menu.
Press the NEW button to get a new project underway and
click ‘Save’, it will be saved as Hello LED. A library known
as GPIO zero is needed to be able to get access to the GPIO
pin from Python.

125
Only the part of the library is required to work with LEDs
on this project. Import the area of this library by inputting
the below into the Python shell section:
from gpiozero import LED
Next, you have to let GPIO Zero understand which GPIO
pin is connected to the LED. Write the below code:

led = LED(25)
Both lines let Python control LEDs that are connected to
the Pi’s GPIO pin and inform it which (pin) s. If the LEDs
in your circuit are more than two, you will have to write
the below code to control it.
led.on()

To turn of the LED again, write:

led.off()
Well Done! You now have the ability to control the
Raspberry Pi’s GPIO pin that is in Python. Attempt to write
those codes again. When the LED is off the led.off() will
not be effective, the same thing happens when the LED is
on and your write led.on().

126
To make a real code, write the below code into the script
section:
from gpiozero import LED from time import sleep
led = LED(25)

while True:
led.on()
sleep(1)
led.off()
sleep(1)

This code will import the LED from the GPIOZero library
and also the Sleep function. After this, it will build an
infinite loop to switch the LED on for a sec and off for
another sec continuously. Press the Run key to watch the
action:

CHALLENGE: LONGER LIGHT-UP


How to alter the program for the LED to stay ON or OFF
for a longer period of time? The smallest delay that can be
used while the LED is going on and off.

127
Using a Breadboard
The project we are about to dive into in this chapter will be
much easier if you make use of a breadboard to keep the
components together to connect the electric features.

There are holes that cover the breadboards to match with


the components, apart from 2.54 mm. Metals strips are
found under these holes and serves as the jumper wires
that have been in use till now. They operate in rows all
across the breadboard that always has a gap across its
middle to separate into two.
Majority of breadboards have letters over the top and
numbers written below the sides.

128
This gives you the ability to locate the specific hole: A1, the
left corner. B1: the hole to the immediate right. B2: a hole
down from there. The hidden metal connects the A1 to B1
but the number 1 hole is always connected to the second
hole except you add a jumper wire.

On bigger breadboards, there are strips of holes at the


down sides that are in color red, blue or black stripes. They
are known as the power rails which makes the wiring
process a lot easier.
Connect a wire right from the Pi’s ground pin to one of the
power rails that are usually in blue, red, black or minus
sign (-) to give a ground for many features of the
breadboard and same can be done if 3.3 V or 5 V power is
required in your circuit.
It is quite easy to add electronic features to a breadboard:
Put their leads in line (the sticky-out metal area) with the
holes and carefully until it is put in place.
To connect, you have to make more than what the
breadboard has provided. M2M can be used; to connect
from the breadboards to the Pi, make use of the M2F
jumper wires.

129
Do not memorize more than a jumper wire or component
lead into a hole on the breadboard. Since holes are in rows
apart from the separation down the middle, the
component lead within A1 is connected electrically to
whatever you include to B1, C1, D1, and E1.

Chapter 18: Reading a Button


When you see ‘input/output’ portion of ‘GPIO’, it means
that pins can be used as inputs as well. Things you will
need for this project are breadboard, M2M, M2F with a
push-button switch. F2F can be used in case you do not
have a breadboard available; however, you will find it more
difficult to press without breaking the circuit.

Begin with the adding of a push-key to the breadboard.


Your push-key has two legs? Ensure that they are in
different rows on the breadboard. If your push-key has four
legs, change its position to make the sides at which the legs
pops out from are in line with the holes on the breadboards
and the smooth legless sides are positioned at the top of
the bottom. Make a connection of the ground rail to the

130
ground pin of the Raspberry Pi. With the M2M jumper
wire.
Now make a connection of a leg on of your push-key with
the ground rail using an M2M jumper wire.
And lastly, join the second leg of your push-key, in case
you are using a four legged switch to your GPIO 2 pin of
the Pi with a M2F jumper wire.

Reading A Button In Python


Press the New key in Thonny to begin a new project, and
press on the Save key. Save it as Key Input. There is huge
similarity in the use of a GPIO as an input for a button and
a pin as an output for LED.

131
The difference is that you will have to import a portion of
the GPIO zero library. Write the below script section:
from gpiozero import Button = Button(2)
To have the code run when the button is pressed, GPIO
Zero provides the wait_for_press function. Type the
following:
button.wait_for_press()
print("You pushed me!")

Tap the Run key and then click the push-button. Your
input will be printed to the shell of the Python that can be
found at the down part of the Thonny window:
An input has been read from the GPIO pin then click the
GPIO pin. In case you want to retry the program, re-click
the Run key which will stop immediately it is done with the
printing of the message to the shell because the program
contains no loop.
For expansion of your program, including the LED and
resistor back in the circuit: Do not forget to connect the
GPIO 25 pin to the resistor and the longer leg of the LED
and the shorter leg of the LED to the breadboard’s ground
rail.

132
If you want to control the LED and read a button,
importing the Button and LED function from GPIO zero
library is important.
Also, the sleep function will be needed. You can scroll back
to the top of the program and write the below as the new 1st
two lines:
from gpiozero import LED from time import sleep

Below the line button = Button(2), write:

led = LED(25)

Clear the line print("You pushed me!") and instead input:

led.on() sleep(3) led.off()

Your program should look like this when done: from


gpiozero import LED
from time import sleep
from gpiozero import Button
button = Button(2)
led = LED(25) button.wait_for_press() led.on()
sleep(3)

133
led.off()
Press the Run key and tap the push-button: the LED light
will ON for three seconds, then go off after. You can now
control an LED using the key from Python.
CHALLENGE: ADD A LOOP
How to add a loop to repeat the program? What are the
things that must be altered to let the LED stays on when
you do not click on it and OFF when you do?

Chapter 19: Make Some Noise:


Controlling a Buzzer

LEDs serve as unique output device but too much of LED


cannot be used if you are aiming for another direction.
Here is the solution: Buzzer, it produces quite audible
noise in the room.
Things you will need for this project include M2F,
breadboard and a functioning buzzer. You can use F2F
jumper wires to connect your buzzer in case you do not
have a breadboard. You can use the same treatment of the
LED for an active buzzer when it comes to programming or
circuitry.

134
You can use the circuit you use for LED for the buzzer. But
use the active buzzer in place of the LED and then leave
out the resistor, because the buzzer requires more current
to function.
A leg of the buzzer should be connected to the GPIO 15 and
the second leg to the ground pin (as in GND in the
diagram) with the use of the breadboard and M2F jumper
wires.
Your buzzer may be a three legged one, just ensure that
you mark the leg with a minus sign – and connect it to the
ground pin and also mark it with ‘SIGNAL’ or S connecting
it to the GPIO 15, and the left leg should be connected to
the 3.3 V pin (labeled 3V3.)

135
Controlling a buzzer in Python
The control of an active buzzer with the GPIO zero library
is similar to the control of a LED. There is ON and OFF
states. Different function will be required even though
there is a buzzer. Begin a new project on Thonny, save
Buzzer and write the below code:
from gpiozero import Buzzer from time import sleep

As it is with LEDs, GPIO Zero has to understand which of


the pins your buzzer is connected to for the control. Write
the following:
buzzer = Buzzer(15)
It is now the same as the one for LED; the only difference
(apart from a different GPIO pin number) is that it is the
buzzer being used and not a led.
Input the below:

while True:
buzzer.on()
sleep(1)
buzzer.off()
sleep(1)

136
Press the green flag for your buzzer to start buzzing: If the
buzzer is heard clicking just once in a second then that is a
passive buzzer and not an active one. An active buzzer will
generate a fast changing signal for the metal plates to
vibrate itself which is oscillating. A passive buzzer on the
other hand will require an oscillating signal.

Press the Stop key to close the program but ensure that the
buzzer is not buzzing at that moment or else it will keep
on the buzz until you decide to make a rerun of the
program.
CHALLENGE: A BETTER BUZZ

How to alter the program for the buzzer to buzz for a


shorter period of time? How to create a circuit that
controls the buzzer with a button?

137
Chapter 20: Python project: Quick
Reaction Game
LEDs and buttons can now be used as input and output
devices, you can now be set to create a real physical
computing. Two-player quick-reaction game created to
discover whose reaction is the fastest. Things you will need
for this project are LED, breadboard, a 330 ohm resistor, 2
push-button switches, M2Fs and M2M jumper wires.

Firstly, you will build a circuit: make a connection of both


the switch at the left of your board and the GPIO 14 pin
(labeled GP14, Fig 6-7). The 2nd switch at the breadboard’s
right to GPIO 15 pin (labeled GP15), and the longer leg of
the LED should be connected to the 330 ohm resistor and
join the GPIO 4 pin (labeled GP4) of your Raspberry Pi and
the 2nd leg on every component on the ground rail.

Lastly, make a connection of the ground rail and Raspberry


Pi’s ground pin (labeled GND).

138
On Thonny, launch a new project which is to be saved as
Reaction Game. You will need the button and LED
functions from the GPIOZero library with the sleep
function too. They can be saved and import together using
a comma sign (,) to divide them. Write the below in the
script section:
from gpiozero import LED, Button from time import sleep
As usual, inform the GPIO Zero which of the pins are the
two buttons and the LED are connected to. Write the
below:
led = LED(4) right_button = Button(15)
left_button = Button(14)

139
Now include instructions to switch the LED on and off, to
confirm if it is working perfectly:

led.on() sleep(5) led.off()


Press the Run key, this will make the LED come up for 5
secs and go off then the program will exit. The light going
off at a fixed time can be predictable, include the following
line from the time import sleep:

from random import uniform

The random library allows you to shuffle and garner


random numbers( with a uniform distribution-
rpf.io/uniform). Search for the sleep(5) and alter it to the
below:

sleep(uniform(5, 10))

Tap on the Run key again: This will make the LED remain
lit at random seconds around 5 – 10. Observe and read the
time it takes for the LED to come off and press the RUN
KEY few times more: there will be different time interval
for every run which makes it difficult to predict.

140
Trigger the buttons for every player which will require you
to include a function. Stroll down to the very end of the
program and write the below code:

def pressed(button):
print(str(button.pin.number) + " won the game")

Indentation is the tool Python uses to identify lines that


are in your function. Thonny will indent the 2nd line
automatically. Lastly, include the below line to discover
which of the players is pushing the keys and do not forget
that the lines must not be indented or else it will be treated
as a function on Python.

right_button.when_pressed = pressed
left_button.when_pressed = pressed

Open your program and push one of the buttons


immediately the LED is off. A message for the number one
button to be pressed will be printed by Python shell at the
down part of the Thonny window.

141
Message will pop up every time they press the button and a
pin will be used for their names. Request for the names of
the players, below the line from shuffled import uniform,
write the below code:

left_name = input("Left player name is ") right_name =


input("Right player name is ")
Go back to your function and replace the line
print(str(button.pin.number) + " won the game") with:

if button.pin.number == 14:
print (left_name + " won the game")
else:
print(right_name + " won the game")

Tap the Run key and input the names of the players into
the Python shell. When the button is pushed this time
around, do it as fast as you can before the LED goes off,
this will reveal the actual players’ names and not pin
numbers.

142
To amend the problem reported on the pressed buttons,
you will introduce a new function from the sys that is
‘system’ library. Exit. Beneath the end of the import line,
write the below code:

from os import _exit

At the last part of your function, below the line


print(right_name + " won the game"), write the following:
_exit(0)

The indentation is very vital in this part: identify _exit(0)


by four spaces and make it in line with else: let the be 2
line at the top of it.
This will instruct the Python to put an end to the program
after pressing the first key which means that the player
with the secondary pressed button got nothing for losing
the game.

143
Your final program should look like this:

from gpiozero import LED, Button from time


import sleep
from random import uniform
from os import _exit
left_name = input("Left player name is ") right_name =
input ("Right player name is ") led = LED(4)
right_button = Button(15)
left_button = Button(14)
led.on() sleep(uniform(5, 10)) led.off()

def pressed(button):
if button.pin.number == 14:
print(left_name + " won the game")
else:
print(right_name + " won the game")
_exit(0)

right_button.when_pressed = pressed
left_button.when_pressed = pressed

144
Tap the Run key and input the player names, hold on for
the LED to go off to see the name of the winner. The two
lines from Python will also be visible: when you see’
Backend terminated (returncode: 0)’ that is Python
informing you that it got your _exit(0) command and exit
the program.

The ‘Start/Stop’ is to restart the backend which means that


the program is paused but not cancelled. To stop the
program press the ‘Stop’ soft key.

Quit the program when you have discovered the winner!

145
Hurray! You have successfully created your own
physical game

CHALLENGE: IMPROVE THE GAME

Do you know how to address a loop for the game to keep


running repeatedly?

Do not forget to clear the _exit(0) instruction!

How do you add a score counter to know who is winning


even after multiples of rounds? Do you know you can set a
timer to make you know the time it takes you to react to
the light when going off?

146
Chapter 21: Physical Computing With
Sense HAT
The Sense HAT, according to its application on the
International Space Station, can be referred to as an add-on
board for the Raspberry Pi which is equipped with sensors
as well as an LED matrix display to perform varieties of
functions.

Generally, the Raspberry Pi has been designed to support a


special type of add-on board which is known as the
Hardware Attached on Top (HAT). This add-on board is
capable of getting hardware added such as microphones
and lights, electronic relays and screens and even the Pi
itself. The Sense HAT is however much more special type
of the HAT genre.

The Sense HAT is popular for its use in a joint project


called the Astro Pi space mission in which the Raspberry Pi
foundation along with the UK space agency and European
Space Agency collaborated.

They deployed Raspberry Pi boards along with Sense


HATs, using the Astro Pi, into the international space
station aboard a cargo rocket by Orbital Science Cygnus.
147
The Sense HATs was nicknamed Ed and Izzy by the
astronauts. Astro Pi space mission saw the sense HAT
successfully reaching the orbit high above the earth, giving
this HAT the positive reputation of being now used to run
code as well as carrying out the most scientific experiment
by schoolchildren across Europe.

The Sense HAT hardware is available at all Raspberry Pi


retailers and you can get it simulated in software as well if
you don’t want to buy one at present.

Introduction to the Sense HAT

The Sense HAT has a multi-functional add-on for the


Raspberry Pi with amazing features. It designed with an
8x8 matrix of 64 red, green with blue LEDs which are all
programmed and that can be controlled to produce colors
from a range of millions. They are built with a five-way
joystick controller as well as six-on-board sensors.

148
Gyroscope sensor: This is used in detecting any change in
the angular velocity by keeping track of the gravity field of
the earth. Talking of the gravity field, it’s simply the force
pulling things down towards the planet center. The
gyroscopic sensor can tell you when the sense HAT rotates
relatives to the Earth's surface as well as how fast it rotates.

Accelerometer: This measures acceleration force in


multiple directions. The combined data from both
gyroscope and accelerometer can be used detecting the
direction which your Sensor HAT is pointing as well as
how it is moved.

Magnetometer: This is used in measuring the magnetic


field strength as well as keeping track of the movement of
the Sense HAT. The magnetometer can also help in
figuring out the direction of the magnetic north with the
use of the earth’s magnetic field of the earth. They can also
be used in detecting metallic objects as well as electric
fields.

All these three sensors that are, the gyroscope,


accelerometer, and magnetometer are built into a single
chip and they are labeled as ACCEL/GYRO/MAG on the
circuit board of sense HAT.
149
Humidity sensor: This sensor measures the water vapor
amount that is present in the air which is called the relative
humidity. The relative humidity ranges from 0% to 100%.
When at 0%, it means there is no presence of water at all in
the air while 100% means that the air is completely
saturated. We can easily predict if it’s about the rain once
we have information about the humidity.

Barometric pressure sensor: This measure the air pressure


and it is also referred to as the barometer. It is a popular
term when it comes to weather forecasting and can be used
to track whether you are climbing up or down a mountain
or hill as the air gets thinner or has a lower pressure
compared to that of the sea level of the earth.

Temperature sensor: This measures the hotness or coldness


of the surrounding environment and it is also being
affected by how cold or hot the sense HAT is. It is to be
noted that sensor HAT is not built with a separate
temperature sensor but they simply rely on the
temperature sensor that is available in the humidity or
barometric pressure sensors. A program can be made to
use one of these two sensors depending on what works for
you.

150
Installation of the Sense HAT

Once you purchase your Sense HAT, you will need to get it
unpacked to make sure you have every accessory
completed packaged in it. It should be made up of the
following:

 Sense HAT
 Spaces (which are the four metal or plastic pillars):
This is used in stopping the Sense HAT from
blending or flexing while the joystick is in use.
 Eight screws
 Metal pins in a black plastic strip similar to the
GPIO pins on the Raspberry Pi; if this is available,
get the strip pushed pin side up via the bottom of
the Sense HAT until you hear the sound of a click.

Though the sense HAT will work without all these being
installed they will help in protecting your Raspberry Pi,
Sense HAT as well as The GPIO header from getting
damaged.

WARNING

 Make sure the Raspberry Pi gets switched off and


disconnected from its power supply before the
151
Hardware Attached on Top (HAT) modules is
plugged in or removed from the GPIO header.
 When installing the HAT, make sure its lying flat
before getting it installed and always check to make
sure it is lined up with the GPIO header pins before
getting it pushed down.
 Get the spacers installed by pushing the four screws
up from the bottom of the Raspberry Pi via four
mounting holes that are located at each corner and
have the spacers twisted onto the screws. Get the
sense HAT pushed down onto the GPIO header of
the Raspberry Pi while ensuring that they are well
lined up with the pins underneath and make sure it
is flat as possible.
 Get the final four screws screwed via the sense HAT
mounting holes into the spacers that were earlier
installed. If properly installed, the sense HAT should
be flat and leveled and it should not bend while
pushing on its joystick.
 Have the power plug back into your Raspberry Pi.
Once powered up the LEDs that are available on the
Sense HAT will get lighted up with a rainbow

152
pattern after which you can switch off again. This
signifies that the Sense HAT is now fully installed. ‘

In case you want to detach the sense HAT again, undo the
top screws and then lift the HAT off but make sure you do
this carefully to avoid bending the pins that are available
on the GPIO header due to the hard grip of the HAT. You
can also employ the use of a small screwdriver. Then you
can now remove the spacers from the Pi.

Hello, Sense HAT

Just like other programming projects, the sense HAT also


has a beginning with a welcome message scrolling across
the LED display. If you are making use of a sense HAT
emulator, you can simply click on the Raspbian menu icon
to get it loaded and then select the programming category
and click on the Sense HAT emulator.

153
● this doesn’t leave out all the testing and
development that is required on a normal IoT Core
system and they can upgrade when it’s time for your
final media to be built.

Chapter 22: PROGRAMMING


EXPERIENCE
This chapter is based on Python as well as the integrated
development environment depending on if you are
working via the python code examples or both.

GREETINGS FROM PYTHON

To load Thonny in either the simple or standard modes,


take the following steps:

i. Click on the Raspbian menu icon.

ii. Choose programming

iii. Click on either Thonny link.

iv. In a situation where you are making use of the Sense


HAT emulator and gets covered by the Thonny window,
154
click and hold the mouse button on either title bar of the
window which is at the top and in blue color. Then, get it
dragged to move it around the desktop until you can see
both windows.

Python Line Change


For a python code that is written for a physical sense HAT,
it will run on the Sense HAT with only one change and
vice-versa.

In a situation where you are making use of the Sense HAT


emulator with Python, there will be a need for you to
change the line from sense_hat import SenseHAT in all
programs to from sense_emu import SenseHat instead.

To make them run on a physical Sense HAT again, all you


will need to do is to change the line back.

To make use of the SenseHAT or the Sense HAT emulator


in a python program, there will be a need for importing the
sense HAT library. Get the following typed into the scrip
area while also recalling to use sense_emu instead
of sense_hat in a situation where you are making use of the
Sense HAT emulator:

155
from sense_hat import SenseHat sense = SenseHat()

The Sense HAT is made up of a simple function used for


taking a message, getting it formatted so that it can get
displayed on the LED and it can also be scrolled smoothly.
To do this, type in the following:

sense.show_message("Hello, World!")

Get your program saved as Hello Sense HAT and select the
Run button. This will result in the display of your message
slowly across the sense HAT’S LED matrix which lights up
the LED pixels to show each letter in turn.

The show message() functions can be used to perform


more things. Get back to your program and get the last line
edited:

156
sense.show_message("Hello, World!", text_colour=(255,
255, 0), back_colour=(0, 0, 255), scroll_speed=(0.05))

The extra instructions that are being separated with the


use of commas are called the parameters and they can be
used in controlling different aspects of the show message()
function.

The scroll_speed=() function us used in changing how fast


the message scrolls across the screen.

The 0.05 value causes the scrolling to be twice the usual


speed. It is to be noted that the more the number the
slower the speed.

The text_colour=() with the back_colour=() parameters


that are spelled in the British English way unlike most
Python instructions helps in setting the writing and
background color respectively. It is important to note that,
they do not accept the use of the color names, the color
you want to use needs to be stated in a trio of numbers.

The first number is used to indicate the amount of red in


the color, from 0 for no red at all to 225 for as much red as
possible; the second number indicates the amount of green
in the color, the third number is the amount of blue.
157
All these colors are known as the RGB all together denoted
by RGB which stands for red, green as well as blue.

Select the Run icon and watch as the Sense HAT. You will
notice that the message will start to scroll considerably
faster and it will be in bright yellow on a blue background.

To find the speed and color combination that you will


prefer, you can change the parameters.

In a situation where you like to make use of friendly names


rather than the RGB values in setting your colors, you will
need to get variables created. Just above the
sense.show_message() line, add the commands:

yellow = (255, 255, 0) blue = (0, 0, 255)

158
The go back to your sense.show_message() line and get it
edited to read:

sense.show_message("Hello, World!",
text_colour=(yellow), back_ colour=(blue),
scroll_speed=(0.05))

Select the run icon again and observe that nothing has
changed. You will still have the blue in the background
with the color of your message remaining in yellow. The
variable names used here will make your code more
readable instead of the use of a string of numbers while the
code helps in explaining the color it is setting. You can
define as many colors as you want such as adding a variable
called red with the values 255, 0 and 0. The value
255,255,255 is used for variable white and the black variable
is displayed with the use of parameters 0, 0, 0.

Apart from scrolling full messages, you also get to display


individual letters. To do this, delete your
sense.show_message() line altogether and type in the
following instead:

sense.show_letter("Z")

159
Select Run and the letter Z will appear on the display of the
Sense HAT. This time, it will not scroll automatically but
stay there instead unlike messages.

The sense.show_letter() can be controlled using the same


color parameters like the sense.show_message(), trying to
change the tie color of the letter to red.

Drawing with Light


The LED display of the Sense HAT can also be used in
displaying pictures. You can treat each LED as a single-
pixel with an image you prefer which enables you to
implement the use of programs as well as animation in
your programs.

There will be a need to change individual LEDs to get


drawings created. To achieve this, you will need to have an
160
understanding of how the LED matrix of the Sense HAT is
laid out to get a program written which will turn on or off
the correct LEDs.

The LEDs in the rows and columns are both eight in


number. When counting LEDs just like most programming
languages, counting should start from 0 and ends in 7.

We have the first LED at the top-left corner with the last at
the bottom right.

The coordinates of any LED on the matrix can be found by


making use of the numbers from the rows and columns.
For instance, the blue LED in the pictured matrix is located
at coordinates 0, 2 with the red LED being at coordinates 7,
4. Across the matrix, the X-axis comes first and down the
matrix is the Y-axis.
161
It is advisable to draw your pictures using your hand first
on gridded paper when planning on pictures to draw on
the Sense HAT. You can also make use of the spreadsheet
such as the LibreOffice calc to get things planned.

Pictures in Python
Get a new program started in Thonny and get is saved as
Sense HAT drawing and type in the following and make
sure you remember to use sense_emu instead of the
sense_hat in the case you are using the emulator:

from sense_hat import SenseHat sense = SenseHat()

Make sure you use both of these lines in your program to


use the sense HAT and then type in:

sense.clear(255, 255, 255)

Click on the run icon and remember not to look directly at


the Sense HAT’s LEDs. The LEDs will turn into a bright
white which is why you are advised not to look directly at
them when you run your program.

162
The sense.clear() is used in clearing the LEDs of the
previous programming and it also accepts RGB color
parameters which help in changing the display to any color
that works for you. Edit the line to:

sense.clear(0, 255, 0)

Select Run which will result in the sense HAT turning to


bright green. Try to experiment with the use of different
colors or get color-name variables added which was
created for your Hello World programs to read things more
easily.

163
Make use of the RGB values for black which has red at 0,
blue at 0 and green at 0 to clear your LEDs. Alternatively,
you can get the line of your program edited to read:

sense.clear()

Once you run this the sense HAT will get dark. The
brackets being empty in the above functions indicates that
the LEDs should turn into black, on the other hand, switch
them off. It is the function used to completely have the
LEDs cleared in your programs.

164
To get your version of the LED matrix created as earlier
shown in this book using two specifically selected LEDs
which are lit up in red and blue, you are required to get the
following lines added to your program after sense.clear():

sense.set_pixel(0, 2, (0, 0, 255)) sense.set_pixel(7, 4, (255, 0,


0))

The first pair is used to indicate the location of the pixel on


the matrix, X-axis which is across followed by the Y-axis.

The second numbers which are in the second bracket in


the first are the RGB values of the pixel’s color.

Select the Run button to see results. This will cause the two
LEDs on your Sense HAT to light up.

Get the two lines deleted and get the following typed in:

sense.set_pixel(2, 2, (0, 0, 255))

sense.set_pixel(4, 2, (0, 0, 255))

sense.set_pixel(3, 4, (100, 0, 0))

sense.set_pixel(1, 5, (255, 0, 0))

sense.set_pixel(2, 6, (255, 0, 0))

165
sense.set_pixel(3, 6, (255, 0, 0))

sense.set_pixel(4, 6, (255, 0, 0))

sense.set_pixel(5, 5, (255, 0, 0))

View the coordinates and get them compared to the matrix


before clicking Run which will display to you the pictures
that will be drawn.

Making use of the individual set_pixel() to get a picture


drawn is slow. You can, however, speed things up by
getting multiple pixels changed at the same time.

Get all the set_pixel() lines deleted and type in the


following:

g = (0, 255, 0) b = (0, 0, 0)

creeper_pixels = [

g, g, g, g, g, g, g, g,

g, g, g, g, g, g, g, g,

g, b, b, g, g, b, b, g,

g, b, b, g, g, b, b, g,

g, g, g, b, b, g, g, g,
166
g, g, b, b, b, b, g, g,

g, g, b, b, b, b, g, g,

g, g, b, g, g, b, g, g ]

sense.set_pixels(creeper_pixels)

Then the next thing is to click Run;

The first two lines result in the creation of two variables to


hold colors: green and black.

The variables are made single letters “g” for the green with
the “b” for black which is used to make the code for
drawing easier to write and read.

The next block of code helps in creating variables that help


to hold color values for all the 64 pixels on the LED matrix
which are separated with commas and are enclosed in
between square brackets. Color variables created earlier are
used instead of numbers.

Lastly, to draw the entered matrix all at once,


sense.set_pixels(creeper_pixels) will take the variables with

167
the use of sense.set_pixels() function which is much easier
than trying to draw pixel by pixel.

Images can also be created and flipped as a way to help


images shown in the right way up when the sense HAT is
being turned around or for creating simple animations
with the use of a single asymmetrical image.

Edit your creeper_pixels variable to close his left eye to get


started by getting the four “b” pixels replaced. You are
required to start with the first two at the third line and
then on the fourth line, the first two is replaced with “g”:

creeper_pixels = [

g, g, g, g, g, g, g, g,

g, g, g, g, g, g, g, g,
168
g, g, g, g, g, b, b, g,

g, g, g, g, g, b, b, g,

g, g, g, b, b, g, g, g,

g, g, b, b, b, b, g, g,

g, g, b, b, b, b, g, g,

g, g, b, g, g, b, g, g ]

Select Run and to have the left eye of the creeper closed.

Go to the top of your program and add the line below to


create an animation:

From time import sleep

After this, go to the bottom and type:

while True:

sleep(1)

sense.flip_h()

Select Run and this will result in the creeper closing and
opening its eyes one at a time.

169
The flip_h() function will get an imaged flipped on the
horizontal axis.

Replace the sense.flip_h() with sense.flip_v() to get the


image flipped on its vertical axis.

The sense.set_rotation(90), can be used in rotating images


by 0,90.180 or 270 degrees depending on the selection of
the degree numbers.

Sensing the world around you

The sensors that are available on the Sense HAT’s LED


matrix is used in performing various functions. It helps you
in taking readings of different parameters ranging from
temperature to acceleration and make use of them in the
program as it fits.

170
EMULATING THE SENSORS
The inertial and environmental sensor simulation will need
to be emulated to make use of the Sense HAT emulator. To
do this, take the following steps:

i. Go to the emulator and select Edit

ii. Select Preferences.

iii. Click on the box which is next to the Environmental


sensors as well as the inertial measurement unit to mark
them.

iv. Finally, click on the Close button.

Environmental sensing

Environmental sensors such as the barometric pressure


sensor, temperature sensor, and humidity sensor are used
in taking environmental measurements surrounding the
Sense HAT.

Environmental Sensing In Python


Create a new program in Thonny and save it as sense HAT
sensor afterward to begin taking readings from sensors.

171
Type in the following lines in the script area which you
should do always with the Sense HAT and always
remember to make use of the sense_emu if making use of
an emulator:

from sense_hat import SenseHat

sense = SenseHat()

sense.clear()

It is advisable to always add sense.clear() at the beginning


of your programs if the display on the Sense HAT is still
showing things from the last program.

Type the line below to help take the reading from the
pressure sensor:

pressure = sense.get_pressure() print(pressure)

Select Run and this will result in a number getting printed


to the Python shell at the bottom of the window. This
number is simply the air pressure reading that is detected
by the barometric pressure sensor and it is measured in
millibars.

While clicking on the Run icon again, try to blow on the


Sense HAT or simply move the pressure slider located in
172
the emulator up which should make the number higher
this time.

Changing Values
The values that are reported by the emulated sensors can
also be changed with the use of the sliders and buttons if
you are making use of the Sense HAT emulator. You can
try to slide the pressure sensor setting down towards the
button and then click on Run again.

Remove the last two lines of code and get them replaced
with the line below to switch to the humidity sensor:

humidity = sense.get_humidity()

print(humidity)

173
Click run to have a number displayed to the python shell.
This number denotes the current relative humidity of the
room and it is depicted with a percentage. Blow the Sense
HAT again or move the slider of the emulator humidity up
which will result in it going up again when the program is
run again.

Remove the last two lines of the programs and replace


them with temperature for the temperature sensor:

temp = sense.get_temperature()

print(temp)

Select Run again and the temperature will be displayed in


degrees Celsius. It is to be noted that this may not be the
exact room temperature because the Raspberry Pi produces
heat all the time its working causing the sense HAT and its
sensors to warm up as well.

174
The sense HAT displays the temperatures based on the
temperature sensor reading which is built into the
humidity sensor. You can make use of the line:
sense.get_temperature_from_pressure() to make use of the
reading from the pressure sensor instead.

You can get the two readings combined to derive an


average which may be more accurate unlike using either of
the sensors alone. To do this, you should delete the two
lines of your program and input:

htemp = sense.get_temperature()

ptemp = sense.get_temperature_from_pressure()

temp = (htemp + ptemp) / 2

print(temp)

Click on the Run icon again and a number will be printed


on the Python console. These readings will be based on
175
both sensors that have been added divided by two which
will result in an average result. In a situation where you are
making use of the emulator, all the three methods will
result in the same number:

176
Chapter 23: Inertial Sensing
The inertial measurement unit (IMU) is the combination of
the gyroscopic sensor, accelerometer including the
magnetometer. These sensors technically take
measurements from the surrounding environments like the
environmental sensors.

For instance, the magnetometer is used in measuring the


magnetic field strength and they are usually used for data
as regards the movement of the sense HAT itself.

The IMU sums up multiple sensors. You are allowed to


take the readings from each sensor independently by some
programming languages while a combined reading is giving
by some.

For the IMU, the Sense HAT and the Raspberry Pi it is


being attached to can move along the three spatial axis that
is side to side on the X-axis as well as forwards and
backward on the Y axis, while it moves up and down on the
Z-axis. It can also get rotated along the three axes but it is
to be noted that their name will change. When rotation is
along the X-axis, it is called the roll while along the Y-axis
is called the pitch and lastly the z-axis is called the Yaw.

177
In a situation where you are rotating the sense HAT along
the short axis, it means you are rotating along with its
pitch while along its long axis is called the roll and when it
is rotated around while it is being kept flat on the table, it
means you are adjusting the yaw.

It is analogous to the airplane when it is taking off, the


pitch is increased as it climbs and when it’s dong the
victory roll, it means it spinning along its roll axis and
when it is making use of the rudder to turn like a car
without rolling, it is called the yaw.

Inertial sensing in Python


Get a new program started in Thonny and get it saved as a
sense HAT movement.

178
The usual starting lines should be filled in and do not
forget to use sense_emu in case you are making use of the
Sense HAT emulator:

from sense_hat import SenseHat sense = SenseHat()


sense.clear()

Work out the current orientation of Sense HAT on its three


axes to make use of information from the IMU by typing
out the following:

orientation = sense.get_orientation()

pitch = orientation["pitch"]

roll = orientation["roll"]

yaw = orientation["yaw"]

print("pitch {0} roll {1} yaw {2}".format(pitch, roll, yaw))

Select Run to view the see the readings for your sense
HAT’s orientation which is split across the three axes.
Rotate the sense HAT again and click on Run again which
should display the number changed which will reflect the
new orientation.

179
Apart from measuring orientation, the IMU can also be
used in detecting movement. The IMU needs to be read
frequently in a loop to get accurate movement readings
unlike the orientation which takes a single reading and it
will eventually get incorrect information for the detection
of movement.

Make use of sense.clear() in deleting everything and type in


the following code:

while True:

acceleration = sense.get_accelerometer_raw()

x = acceleration['x']

y = acceleration['y']

z = acceleration['z']

180
Your result will be variables that will contain the current
accelerometer readings for the three spatial axes which
include the X for the left and right, Y for the forwards and
backward as well as the Z for the up and down.

The number displayed by the accelerometer sensor may be


difficult to read, so it’s advisable to round them up to the
nearest whole number by making use of the following
lines:

x = round(x)

y = round(y)

z = round(z)

Print the resulting values afterward by making use of the


line below:

print("x={0}, y={1}, z={2}".format(x, y, z))

Click Run to see the accelerometer values printed to the


Python shell area. This will get printed continuously unlike
the previous program. To stop the continuous printing, you
will need to stop the program by clicking the red stop
button.

181
It must have been observed that the accelerometer is
showing that one of the exes which are the z-axis in a case
where your Pi lies flat on the table have an acceleration of
the value 1.0 gravities (1G) with the sense HAT remaining
stagnant. This is because it’s detecting the gravitational
pull of the earth. The gravitational pull is the force that is
pulling the sense HAT down towards the earth center.

Pick up the Sense HAT and Raspberry Pi carefully and


rotate them around while the program is running and sure
to be careful not to dislodge any cable. You will get to see
the values changed such that the Z-axis will read 0G and
the X-axis now reading 1G while the Pi’s network and the
USB ports are pointing towards the floor. Get it turned
again such that the HDMI and power ports will be pointing
to the floor and now the Y-axis will read 1G.

182
If the opposite is done with the HDMI port pointing to the
ceiling, this will result in -1G on the Y-axis.

Combining the knowledge of the gravity of the earth which


is about 1G and that of the spatial axes knowledge, the
accelerometer reading can be used in figuring out which
way is down including which way is pointing up. It can also
be used in the detection of movement.

Shake the sense HAT and Raspberry Pi carefully and watch


the number as you do so, it will be observed that the
harder you shake the more the acceleration.

With the use of sense.get_accelerometer_raw(), you are


notifying the sense HAT to get the other two sensors in the
IMU i.e the gyroscopic sensor and the magnetometer
turned off and then get the data returned purely from the
accelerometer. The same action can be carried out with the
other sensors as well.

Make use of the line acceleration which is


sense.get_accelerometer_raw() and get it changed to:

orientation = sense.get_gyroscope_raw()

183
Alter all the word acceleration available on the three lines
below it to orientation.

Clicking on Run will display the orientation of the Sense


HAT for all the three axes with all rounded up to the
nearest whole number. All data are coming purely from the
gyroscope without the use of the accelerometer or
magnetometer. This comes in handy in detecting the
orientation of a moving sense HAT at the back of a robot.

You can put a stop to the program by clicking on the red


stop button. Delete everything available on your program
except the first four lines and type in the below to make
use of the magnetometer:

While True line:

north = sense.get_compass()

print(north)

Click on Run to execute your program and you will see


magnetic north direction printed repeatedly to the Python
shell area. By rotating the sense HAT carefully, you will get
to see the heading change as the orientation of the sense
HAT relative to the north shifts. This is a compass in the

184
making, you can see the way this works with the use of a
fridge magnet by trying to move it around the sense HAT
to view what will happen to the readings on the
magnetometer.

JOYSTICK CONTROL
The joystick of the Sense HAT is located at the bottom-
right corner, though it is small it’s a very powerful tool. It
can recognize input in four directions that are up, down,
left and right. It is also made up of a fifth input which can
be accessed by getting it pushed down from above like a
push-button switch.

WARNING

Your spacers being fitted should be the only reason for


using the joystick of the Sense HAT. In the absence of the
spacers, the pushing down on the joystick can flex the
sense HAT board and thereby cause damage to both the
sense HAT as well as the GPIO header of the Raspberry Pi.

Joystick control in Python


Get a new program started in Thonny and get it saved as
sense HAT joystick. Get started with the usual three lines
185
that are used in setting up the Sense HAT and clear the
LED matrix:

from sense_hat import SenseHat

sense = SenseHat()

sense.clear()

The next thing is to get the infinite loop set up:

While True:

Then notify Python to listen for inputs coming from the


Sense HAT joystick using the flowing line with Thonny
indenting automatically for you:

for event in sense.stick.get_events():

Lastly, get the line below added which Thonny will indent
for you again. This line will cause an action to take place
whenever you press the joystick:

print(event.direction, event.action)

Select Run and try to move the joystick in a different


direction. The direction chosen will be printed to the
Python shell area either up, down, left or right and when

186
the joystick is being pushed down just like a push button
switch it will have middle printed.

Each time the joystick is pushed once, you will be given


two events:

One event pressed for when your first push a direction.

The other event, released for when the joystick returns to


the center. This can also be used in your programs. For
instance, think of a game character that can be made to
start moving as soon as the joystick is pressed in a
direction then stops again as soon as it is released. The
joystick can be used in triggering functions and it is not
limited to just being used for loop. Get everything below
the sense.clear() deleted and input in the following:

def red():

sense.clear(255, 0, 0)

def blue():

sense.clear(0, 0, 255)

def green():

sense.clear(0, 255, 0)

187
def yellow():

sense.clear(255, 255, 0)

These functions will change the whole sense HAT LED


matrix into a single color which could be red, blue, green
or yellow which enables you to see the program more
clearly. To get them triggered, you will need to notify
Python which functions works with whichever joystick
input.

Get the following fines typed in:

sense.stick.direction_up = red sense.stick.direction_down =


blue sense.stick.direction_left = green
sense.stick.direction_right = yellow
sense.stick.direction_middle = sense.clear

Lastly, the program will need an infinite loop which is


otherwise called the main loop for it to keep running so
you will need to keep watching for joystick inputs instead
of just running the code you have written once you are
quitting. Get the following lines typed in:

while True: pass

188
Select run and try to move the joystick. The LED will get
lighted up displaying colors.

To get the LEDs turned off, get the joystick pushed like a
push-button. The middle direction is set to make use of the
line sense.clear() function which turns the LEDs all off.

Chapter 24: Python project—Getting


started with the Camera Module

This tutorial is compiled to teach you how to connect the


Raspberry Pi Camera Module to your Raspberry Pi and take
pictures, record video, and apply image effects.

189
What you will need

Raspberry Pi computer with a Camera Module port


All the current Raspberry Pi models have a port for you to
connect the Camera Module.

Note: The Raspberry Pi Zero has a smaller port for the


Camera Module, so if you want to use a Pi Zero, make sure
you get the right Camera Module ribbon cable.

190
Raspberry Pi Camera Module

There are two versions of the Camera Module:

● The Standard version: This can only capture images in


normal lighting conditions.

● The Noir version: Although it has no infrared filter, an


infrared light source can be attached to capture images in
extremely low light.

Connecting the Camera Module

Ensure your Raspberry Pi is turned off.

1. Find the Camera Module port.

2. Open the port by carefully pulling up the edges of the


plastic clip.

191
3. Insert the Camera Module ribbon cable with the panel
facing downward.

4. Lock back the port by pushing the plastic clip back in


place.

192
 Boot the Raspberry Pi.
Open the main menu, then under preferences select the
Raspberry Pi Configuration tool.

Enter the Interfaces tab and make sure the camera is


enabled:

● Restart the Raspberry Pi.


193
How to control the Camera

Module via the command line

By now, you have connected the Camera Module and the


software is enabled, use any of these two command tools,
raspistill or raspivid.

● Click the black monitor icon in the taskbar to open a t

erminal window:

● Type the command in the image below to take stills and


save them on your desktop:

raspistill -o Desktop/image.jpg

194
● Click Enter to run the command.

If you run the command, a camera preview will display for


five seconds, then a still photo will be taken.

● Find your picture’s file icon on your desktop, then


double-click the icon to open your picture.

195
You can add more options to set the size and look of the
image the raspistill command takes.

● You can add -h to change the height of the image and -w


for the width:

raspistill -o Desktop/image-small.jpg -w 64

● Use the raspivid command below to record a video with


the Camera Module.

raspivid -o Desktop/video.h264

● The video.h264 file will be saved to your desktop,


double-click the file icon to play it with VLC Media Player.

How to control the Camera Module using Python code

With the Python picamera, you can control the Camera


Module to make interesting projects.

● Open a Python 3 editing software, like the Thonny


Python IDE:

196
● Create and save the new file as camera.py.

● Note: Ensure you don’t save the file as picamera.py.

● Type in the following code:

from picamera import PiCamera

from time import sleep

camera = PiCamera()

camera.start_preview()

sleep(5)

camera.stop_preview()

197
● Save, then launch the program. The camera preview will
display for five seconds.

Note: A display monitor has to be connected to the Pi for


this to work, you can’t see the camera preview if you use
remote access like SSH or VNC.

Enter the following code to rotate your preview by 180


degrees, if it’s upside-down:

camera = PiCamera()

camera.rotation = 180

● To rotate the image, set rotation to any angle (90, 180 or


270). You can set rotation back to 0 degrees to reset your
image.
It’s easier to see any error in the program if you make the
preview a bit see-through.

● Set an alpha level to make the preview see-through:

camera.start_preview(alpha=200)

The alpha value can be set within 0 to 255.

198
Take still pictures with Python code

After setting the commands, you can now capture images


with your Camera Module.

Change the code to add a camera.capture() line:

camera.start_preview()

sleep(5)

camera.capture('/home/pi/Desktop/image.jpg')

camera.stop_preview()
Note: Set the sleep mode for at least two seconds, this
should be sufficient time for the camera sensors to register
lighting conditions.

● Launch the code.

The camera preview will display for five seconds, then a


still photo will be taken. The preview will adjust the
resolution while taking the picture.

The image will be saved to your desktop.

Take five photos at once by adding a loop:

camera.start_preview()

199
for i in range(5):

sleep(5)

camera.capture('/home/pi/Desktop/image%s.jpg' %
i)

camera.stop_preview()

The variable i indicates the amount of times the loop has


run, from 0 to 4. Your photos will be saved as image0.jpg,
image1.jpg till it gets to image0.jpg.

● Launch the code to take more pictures with your Camera


Module.
The camera will capture an image every five seconds,
stopping after the fifth photo.

● Check the five new images on the desktop.

Recording video with Python code

Now, let’s try videos.

Change the code by removing capture() and replacing it


with start_recording() and stop_recording()

Write it as shown in the image below:

200
camera.start_preview()

camera.start_recording('/home/pi/Desktop/video.h26
4')

sleep(5)

camera.stop_recording()

camera.stop_preview()

Launch the code.

Your Raspberry Pi will display a 5 seconds preview,


recording the video before closing.

How to change image settings and add image effects

The Python picamera software supports several effects


and configurations that you can use to edit how your
images look.

Note: Some settings will modify just the preview, some will
only modify your image and some can modify both.

Set the Image Resolution

Here is how to change the resolution of the image taken


by the Camera Module.
201
The default resolution for your image is set to your
monitor’s resolution. The maximum resolution for pictures
and videos are 2592×1944 and 1920×1080 respectively.

● Type the following command to set the maximum


resolution for your picture:

Note: You have to set the frame rate to 15 to enable


maximum resolution.

camera.resolution = (2592, 1944)

camera.framerate = 15

camera.start_preview()

sleep(5)

camera.capture('/home/pi/Desktop/max.jpg')

camera.stop_preview()

64×64 is the minimum resolution.

Change the resolution to 64×6 to take pictures at the


lowest resolution.

Add text to your image

202
Use the command annotate_text to add text to your
image.
Write and launch the code to try it:

camera.start_preview()

camera.annotate_text = "Hello world!"

sleep(5)

camera.capture('/home/pi/Desktop/text.jpg')

camera.stop_preview()

Change the look of the added text

Use the following command to change the size of your text:

camera.annotate_text_size = 50

Although the default size is 32, you can change it to any


size within 6 to 160.

You can also change the color of your text.

● The first step is to add Color to your import line at the


beginning of the program:

from picamera import PiCamera, Color

203
● Change the code under the import line to the following:

camera.start_preview()

camera.annotate_background = Color('blue')

camera.annotate_foreground = Color('yellow')

camera.annotate_text = " Hello world "

sleep(5)

camera.stop_preview()

Change the brightness of the preview


The default brightness is 50 but you can change it to any
value from 0 to 100.

● Launch the following code to try it:

camera.start_preview()

camera.brightness = 70

sleep(5)

camera.capture('/home/pi/Desktop/bright.jpg')

camera.stop_preview()

204
The following code adjusts the brightness and adds text
that displays the current brightness level:

camera.start_preview()

for i in range(100):

camera.annotate_text = "Brightness: %s" % i

camera.brightness = i

sleep(0.1)

camera.stop_preview()

Change the contrast of the preview


You can change the contrast of your preview, just like you
changed the brightness.

Run the following code to try this out:

camera.start_preview()

for i in range(100):

camera.annotate_text = "Contrast: %s" % i

camera.contrast = i

sleep(0.1)
205
camera.stop_preview()

Add cool image affects

You can apply any effect by using camera.image_effect.


The effect options include:

 None
 Negative
 Solarize
 Sketch
 Denoise
 Emboss
 Oilpaint
 Hatch
 Gpen
 Pastel
 Watercolor
 Film
 Blur
 Saturation
 Colorswap
 Washedout
 Posterise

206
 Colorpoint
 Colorbalance
 Cartoon
 deinterlace1
 deinterlace2

The default is set to none.

● To try out any photo effect:

camera.start_preview()

camera.image_effect = 'colorswap'

sleep(5)

camera.capture('/home/pi/Desktop/colorswap.jpg')

camera.stop_preview()

● Launch this code to loop in all the image effects using


camera.IMAGE_EFFECTS:

camera.start_preview()

for effect in camera.IMAGE_EFFECTS:

camera.image_effect = effect

camera.annotate_text = "Effect: %s" % effect


207
sleep(5)

camera.stop_preview()

Set the image exposure mode

You can set the exposure by using


camera.exposure_mode.
These are the various exposure modes:

 off
 auto
 night
 nightpreview
 backlight
 spotlight
 sports

208
 snow
 beach
 verylong
 fixedfps
 antishake
 fireworks

Exposure is preset to auto.

● To choose any exposure mode and try it:

camera.start_preview()

camera.exposure_mode = 'beach'

sleep(5)

camera.capture('/home/pi/Desktop/beach.jpg')

camera.stop_preview()

● You can use camera.EXPOSURE_MODES to loop over


the various exposure modes.

209
Change The Image’s White Balance
You can preset the white balance using
camera.awb_mode.
The available white balance modes are:

 off
 auto
 sunlight
 cloudy
 shade
 tungsten
 fluorescent
 incandescent
 flash
 horizon

The white balance is preset to auto mode.

● To try out an auto white balance mode use this:

camera.start_preview()

camera.awb_mode = 'sunlight'

sleep(5)
210
camera.capture('/home/pi/Desktop/sunlight.jpg')

camera.stop_preview()

● You can use camera.AWB_MODES to loop over the


white balance modes.

Chapter 25: Python project—Make a


Push Button Stop Motion
You can use a Raspberry Pi 4S, Python and a Camera
Module to make stop motion animation videos or take
pictures, using a push button connected to the Pi’s GPIO
pins as the controller. You can animate a LEGO tower,
figures in a scene and much more.

What you will need

● Raspberry Pi camera module

● 1 x Full size breadboard

● 2 x Male-to-female jumper leads

● 1 x Tactile button

211
Software

You have to install the following packages:

libav-tools
You need an internet connection to install the packages.
You must update and upgrade your system, before
proceeding. Open the terminal, then enter the following
commands:

You can now install the required packages:

● Ensure that you have installed libav-tools, to check,


enter avconv at the command line.

212
The Camera

Connect the camera before starting your Raspberry Pi.

The camera port is beside the Ethernet port, pull up the


cover tab.

1.Insert the strip in the connector, with the blue side facing
the Ethernet port.

2. Push the tab down while holding the strip in place.

3. Start up your Raspberry Pi.

Test the camera

Enter the following command to open a terminal window


in the application menu:

213
A preview will be displayed on your screen. Don’t worry if
the display is upside down, you can fix it later. To exit the
preview, press Ctrl + C.

To view the files in your home directory, run the command


ls; the icon for image1.jpg will be listed. Double-click
image1.jpg to preview it.

To view more folders and files, open the file manager by


clicking the icon on the taskbar.

Take a picture with Python

Launch Python 3 (IDLE) at the main menu:

214
To open the Python file editor, click File > New Window
in the menu.

With great care, enter the following code into the new
window. (Pay attention to case!):

from picamera import PiCamera

from time import sleep

camera = PiCamera()

camera.start_preview()

sleep(3)

camera.capture('/home/pi/Desktop/image.jpg')

camera.stop_preview()

Choose File > Save in the menu (or use Ctrl + S), then save
the file as animation.py.

Use F5 to launch your program.

The image.jpg will be saved on your Desktop. To open the


image, double-click the icon.

If your photo is upside-down, you can fix this manually by


repositioning the camera using a mount, or you can use
215
Python to flip the image. Add the following to your
command line to do this.

camera.rotation = 180

after camera = PiCamera(), so it becomes:

from picamera import PiCamera

from time import sleep

camera = PiCamera()

camera.rotation = 180

camera.start_preview()

sleep(3)

camera.capture('/home/pi/Desktop/image.jpg')

camera.stop_preview()

When you rerun the file, image.jpg will be overwritten


with a new image, which is in the right orientation. Don’t
forget to keep these lines in your code when you alter it in
the next steps.

216
Connect a Hardware Button
Connect the Raspberry Pi to the button, using your
breadboard and jumper leads. Run your connection as
shown in the diagram below:

Import Button from the gpiozero module at the summit


of the code, create a Button connected to pin 17, and
replace the sleep line with button.wait_for_press, as
shown below:

from picamera import PiCamera

from time import sleep

from gpiozero import Button

button = Button(17)

camera = PiCamera()

217
camera.start_preview()

button.wait_for_press()

camera.capture('/home/pi/image.jpg')

camera.stop_preview()

Save, then run the program.

When the preview starts, use the button connected to your


Raspberry Pi to take a picture.

Proceed to the file manager window to view your image, it


will be saved as image.jpg. Double-click the icon to view.

Take a selfie
To take a picture of yourself with the camera board, you
need to add a delay, so you can get in position. You can
modify the program to accomplish this.

Add the following line in your code to instruct the program


to sleep briefly before taking a photo:

camera.start_preview()

button.wait_for_press()

218
sleep(3)

camera.capture('/home/pi/Desktop/image.jpg')

camera.stop_preview()

Save, then run the program.

Press the button to take your selfie. Try to keep the camera
steady, it is better if you use a mount. You can then return
to the file manager, to check your image. Launch the
program again to take another selfie.

Stop Motion Animation

Now that you have taken individual photographs with the


camera, let us combine a few still images to make a stop
motion animation.

IMPORTANTL You need to create a new folder to store


the stills. Enter mkdir animation in the terminal window.
Modify the code to add a loop to keep taking pictures
whenever you press the button:

camera.start_preview()

frame = 1

219
while True:

try:

button.wait_for_press()

camera.capture('/home/pi/animation/frame%03d.jpg'
% frame)

frame += 1

except KeyboardInterrupt:

camera.stop_preview()

break

Because while True goes on forever, you need to find a


way to exit it gracefully. Using try and except shows it can
deal with an exceptional situation - if you force-stop it with
Ctrl + C the camera preview will close and exit the loop.

frame%03d indicates that the file will be saved as “frame”


followed by a 3-digit number with two leading zeroes - 001,
002, 003, etc. This makes it easy to sort the images the in
correct order, when making your video.

Now, you can set up the animation subject (e.g. LEGO) and
prepare to begin the stop motion animation.
220
To capture the first frame, press the button, then adjust the
animation subject and press the button again to capture
each successive frame.

Once you are satisfied with your footage, press Ctrl + C to


end the program.

Go to your file manage, open the animation folder to view


your stills collection.

Generate the video


To create a video, return to the terminal window.

Run the command for rendering videos:

avconv -r 10 -i animation/frame%03d.jpg -qscale 2


animation.h264

Note: you’re still using %03d - this format is supported by


Python and avconv, so your images will be imported into
the video in the right order.

If you are given the avconv: command not found, then


you have to install libav-tools.

Open the terminal, then enter the following commands to


update and upgrade your system:
221
sudo apt-get update

sudo apt-get upgrade

You can now install libav-tools package:

sudo apt-get install

If you want to adjust the frame rate, edit the rendering


command. Try replacing -r 10 (10 frames per second) with
another number.

You can change the name of the rendering video to prevent


it from overwriting your previous attempt. Replace
animation.h264 with something else to accomplish this.

222
Chapter 26: Python project—Minecraft
Photobooth
Create a photo booth out of blocks in Minecraft, and
program it to take a photo of you (in real life!) as you enter
it.

What you will need

Hardware

● Raspberry Pi 4

● Raspberry Pi camera module

What you will learn

Setting up the Minecraft photo booth will teach you:

● How to use Python API to control the Minecraft world.

● How to find the x, y, and z coordinates of a player.

● How to trigger the camera module with the player’s


coordinates.

● How to use the while loops, and if functions in Python.

223
● This material covers aspects from the following strands
of the Raspberry Pi Digital Making Curriculum:

● Apply abstraction and decomposition to solve


complex problems

● Use basic digital, analogue, and electromechanical


components

Connect the Camera

Connect your camera and test it to make sure it works


before starting your Raspberry Pi.

Connect a Raspberry Pi Camera Module

You can use the Raspberry Pi Camera Module to take high-


definition video as well as photographs. You have to
connect the Camera Module to your Pi, if you intend to use
it:

● Before you begin, disconnect your Raspberry Pi from its


power source.

● Insert the flex cable of the camera into the connector


between the HDMI and Ethernet ports, make sure the
silver connectors are facing the HDMI port.

224
● To open the flex cable connector, first pull upwards at
the tabs on the top of the connector,then pull it towards
the Ethernet port.

● Insert the flex cable firmly into the connector, make sure
you don’t bend the flex so it becomes too sharp an angle.

● While you hold the flex cable in place, push the top part
of the connector towards the HDMI connector, then
downward.

To connect the camera, Restart your Raspberry Pi, make


sure that you disable the camera:

● Open the Menu, then enter Preferences and select


Raspberry Pi Configuration. Then ascertain that the
radio button for Camera in the Interfaces tab has been
checked.

Now, you have to test your camera, to make sure it’s


working. The quickest way is to open a Terminal window
and type the following:

raspistill -k

A preview image will display on your screen. To exit the


raspistill program type x and then press Enter.

225
Importing the Minecraft and PiCamera
Modules
To begin, you have to import the Minecraft API
(Application Programming Interface). This will allow you
to connect to Minecraft and use Python codes. You also
have to import the PiCamera module which controls the
camera and the time module to add a small delay between
taking the photos.

Go to the application menu and open Minecraft; create a


new world or enter an existing one.

Move the Minecraft window to the side of your screen.

To move the Minecraft window, use the Tab key to remove


it as the focus of your mouse. You are going to need it later
when you want to switch between the Minecraft and
Python windows.

Open the programming menu, then launch Python 3:

226
The Python IDLE code editor will open, you will it use to
write the photo booth program.

Open a new window by clicking New > Window.

Enter the following code:

from mcpi.minecraft import Minecraft

from picamera import PiCamera

from time import sleep

mc = Minecraft.create()

camera = PiCamera()

mc.postToChat("Hello world")

227
Use Ctrl + S to save, then use F5 to run the program. The
message “Hello world” will display on the Minecraft
window

Take A Picture

You will now have to write some code to take a picture


with the camera.

Go to the end of your program, then add the following


lines:

camera.start_preview()

sleep(2)

camera.capture('/home/pi/selfie.jpg')

camera.stop_preview()

To give yourself enough time to strike a pose and smile


before taking a picture, set the camera to show a two
second preview. The image will be saved to your home
directory as selfie.jpg.

To take a photo, Save and run the program.

You will find your photo in the File Manager.

228
Building a Photo Booth
Now, you have to build a photo booth in the Minecraft
environment. You can do this manually and set up the
photo booth anywhere you want.

Use any block of your preference to build the photo booth.


You can get creative with the shape, but you must leave at
least one block space of width within, for the player to
enter, similar to a door or gate.

After creating your photo booth, you have to move your


player inside and onto the trigger block. For the function
you wrote in step one, to run, to trigger the camera, the
player must stand on the trigger block.

229
Your position in the Minecraft environment is given in
reference to the x, y, and z axis. The x, y, z coordinates of
your player will be displayed at the top left of the window,
for example 10.5, 9.0, -44.3. When you are in the photo
booth, these coordinates should be the same as the x, y, z
coordinates of the ‘trigger’ block in your photo booth.

Move your player into the photo booth

Note the x, y, z, coordinates of your camera ‘trigger’ block.

Finding Your Position


When playing Minecraft, the program will have to verify
that you are inside the photo booth. If you are, it will
trigger the take_the_pic function to capture a photo with
the camera. Minecraft has to know your location in the
Minecraft world to do this.

You can find your position, by using the code, x, y, x =


mc.player.getPos(). This will save the x, y, and z position
of your player in the variables x, y, and z. After that, you
can use print(x) to print the x value, or print(x, y, z) to
view all of them. Now that you know the position of your
player, you can check if he/she is in the photo booth.

230
Since we are using Minecraft, we can use mc.postToChat
to send the coordinates to the Minecraft window.

To change the message “Hello world” to “Find the photo


booth” after the Minecraft.create() line write:

mc = Minecraft.create()

mc.postToChat("Find the photo booth")

Add it to the end of your code:

while True:

x, y, z, = mc.player.getPos()

mc.postToChat((x, y, z))

Now, save and run your code and your coordinates will be
displayed on the Minecraft window.

Then, focus on the Python window and press Ctrl + C to


halt the running code.

Testing Whether You Are In the Photo Booth


Now that you have a photo booth, the coordinates of the
trigger block, and code for controlling the camera module
and to take your photo.
231
This next code is meant to confirm if the program will
identify when you are in the photo booth. You have to
create a loop that checks if the player’s coordinates match
the trigger block coordinates.

It should match, when you are standing in the photo


booth. You will use a simple if statement called a
conditional, to do this.

Use the following to test the player’s position by changing


the lines inside your while loop:

while True:

x, y, z = mc.player.getPos()

sleep(3)

if x >= 10.5 and y == 9.0 and z == -44.3:

mc.postToChat("You are in the photo booth!")

Notice that the if statement checks if x value is greater


than or equal to 10.5: this makes sure that it picks up the
block since it could have a value of 10.6.

Replace the coordinates in the if statement with those of


your own photo booth.

232
I need a hint

Change the x, y, and z values to the values of your photo


booth.

You have to change this line of code:

if x >= 10.5 and y == 9.0 and z == -44.3:

Incase the photo booth was at position 11.5, 3, 34.5 you


have to change that code too:

if x >= 11.5 and y == 3.0 and z == 34.5:

You may also have to change the operators >=, == to <=


based on the position and entrance of your photo booth.

Save and run to test the code: Enter the photo booth and
the message “You are in the photo booth!” will be displayed
in the Minecraft window.

Putting It All Together

Now that your photo booth is up and running, you can add
the camera module to take a photograph. Call the capture
code, and don’t forget to smile. Add the instructions for
sending messages to Minecraft and the call to capture() in
the if statement:
233
if x >= 10.5 and y == 9.0 and z == -44.3:

mc.postToChat("You are in the Photobooth!")

sleep(1)

mc.postToChat("Smile!")

sleep(1)

camera.start_preview()

sleep(2)

camera.capture('/home/pi/selfie.jpg')

camera.stop_preview()

sleep(3)

This will check your location and if your location matches


with that of the photo booth, the camera will take a photo.

234
Conclusion

We believe you have learnt a great deal from this guide.


Thanks for taking out the time to read through.

235

You might also like