Documente Academic
Documente Profesional
Documente Cultură
Guide
Graham O. Wilson
Copyright 2019 © Graham O. Wilson
All rights reserved. This book is copyright and no part of it
may be reproduced, stored or transmitted, in any form or
means, without the prior written permission of the
copyright owner.
Printed in the United States of America
Copyright 2019 © Graham O. Wilson
Contents
Introduction .............................................................................. 1
Chapter 1: Getting Started With Raspberry Pi 4 ....................... 2
Guided Tour of the Raspberry Pi .......................................... 4
Chapter 2: Discover the Items Essential for Setting up A
Raspberry Pi 4 ....................................................................... 17
Setting up The Software ..................................................... 30
Chapter 3:Using your Raspberry Pi ....................................... 35
The Chromium Web Browser ............................................. 43
The File Manager ............................................................... 46
The Raspberry Pi Configuration tool ................................... 58
Chapter 4: Programming with Scratch.................................... 64
Introducing the Scratch 2 interface ..................................... 65
Looping the Loop................................................................ 74
Chapter 5: Project 1--Astronaut Reaction Timer ....................... 1
Chapter 6: Project 2--Synchronized Swimming ........................ 7
Chapter 7: Project 3--Archery Game ........................................ 1
Chapter 8: PROGRAMMING WITH PYTHON .......................... 5
Introducing the Thonny Python IDE ...................................... 6
Your First Python Program: Hello, World! ............................. 8
Chapter 9: Project 1: Turtle Snowflakes ................................. 14
Chapter 10: Physical Computing with Raspberry Pi ............... 26
Introduction to GPIO header ............................................... 26
Chapter 11: Your first Physical Computing Program: Hello,
LED!....................................................................................... 37
Chapter 12: LED Control in Python ........................................ 41
Chapter 13: Using a Breadboard ............................................ 43
Chapter 14: Reading a Button ............................................... 45
Reading a button in Python ................................................ 46
Chapter 15: Make Some Noise: Controlling a Buzzer ............ 49
Controlling a buzzer in Python ........................................... 50
Chapter 16: Python Project 2 Quick Reaction Game ............. 52
Chapter 17: Virtual Gaming with Raspberry Pi 4 .................... 58
Introduction
1
anything from internet-connected weather stations to retro
games.
This book will guide you if you plan to use your Raspberry
Pi to build robots, gaming consoles and various other
projects. Shall we?
2
In 2012, only a few thousand were built and they sold out
quickly, and since then, millions more have been sold all
over the globe.
People are now using the Raspberry Pi in their offices, data
entry centers, classrooms, factories, homes, spacefaring
balloons and self-piloting boats. The original Raspberry Pi
was called Model B and various models have since been
released after it, with each new model comes improved
specifications and specific features for specific use-case.
The Raspberry Pi Zero model for example, is a much
smaller (in size) and less power consuming version of the
Raspberry Pi, features that were dropped to achieve this,
includes the wired network port and the multiple USB
ports.
The latest version and most powerful version of the Pi, the
Raspberry Pi 4 Model B is the ultimate focus of this book,
3
so you will be provided with enough information about it.
This information can also be applied to other Raspberry Pi
models, so it will be useful to anyone using a different
model of the Raspberry Pi.
4
The Raspberry Pi 4 Model B
The Raspberry Pi’s small board may look like a lot is
crammed into it, but it is actually easy to understand, and
we are going to start with the components, the inner
workings responsible for its capabilities.
5
The Raspberry Pi’s Components
Much like the setup of any other computer, the Raspberry
Pi comprises different components, and they all contribute
to its functionality. On the top side of the board, check the
metal cap just above the center point for probably the most
important of these components: the system-on-chip (SoC).
6
on the RAM until you save it, then it will be written to the
microSD card.
The Ram and microSD card work together as the Raspberry
Pi’s volatile and non-volatile memory respectively. The ram
as the volatile memory will lose its contents, when you turn
of your Raspberry Pi, while the microSD card, the non-
volatile memory will retain its contents.
7
To the bottom edge of the board just behind the middle set
of USB ports is another black plastic-covered chip. This
chip is the USB controller, which runs the four USB ports.
You will find a smaller chip next to it called the network
controller; it runs the Pi’s Ethernet network port.
8
And if all of these seem confusing, don’t lose sleep over it,
because using a Raspberry Pi doesn’t require you to know
all of its components and their location on the board.
9
The Raspberry Pi’s USB ports
By the right of the USB ports is the Ethernet port which is
also called the network port. With this port, you can
connect the Pi to a wired computer network through a
cable called the RJ45 connector. Pay close attention to the
Ethernet port and you will discover two light-emitting
diodes (LEDs) at is bottom; these are status LEDs that
indicate when the connection is working.
10
speakers. Rather than to just provide you with audio, the
3.5 mm audio-visual (AV) has a hidden extra feature; it
carries a video signal that you can connect to projectors,
TVs, and any other display that supports a composite video
signal. You will need a tip-ring-ring-sleeve (TRRS) adapter,
a cable specially designed for this function.
11
Look above this, still on the left-side edge, you will find the
micro High Definition Multimedia Interface (micro-HDMI)
ports, they are smaller versions of the same connectors on
Televisions, game consoles and set-top boxes. True to its
name, it carries both audio and video signals, hence the
term multimedia while the high definition comes from the
high quality of the signals. You can use these ports to
connect the Raspberry Pi to display devices such as
computer monitors, TVs or projectors. You have the option
to connect to at most, two devices at the same time.
Just above the HDMI ports, you will find USB Type-C
power port, this is used to connect the Pi to a power
source. You will notice that the USB Type-C power is
present in smartphones, tablets and other portable devices.
12
It is better if you use the official Raspberry Pi USB Type-C
Power Supply to power your Pi, but you can get by with a
standard smartphone charger.
Check the upper edge of the Raspberry Pi’s board and you
will find another weird-looking connector; you’d mistake it
for the camera connector if you don’t look closer. It is the
exact opposite of the camera connector, instead, it is a
display connector also known as Display Serial Interface
(DSI). It is designed to be used with the Raspberry Pi
Touch Display.
13
To the right edge of the board, there are 40 metal pins,
divided into two rows with 20 pins each. It is the GPIO
(general-purpose input/output) header; the Raspberry Pi
uses it to transmit signals to additional hardware, such as
LEDs, buttons, joysticks, temperature sensors, pulse rate
monitors and other similar hardware.
Below the header, just to the right, you will find a smaller
header with just four pins: you can use this to connect the
Power over Ethernet (PoE). The PoE is an additional power
option that allows the Raspberry Pi to be powered from a
network connection, instead of the USB Type-C port.
14
The last port on the Raspberry Pi can’t be seen from the
top of the board. Turn it over and you will see a microSD
card connector, located at the opposite side of the display
connector. This is where you'll insert the Pi’s storage: The
microSD card inserted here will house all the operating
system that runs the Raspberry Pi, all installed software
and all saved files.
15
peripherals to your Pi will be provided in Chapter 2,
Getting started with your Raspberry Pi. There are a lot
more peripherals you can connect to your Raspberry Pi.
16
Chapter 2: Discover the Items
Essential for Setting up A Raspberry
Pi 4
Discover the items essential for setting up a Raspberry Pi
and learn how to connect them. The Raspberry Pi may
seem like any other computer because it requires various
external components known as peripherals, but it was
design for as fast and easy a set-up as imaginable. So if you
are intimidated just because the bare circuit board of a
Raspberry Pi looks different from encase, closed-off
computers, don’t be.
If you follow information on this book, you should be
running a Raspberry Pi in under ten minutes. If you got
this book from a Raspberry Pi Starter Kit, it means you
already have most of what you need to run the raspberry
Pi: just get a display monitor or a TV with HDMI
17
connection, this is the same connector used in Blu-ray
players, set-top boxes and gaming consoles. If you don’t
possess a Raspberry Pi Starter Kit, you are going to need
the following in addition to the Raspberry Pi 4 Model B:
19
This is required to transfer sound and images from the
Raspberry to a display monitor or TV. The end with the
micro-HDMI connector is to be connected to the
Raspberry Pi, while the other end, the one with the full-size
HDMI connector is to be connected to the display. You can
also use a micro-HDMI to HDMI adaptor with the
standard, full-size HDMI cable.
If your monitor doesn’t have an HDMI socket, get a micro-
HDMI to DVI-D, Display Port, or VGA adapters. If you are
connecting to an older TV with composite video or have a
SCART socket, get a 3.5mm tip-ring-ring-sleeve (TRRS)
audio/video cable.
You can safely use a Raspberry Pi without a case, just don’t
place it on a metal surface, because metal conducts
electricity and can cause the Pi to short-circuit. Altogether,
you might be better off with a case: you will find the
Official Raspberry Pi Case in the Starter Kit, you can also
purchase cases produced by third parties, available at
stockists.
If you intend to use a Raspberry Pi on a wired network
instead of a wireless network (Wi-Fi), you are going to
need a network cable to connect the Pi to your network
router or switch.
20
Using the Raspberry Pi’s inbuilt wireless radio doesn’t
require a cable but you need to know the name and
password or passphrase of your wireless network.
21
1. Pick up the case’s base and hold it in a way that the
elevated end is to your left while the lower end is to the
right.
22
3. Take the white lid, you will see two clips on the left
side, place them into the matching holes on the left
side of the base, just above the microSD card slot.
Adjust until they are in place, then push down the
right side (above the USB ports) until you a click is
heard.
23
The card should slide into the connector, then stop
without any click.
24
plug your mouse, but if you are not using this keyboard,
you can connect the mouse to another one of the Pi’s USB
port.
Connecting a Display
The smaller end of the micro-HDMI cable should be
connected to your Raspberry Pi, specifically to the micro-
HDMI port closest to the USB Type-C port, then the other
end should be connected to your display device.
25
In case your display has more than one HDMI port, you
will find the port number next to the port, then switch the
input of your display to the one you connected the Pi to.
But is case there is no number by the HDMI port, just
switch between the available inputs until you find the right
one.
Note:
TV Connection
You can still use the Raspberry Pi with a display monitor or
TV that don’t have HDMI connector. Purchase a adapter
cable from any electronics stockist and use it to convert the
micro-HDMI port of your Raspberry Pi to DVI-D, DVI-D,
DisplayPort, or VGA that you can use for older computer
monitors; all you have to do is connect the adapter cable to
26
the micro-HDMI port of your Raspberry Pi, then you can
use a suitable cable to connect the adapter cable to your
display monitor.
In case you want to use a TV that only has composite
video or SCART input, then it’d be ideal for you to get a
3.5 mm tip-ring-ring-sleeve (TRRS).
27
Connect the other end of the Ethernet cable to a port on
your network hub, do this, the same way you connected
the cable to your Pi.
Connecting a Power Supply
The last step in setting up your Raspberry Pi should be
connecting it to a power supply, only do this when you are
ready for the software installation: because the Raspberry
Pi doesn’t have a power switch, it will turn on immediately
you plug in a live power supply. Start by connecting the
USB Type-C end of the power supply cable to the USB
Type-C power connector of your Pi. This should be easy,
since the cable can go in either way. In case you are using a
detachable cable, ensure you plug the other end into the
body of your power supply.
28
The last step is to plug the power supply into a main
socket, the switch on the socket; the Pi should start-up
immediately. Congratulations on the successful set up of
your Raspberry Pi.
29
Setting up The Software
Note
30
You are looking at the NOOBS menu, a system that allows
you to choose the OS you want on your Raspberry Pi. The
standard version of NOOBS includes two OS options: the
Raspbian, a version of the Debian Linux designed specially
for the Pi; and LibreELEC, a version of the Kodi
Entertainment Centre software.
If you don’t want one of these two OS, you can connect
your Pi to a wired network or a Wi-Fi (from the ‘w’ option
on the top bar of icons), then you can download and install
another OS.
To install an operating system, use the mouse to mark the
box in front of the OS; (We will be installing the Raspbian
in this tutorial, but the instruction applies to any OS) move
the cursor to the white box, then click the left button of the
mouse once.
31
This will cause the ‘Install (i)’ menu icon which was
formerly greyed out will be displayed properly indicating
the operating system is ready for installation.
32
It will take about 10 to 30 minutes to complete the
installation process, depending on how fast the microSD
card is. During the installation of the operating system, a
progress bar will be displayed at the lower part of the
window, a slideshow will also commence showing some
key features of the operating system. More information on
the operating system will be provided in Chapter 3, Using
your Raspberry Pi.
A window with an ‘OK’ button will pop up after the
installation is completed; click the ‘OK’ button and the Pi
will restart into the operating system you just installed. A
lot of texts will start scrolling on your screen, these are
called the boot messages, because this is the first time you
33
are booting into the Raspbian, it will require a minute or
two for it to adjust to the space available on your microSD
card, to optimize it. It will boot quicker, next time you
start-up your Pi.
34
Chapter 3: Using your Raspberry Pi
4
35
The Welcome Wizard
The Welcome Wizard will come up on your first run of the
Raspbian. The Welcome Wizard will walk you through
configuring the Raspbian to your needs and location, this
just involves changing some settings
The next screen will provide you with a list of available Wi-
Fi networks, scroll through the list to find your network.
You can use the keyboard or mouse to scroll, then click
Next when you have scrolled to your network’s name.
37
You will be required to provide a password, also called pre-
shared key, if your network is secure (which it should be),
you may find it written on the bottom of the router or on a
card with the router. Click Next to connect to the network
or Skip if you don’t want to.
On the next screen, you will have the option to check for
and install updates for Raspbian. Regular updates of the
Raspbian are provided to fix bugs, add new features and
improve performance. Click Next to install updates or Skip
if you don’t want to install updates. Downloading the
updates will take some time, after installing the updates, a
38
window will pop up saying ‘System is up to date’, click the
OK button.
39
Navigating the Desktop
In reference to its main graphical interface, ‘Raspbian with
the Raspberry Pi Desktop’ is the official name of the
version of the Raspbian installed on most Raspberry Pi
boards. Most of the desktop is cover with a picture, the
image is called wallpaper A, the programs you are running
will appear on the top of it. You will find taskbar (B) at the
top of your desktop, this is where you get to load any of the
programs; the loaded programs will then be indicated by
task (C) in the taskbar.
The speaker icon (H) is right next to it; use the left mouse
button to click on it, if you want to adjust the audio
volume, or use the right mouse button, if you want to
choose the output your Pi uses.
After that is the network icon (G); a series of bars will
indicate the signal strength if you are using a wireless
network, while two arrows will be displayed if you are
using a wired network.
41
Click the network signal to view a list of wireless networks
available nearby.
The Bluetooth icon (F) is right beside it, press it to view
and connect to nearby Bluetooth devices.
On the left side of the menu bar, you will find the launcher
icon (J), here, you will find all the programs installed along
with the Raspbian.
You will see some as shortcuts, while the others will be
hidden in the menu, click on the Raspberry icon (K) on the
far left to bring up the hidden programs.
42
In the menu, programs are separated into categories, and
the name of each category is self-explanatory: for instance
the programing category houses software that will help you
write your own programs, more details on programing is
available in Chapter 4, Programming with Scratch; while
the games category contains games, you can play to while
away time.
There are a lot more programs available apart from the
ones covered in this book, so experiment, explore and
increase your knowledge.
43
Chromium is similar to the google chrome browser
available on other computers, so you will easily get used to
it. Chromium allows you to visit websites, play videos and
games, it also allows you to communicate with people all
over the globe through forums and chat sites. Maximize
the window so that Chromium takes up more of your
screen: you will see three icons on the top-right of your
Chromium window titlebar (N).
In the middle is the up-arrow icon (P), this is the maximize
button, click on it and the window will fill your screen.
The minimize icon (O) is just to the left of the maximize
icon, click on it and the window will be hidden, you can
click on it in the taskbar at the top of your screen to bring
it back up.
Look to the right of maximize and you will find close icon
(Q), click on this to close the window.
44
The big white bar at the top of the chromium window, with
a magnifying glass on its left side is the address bar. Type
raspberrypi.org, then press ENTER on your keyboard to
visit the Raspberry Pi website. Also try typing a search into
the address bar for example ‘Raspbian’, ‘Raspberry Pi’ or
‘Educational computing’.
46
● Once you launch the File Manager by clicking on it,
you will be enabled to browse through files and
folders otherwise called directories located on your
Raspberry Pi’s microSD card including those that
are available on your removable storage devices
such as the USB flash drives which are connected to
your Raspberry Pi’s USB ports.
● At the initial opening of the File Manager, you will
be taken to your home directory automatically
where you will find a series of other folders called
subdirectories that are arranged in categories just
like in the menu.
47
● Any files that are saved into this folder will
automatically show up on the Raspbian desktop
which makes it easy for you to access such files and
load them.
● Documents: The Document folder is where most of
the files created by you are saved.
● Downloads: All files that are downloaded from the
internet using the Chromium web browser are
automatically saved in the Downloads folder.
● MagPi: The MagPi is an official magazine of the
Raspberry Pi Foundation and this is the folder
where its electronic copy is stored.
● Music: The Music folder is where all music created
by you on the Raspberry Pi is being stored.
● Pictures: This is the folder where your image files
are stored.
● Videos: The video folder is where all videos are
stored. It is also the first place all programs
responsible for playing your videos will look out for
first.
● Public: All files that are saved in this folder will
appear visible to other users of the Raspberry Pi
48
even if there have their personalized username and
password.
49
Fortunately, all files that are available on a removable
device can be copied to the Raspberry Pi’s micoSD and vice
versa even with both your home directory and the
removable device simultaneously opened in separate File
Manager windows. This process can be referred to as
“Dragging and Dropping” and to do this, you are required
to take the following steps:
i. Move the pointer of your mouse to the file you
like to copy.
ii. Click and hold down the left mouse button.
iii. Slide your mouse pointer to the other window
and release it.
iv. An alternate method of doing this is by taking
the following steps:
v. Click on the file once.
vi. Select the Edit menu.
vii. Click on “Copy”
viii. Click on the other window.
ix. Select the Edit menu again.
x. Click on “Paste”
52
Apart from writing documents with a word processor, you
can also get them formatted your preferred ways such as:
● Changing the font style, size, color
● Adding effects
● Insertion of pictures, tables, charts as well as other
content
● Other functions of the word processor include
identifying mistakes by:
● Highlighting spelling problems in red as you type.
● Highlighting grammar problems in green while
typing.
Practice
● Start by writing a paragraph on what you have
learned so far regarding the Raspberry Pi including
its software.
● Go to the top of the window and play around with
different icons to see their outcomes such as making
53
your fonts bigger and altering the colors. If you need
more enlightenment on getting this done, hover
your mouse over each icon one after the other to
access the “tool tip” which explains the functions of
each icon.
● Once you are satisfied, go to the File menu and
select the “Save” option to get your works saved.
Assign a name and click on the “Save” button.
54
same Office menu category as the LibreOffice writer. These
other parts include:
● LibreOfficeBase: This is a database tool used in
storing information as well as looking them up
quickly and getting them analyzed.
● LibreOfficeCalc: This is a spreadsheet tool that
handles numbers as well as creates charts and
graphs.
● LibreOfficeDraw: This is an illustration program
tool used for creating pictures and diagrams.
● LibreOfficeImpress: This is a presentation
program used in the creation of slides and the
running of slideshows.
● LibreOfficeMath: This is a formula editor tool used
in the creation of properly formatted mathematical
formulae for use in other documents.
56
● If the software has a tick placed next to it, it shows
that it has already been installed on your Raspberry
Pi but if no tick is available, click on the check-box
which is next to it and get it marked for installation.
● You can get multiple software installed all at once
by marking all the preferred software though it is
important to have the recommended microSD
available to have enough room for installing the
software.
● You can also get software uninstalled similarly by
finding a piece of software with already have a tick
in its checkbox and click on it to remove the tick.
● Once you are satisfied with your selection, select the
OK button to start installing or uninstalling.
● Once you are done downloading and installing your
preferred software, you will be prompted with a
dialogue. Click on the OK button to close the
Recommended Software tool.
57
The Add/Remove Software tool is an additional tool
used for installing and uninstalling software. This tool can
be accessed from the same Preference category of the
Raspbian menu.
58
Once the raspberry pi configuration is loaded, it splits into
four tabs with each of these tabs controlling a particular
aspect of Raspbian. The first tab you will see when the tool
is initially loaded is referred to as “System” which enables
you to change your account password, set a hostname as
well as changing a range of other settings.
MORE DETAILS
● With this brief overview, you will get more
familiarized with the tool while more detailed
information about each setting is made available in
Appendix E.
59
● Select the interfaces tab to display the next category
where you will find a range of settings that all start
disabled. It is to be noted that the settings should
only be changed if you are getting new hardware
added or being instructed by the manufacturer of
the hardware.
Shutting down
● Just like in the case of any computer, the Raspberry
Pi helps in storing the files you are working on into
volatile memory. The volatile memory can be
defined as a memory which is emptied whenever
you switch off your system.
60
● In the process of working with documents, you are
advised to save each of these documents to help in
transferring the files from volatile memory to non-
volatile memory such as the microSD card to save
you from losing your important information.
● It is to be noted that the documents you are
working on are not only the currently opened files
because the Raspbian itself keeps several other files
opened while it is working. As a result, abruptly
pulling the power cable from the Raspberry Pi while
these files are still open can get the operating
system corrupted with a need to get them
reinstalled.
● It is therefore important to get all files saved by
Raspbian and make it ready for getting powered off
which a process is referred to as getting the
operating system shut down.
63
Chapter 4: Programming with
Scratch
Making use of the Raspberry Pi is not just about making
use of the software that has been created by other people
but getting your software created as well based on your
creativity. The Raspberry Pi provides you with a platform
where you can get to create your programs and experiment
on them as well.
The Scratch is a visual programming language that was
developed by the Massachusetts Institute of Technology
(MIT) giving the key to the accessibility of coding on the
Raspberry Pi.
With the scratch, you will get to develop your program
step-by-step with the use of blocks which are made up of
pre-written chunks of code which are hidden behind color-
coded jigsaw pieces.
The Scratch can be regarded as a programming
environment that is powerful and fully functional for the
creation of simple games and animations as well as in the
development of complex interactive robotics projects.
64
Introducing the Scratch 2 interface
65
● Sprites List: This is the section of the window
where all sprites that have been created or loaded by
you into Scratch are displayed.
● Blocks Palette: The Block palette displays all
blocks that are available for your program which
also features color-coded categories.
● Blocks: The Blocks are the pre-written chunks of
program code where you can build your programs
step-by-step.
● Script Area: This is the area where your programs
are built by dragging-and-dropping blocks from the
blocks palette.
66
It is to be noted that unlike most programming languages
where you will need to be told what to do by the computer
through written instructions, the Scratch works differently.
67
v. Get it dragged over the script area at the right-
hand side of the Scratch window before releasing
the mouse button.
vi. You will notice that the shape of the block that
has just being dropped has a hole at the top
including a matching part that sticks out at the
bottom. This indicates that your block is
expecting to have something above as well as
below it. What you have above it is referred to as
a trigger for this program.
vii. Go to the blocks palette and click on the Events
category which has a light brown color and drag
it onto the scripts area.
68
x. It is to be noted that this doesn’t have to be
precise, as long as its close enough, the block
will automatically snap into place just like a
jigsaw piece. If this doesn’t happen, click and
hold on to it again to get the position adjusted
until it snaps into place.
xi. The program is now complete and can be put
into work by running the program.
69
● Remember to get your program named and saved
before moving on. To do this;
i. Click on the File menu.
ii. Select the Save Project.
iii. Type in a preferred name.
iv. Select the Save button.
70
Next Steps: Sequencing
● Although your program is made up of two blocks,
there is only one real instruction available which is
saying “Hello!” each time you click on the flag and
the program runs but by sequencing, you will be
able to do even more.
● Generally, computer programs are a list of
instructions with each instruction following from
the last in form of a logical progression called the
linear sequence.
● Get started by clicking and dragging the say Hello!
Block from the scripts area back to the blocks
palette which will help in deleting the block and
getting it removed from your program while leaving
just the trigger block when clicked.
71
● Go to the blocks palette and click on the Motion
category after which you can now click and drag
“move 10 steps block” so it gets locked into space
below the trigger block on the script area. According
to the name, this instructs the cat sprite to move
some steps towards a direction it is currently facing.
73
● This can be fixed in a different way past making use
of the play sound meow until done block, this can
be done by taking the following steps:
i. Click on the Control category of the blocks
palette which is color-coded with gold.
ii. Click and drag a wait one secs block in between
the play sound meow block and bottom move-10
steps block.
iii. Select the green flag to run the program one last
time.
iv. Once you do this, you will notice that the cat
sprite will wait for a second after moving to the
right before it moves back to the left again. This
process is called DELAY and it is important for
getting how long it takes for your sequence of
instructions takes to run controlled.
74
● Nevertheless, there shouldn’t be a stop because
there is a type of Control block included in a scratch
that is referred to as the LOOP.
● Go to the blocks palette and select the Control
category which is color-coded with gold and search
for the forever block.
● Click and then drag the forever block to the scripts
area and get it to drop underneath the when clicked
block afterward and just above the first move 10
steps block.
75
● This process is called an infinite loop in
programming, which is a loop that never ends but
keeps recurring. To stop the infinite loop, click on
the red octagon which is next to the green flag
above the stage area.
● To alter the loop type, click and drag the first move
10 steps block and get it pulled out including the
blocks that are beneath it from the forever block
and drop them underneath the when click block
afterward. Then click and drag the forever block to
the blocks palette to get it deleted after which you
can click and drag the repeat 10 block below the
when clicked block for it to go round the other
blocks.
● To run the new program, click on the green flag. It
will look as if the program is performing the same
action as the original version by getting the
sequence of instructions repeated over and over
again. Nevertheless, in this case, instead of
continuing forever, the loop will be put to an end
after ten repetitions. This is referred to as the
definite loop in which case you will be the one to
decide when it finishes. Making use of the loops,
76
infinite and definite loops, comes in very handy for
most programs such as the sensing programs and
games.
ix. Click and then drag the set loops to 0 block onto
the script area. This instructs the program to get
the variable to initialize with a value of 0.
78
x. Click on the Looks category of the blocks palette
and drag the say Hello! for 2 secs block below
your set loops to the 0 block afterward.
xi. Note that the say Hello! blocks cause the cat
sprite to say anything written in them. Instead of
having to write the message in the block
yourself, variables can be used instead. To do
this:
xii. Click on the Data category in the blocks palette
again.
xiii. Click and drag the rounded loops block referred
to as a reporter block which you will find at the
top of the list having a tick box placed next to it.
Get it dragged over the “Hello!” word in the say
Hello! for 2 secs block. This will result in the
creation of a new combined block, say loops for
2 secs.
xiv. Go to the blocks palette and click on the Events
category.
xv. Click and drag with when block to get it placed
on the top of your sequence of blocks.
79
xvi. Click on the green flag which is above the stage
area and the cat sprite will say “0” which is the
value given to the variable loops.
80
secs blocks and get both of other blocks surrounded
in your sequence.
● Select the Operators category in the blocks palette
which is color-coded green, then get the diamond-
shaped block clicked and dragged after which you
get it dropped into the matching diamond-shaped
hole in the repeat until block.
You will notice that the programs will work similarly just
like before with the cat sprite counting from 0 up to 9 after
which the program stops. This happens because the repeat
until block works in the same way to the repeat 10 block.
Nevertheless, rather than counting the number of loops
81
itself, it will be comparing the value of the loops variable to
the typed-in value at the right of the block. Once the loops
variables get to 10, it will stop. This is referred to as a
comparative operator which helps in comparing two
values.
83
The if-then block can be regarded as a conditional block
meaning the blocks that are located inside it will only run
if some conditions are met.
i. Go to the blocks palette and click on the Data
category.
ii. Drag and drop the loops reporter block into the
first empty square in your symbol block.
iii. Click on the second empty square.
iv. Type in the number “5”
v. Lastly, click on the word “Hello!” in your say
Hello! for 2 secs.
vi. Type “That’s high!”
vii. Click on the green flag for the program to run.
84
Chapter 5: Project 1--Astronaut
Reaction Timer
● The Astronaut Reaction Timer is designed in honor
of the British ESA astronaut, Tim Peake and his time
while aboard at the International space station.
● It is advisable to have your existing program saved if
you like to keep them and click on “File” and “New”
afterward to start with a new project.
● Assign a name before starting by clicking on the File
and Save project. You can call it “Astronaut Reaction
Timer.”
● Note that this project will be based on two images,
first to indicate stage background while the other as
a sprite both of which aren’t included in the built-in
resources of Scratch.
● To get them downloaded, you are required to take
the following steps:
i. Load the Raspbian menu by clicking on the
raspberry icon.
ii. Move the mouse pointer to the Internet.
iii. Click on “Chromium Web Browser”
1
iv. After the browser loads, type in rpf.io/astronaut-
backdrop in the address bar.
v. Hit the ENTER key.
vi. Right-click on the picture of space.
vii. Click on “Save image as…..”
viii. Select the “Download folder”
ix. Select the Save button.
x. Click the address bar again and type in
rpf.io/astronaut-sprite.
xi. Hit the ENTER key.
Once both images have been saved, you can now choose to
close Chromium or leave it opened and make use of it in
the taskbar to get switched back to Scratch 2.
2
Now get started by taking the following steps:
● Right-click on the cat sprite located on the stage.
● Remove it by selecting Delete.
● Go to the bottom-left of the Scratch 2 window to
find the stage controls.
● Select the upload backdrop icon.
● Go to the Downloads folder to find the file Space-
background.png.
● Click on it to get it selected and click OK.
● Note that the plain white background will change to
the space picture with the scripts area replaced with
the backdrops area. You can now draw over the
backdrop here but only click on the tab marked
Scripts located at the top of the Scratch 2 window
for now.
3
● Click on the upload sprite icon which is next to the
word “New sprite” located at the top of the sprites
pane to get a new sprite uploaded.
● Search for the file Astronaut-Tim.png in the
Downloads folder, click on it to get it selected and
click on OK. Once this is done, the sprite will
automatically appear on the stage though might not
be in the middle. Click and drag it using your mouse
and drop it such that it is placed near the lower
middle.
● Once you have your new background as well as a
sprite in place, you can now start to create your
program. To get started:
● Get a new variable created called “time” ensuring
that the “For all sprites” is selected before clicking
on OK.
4
● Click on your sprite to get it selected either on the
stage or in the sprite pane.
5
distance reporting block into the new blank space
that is created.
● Note that the round block gets numbers rounded up
or down to their nearest whole number to eliminate
the problem of having a hyper-accurate or difficult
to read the number of kilometers.
● To run your program, click on the green flag and
observe how far the ISS will travel in the time it
takes to press the SPACE key. Always get your
program saved when you are done to get it easily
loaded again whenever you need it without having
to start all over again.
6
Chapter 6: Project 2--Synchronized
Swimming
The project has been designed to show that games can
make use of more than a single button by offering two-
button control making use of the ← and → keys with the
keyboard.
i. Get a new project created and get it saved as
“Synchronised Swimming”
ii. Go to the stage control section and click on
Stage.
iii. Select the Backdrops tab.
iv. Select the water-like blue color from the palette.
v. Click on the white backdrop.
7
vii. To access a list of built-in sprites, select the
“choose sprite from library” icon.
viii. Click the Animals category and then the “Cat1
Flying” and select OK. Note that the sprite also
comes in handy for swimming projects.
ix. Click the new sprite and drag two when space
key pressed Events blocks into the scripts area.
x. Select the small down arrow which is next to the
word “space” onto the first block and select the
“left arrow” from the list of possible options
afterward.
xi. Get a turn 15 degrees Motion block dragged
under your when left arrow pressed block.
xii. Repeat the previous step with your second Event
block with an exception to choosing the “right
arrow” from the list and making use of a turn 15
degrees Motion block.
8
xiii. To test your program, press ← or →. It will be
observed that the cat sprite turns as you do
moving in the direction you must have chosen
on the keyboard. You will also notice that you
didn’t need to select the green flag because the
Events get blocks you must have used triggered
and are active at all times even with the program
not running as usual.
xiv. Execute the same steps twice but choose the “up
arrow” and “down arrow” this time for the
Events trigger blocks and move 10 steps for the
Motion blocks. Now press the arrow keys and
you will find out that the cat can turn around
and swim forward and backward as well.
9
iv. Click on the round X icon that is displayed at the
top right corner to get it deleted.
v. Click on the “cat1 flying-b” costume and make
use of the name box located at the top to get it
renamed to “right”
vi. Get the costume renamed as “right” on this copy
to get it selected.
11
Now you will notice that the cat will move to the middle of
the stage while pointing to the right as well.
● To get more swimmers created, get a repeat 6 block
added by changing from the default value of 10 and
getting a created clone of myself Control block
inside it added.
● To make it such that the swimmers are swimming in
different directions, get a turn 60 degrees block
added above the create clone block while it remains
inside the repeat 6 block. Select the green flag and
give the arrow keys a try again and you will get to
see how the swimmers come to life.
● You can get some music added to get the Olympic
feeling completed. To do this, you are required to
take the following steps:
i. Click on the Sounds tabs located above the
blocks palette.
ii. Select “choose new sound from library” icon.
iii. Select the Music Loops category.
iv. Select the small play icons until you find your
preferred music.
v. Select the OK button to select the music.
12
vi. Click on the Scripts tab to get the scripts area
opened again.
vii. Get another when clicked Events block added to
your script area again.
13
Lastly, you can get to stimulate a full dancing routine by
getting a new event trigger added to your program. You
can do this by taking the following steps:
i. Add a when space key pressed Events block.
ii. Add a switch costume to the right block.
iii. Below this, get a repeat 36 block added while
also remembering to get the value changed from
the default. Also inside this is a turn 10 degrees
block and a move 10 steps block.
iv. Start the program by clicking on the green flag
and hit the SPACE key to try the new routine.
v. Get the program saved when done.
14
Chapter 7: Project 3--Archery Game
The Archery game involves players trying to hit a target
with a randomly swaying bow and arrow.
To get started with this project:
i. Open the Chrome Web browser
ii. Type in rpf.io/archery-resources after which you
can hit the ENTER key. It will take a few seconds
for the resources for this game to download
completely. Iii.
iii. Switch back to Scratch 2
iv. Select the File menu
v. Click on the Load Project.
vi. Go to the Places pane located at the left-hand
side of the window and click on “Pi”
vii. Click on the “Downloads folder”
viii. Click on the ArcheryResources.sb2 followed by
the “Open button”
ix. You will be prompted with a question if you
want to get the contents of your current project
replaced. In a case where your changes are not
saved yet, click Cancel and get them saved,
otherwise select OK.
1
Note that your new project is made up of a backdrop and a
sprite without any of the actual code for making a game. It
is mainly your job to get the codes added. To do this, you
are required to take the following steps:
i. Add a when clicked block.
ii. Add a broadcast message 1 block.
iii. Go to the end of the block and click on the down
arrow and then “New Message.”
iv. Type in “new arrow” before selecting the OK
button which results in your block now reading
broadcast new arrow.
● The broadcast can be defined as a message from one
part of a program that can be received by any part of
your program. To execute a broadcast, add a when I
received message1 block and get it changed to read
when I received new arrow.
2
● In this situation, you can click on the down arrow
and select “new arrow” from the list available with
no need to create a message again.
● Add a go to x: -150 y: -150 block below the when I
receive a new arrow block and then get the size set
to 400%. Note that these are not the blocks’ default
values so you will need to get them changed once
they have been dragged into the script area.
● Select the green flag to see how the programs you
have written so far works. You will notice that the
arrow sprite which the player uses for aiming target
will jump to the bottom-left of the stage and will be
quadrupled in size.
● To assign a challenge to the player, get movement
simulating swaying as the bow is drawn added
including the archer taking aims. To do this, you are
required to take the following steps:
i. Drag a forever block and then followed by a glide
1 secs to x: -150 y: -150 block.
ii. Get the first box edited to say “0.5” rather than
“1.”
iii. Place a pick random -150 to 150 Operators block
into each of the other two white boxes which
3
means that the arrow will get drifted around the
stage in a random direction which makes it far
difficult to hit the target.
iv. Select the green flag again.
v. Once you have clicked the green flag, you will
notice that your arrow sprite will start to drift
around the stage thereby covering different parts
of the target.
4
Chapter 8: PROGRAMMING WITH
PYTHON
5
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.
6
that allows you to save, create, load, and run your
programs in various ways.
7
Your First Python Program: Hello, World!
8
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:
Hello World!
9
Syntax error
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.
10
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!
11
wonder what happens when you remove the brackets or
quotation marks from the codes and consequently run it.
What you see on the first line as an output in the shell area
resembles the earlier feedback from the Hello world
program. 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
12
after the symbol is invalid and will not be parsed by the
interpreter.
13
Chapter 9: Project 1: 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.
pat = turtle.Turtle()
pat.forward(100)
15
Pat drawing a line!
for i in range(2):
pat.forward(100)
pat.right(60)
pat.forward(100)
16
pat.right(120)
for i in range(10):
pat.right(36)
Click the Run icon, and watch the turtle: it’ll draw a
parallelogram, as before, but when it’s done it’ll turn 36
17
degrees and draw another, then another, and so on until
there are ten overlapping parallelograms on the screen –
looking a little like a snowflake
18
You can also have the colours 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
U.S. SPELLINGS
19
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))
Now that you can create a ninja star, you should write
codes that will bring to life a benign snowflake, that looks
closely like real life. To make this happen, add a new line 6
20
directly below your colours list with the following
instruction:
21
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():
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)
22
pat.right(90)
pat.forward(90)
Make sure that the new loop you create remains above the
commented-out colour line. You should as well run and
call your new function:
for i in range(8):
branch()
pat.left(45)
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):
23
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) 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.
24
Finally! A snowflake to remember.
25
Chapter 10: Physical Computing
with Raspberry Pi
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 buttonss. 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.
26
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
27
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
28
controlled from the GPIO header. There are lots of components
but GPIO projects are mostly done with the use of these
common parts.
29
connect component individually when you are not using a
solderless; M2M (male-to-male).
This is a tool for connecting across the solderless. u will need
these three types of Jumper wire depending on your project.
M2M and M2F can be avoided when you are using a Solderless.
30
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.
31
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.
32
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
is 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:
● 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
33
● Male-to-female (M2F) and female-to-female (F2F)
jumper wires
● Optionally, a breadboard and male-to-male (M2M)
jumper wires
34
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. 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.
35
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, 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Ω.
36
Chapter 11: Your first Physical
Computing Program: Hello, LED!
37
limiting resistor only if the LED comes with a built-in resistor of
the required value.
Begin your work by confirming if your LED is functioning.
Position the Raspberry Pi in a way that will separate the GPIO
header into 2 vertical stripes off to the right. Make a connection
of Raspberry Pi with first 3.3 V pin.
With the use of a F2F jumper wire. Join the other end to the log
leg to either the anode or positive of your LED using yet another
F2F jumper wire. 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.
Connect your LEDs to these pins and do not forget the resistor.
In as much as you have your Raspberry Pi on, the LED light will
be up. And if in case it does not, cross check your circuits to
38
confirm whether you are doing it exactly as you are being
taught. 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. 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.
39
Now it is time to create a Python to control the power
switch of the LED.
CODGEDING KNOWLE
You have to be able to use the Thonny Python IDE comfortably
to be able to continue this project. Chapter 4 contains some
projects that will give you the comfortability to do so, please
check and go through the project before you continue.
40
Chapter 12: LED Control in Python
The 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. 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().
41
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: The LED will start
flashing.
42
Chapter 13: 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. 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
43
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.
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.
44
Chapter 14: 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 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.
45
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. 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:
46
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.
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)
47
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.
48
Chapter 15: 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.
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.)
49
Controlling a buzzer in Python
50
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)
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.
51
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?
52
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)
54
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.
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.
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:
55
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.
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")
56
_exit(0)
right_button.when_pressed = pressed
left_button.when_pressed = pressed
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!
Hurray! You have successfully created your own physical game
CHALLENGE: IMPROVE THE GAME
57
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?
58
To build one, you will need information about the RetroPie
ROMs, downloads, and others.
● Raspberry Pi 4 board
● The Raspberry Pi
59
The Pi 3B+ will do the job but the Pi 4 offers better
performance, so we advise you to choose this option.
The Raspberry Pi with the enhanced 4GB ram will cost a lot
more. You can purchase a starter kit which contains
everything you need, except the mouse and keyboard.
After getting all the listed hardware, you have to find the
right emulators. It is best to install an emulation suite but
if you want to you can install the emulators individually.
The emulation suite contains many top emulators and can
be written on a SD card. You will find other unlisted
emulators preinstalled on the suite.
1. RetroPie
2. RecalBox
3. PiPlay
4. Lakka
62
PES also provides wireless network and network gaming to
retro platforms (except the N64) and it can be dual-booted
with BerryBoot.
6. Batocera
63
choose RecalBox or RetroPie. There’s very little difference
between them.
64
How to Add ROMs to RetroPie and Other Suites
65
If you want the retro feel, go for the old school joysticks
and console controllers with USB connectors. They are
available. I prefer to use a standard Raspberry Pi 3 case and
it’s not usually in the open. You may decide to use a retro
console-themed case and display it proudly. There are lots
of them available in various designs the mini SNES console
design for example.
You can also try 3D printing, Lots of retro style cases can be
found online as digital files, you just have to buy and
produce them. If you don’t have a 3D printer, there are
people who provide this service. You have to upload the
design and they want their payment upfront, they will ship
it to you. If you intend to build your own case, you can use
the slick design of a game for inspiration.
66
A Note from the author
Thanks for reading this book; I hope you have been well
informed.
67