Programming The Raspberry Pi 4
Programming The Raspberry Pi 4
Programming The Raspberry Pi 4
Pi 4
Scott O. Robins
Copyright © 2019 Scott O. Robins
2
Chapter 1: Setting up Your New
Raspberry Pi 4
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.
Power Supply
4
● It is also advisable to make use of your official
universal power supply.
MicroSD card
TV Or Computer Screen
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
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
8
VGA
OPTIONAL EXTRAS
Case
Headphones or Speakers
Ethernet Cable
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 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.
12
i. Download SD Formatter for your Windows or Mac by
visiting the SD Association’s website.
13
v. Format the card
14
Have the Files Copied
15
5. After copying all the files to the SD card, you can now
have your SD card ejected.
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.
17
● The keyboard can also be connected in the same
way.
For Raspberry Pi 4
18
● The second screen should be connected similarly.
Raspberry Pi 1, 2, 3
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.
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.
21
iii. Once the installer has been loaded, you will be
prompted to select the OS you like to install.
v. Select install.
22
● Enter a new password for your Raspberry Pi and
select “Next.”
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.
24
Chapter 5: Raspberry Pi Desktop
Recall that the Raspberry Pi runs Raspbian which is a
version of an operating called the Linux
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
27
Keyboard
28
Chapter 6: Connecting To the Internet
29
● Once your Pi has been connected to the internet,
you will be prompted with a wireless LAN symbol
instead of the red crosses.
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.
Installing 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.
33
● Select and browse a category from the menu located
on the left to search for software.
34
ii. Select Enter.
iii. A list will appear from which you will select “Simple
drawing/paint program”
vi. Once you type in the right password, pinta will get
downloaded and installed.
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:
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.
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”
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.
39
● Input in your password as soon as you are
prompted.
40
iii. Enter the command “sudo apt-get dist-upgrade” to get
all your installed packages upgraded to their latest
versions.
41
Running Out Of Space
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.
iv. For any prompt that comes up, reply with “yes.”
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.
44
Generally, apt is lacking in terms of robustness features
that are atomicity and fall-back.
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.
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.
47
Music: Music that is created and kept on the Raspberry Pi
is saved here/
ii. The right pane will display the files and subdirectories of
the directory which are selected in the left pane.
48
manager. Once this pop up comes up, select OK for you to
view the files and directories.
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
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.
51
button located at the screen’s top right, select it from the
list and click on it before getting it unplugged.
Ejecting Devices
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.
53
● The command ‘Is’ can be used in listing the files that
are available in the Desktop directory.
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.
Interfaces
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.
Performance
Localization
With this tab, you can easily change the settings of your
Raspberry Pi into a specific country or location.
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.
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.
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.
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.
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.
63
in various ways. Script area—your python programs are
implemented at the script area which is usually split into
two–major and supplementary.
64
Python IDE. Wait for a few seconds as the program—
usually the simple mode loads, welcoming your eyes to its
user interface.
print("Hello, World!")
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.
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.
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!
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.
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.
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.
pat = turtle.Turtle()
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.
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)
for i in range(10):
74
…and the following at the bottom of your program:
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
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.
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
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.
pat.color(random.choice(colours))
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:
78
be recalled when you need it. And the function remains in
your portfolio.
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)
pat.forward(90)
Make sure that the new loop you create remains above the
commented-out color line.
for i in range(8):
80
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):
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.
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.
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
84
from pygame.locals import * from time
import sleep
pygame.init()
width = pygame.display.Info().current_w
height = pygame.display.Info().current_h
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.
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))
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
sleep(3)
zombie =
pygame.image.load('scary_face.png')
88
Add a delay, so that the zombie image doesn’t appear right
away:
sleep(3)
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.
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))
scream = pygame.mixer.Sound('scream.wav')
scream.play()
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!
sleep(0.4)
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
93
2. The Chromium Web Browser will automatically
download the code of the program to your Download
folder.
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.
94
west’ and ‘go east’, but as there aren’t any rooms in those
directions the game will show you an error message.
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.
'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:
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.
96
You have added another room
'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'
Click Run, and try going into the Kitchen room– the
monster won’t be too impressed when you do!
A
monster has got you!
'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' : {
'item' : 'potion'
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:
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!
101
CHALLENGE: EXPAND THE GAME
102
Looking for errors in your code can become daunting, but a
process called debugging can lift the burden off your
shoulders.
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.
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.
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:
107
=> indicates that a number is equal to or greater
than another number.
USING = AND ==
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.
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.
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
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.
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.
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.
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.
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
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
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!
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.
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()
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:
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.
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.
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.
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.
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
led = LED(25)
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?
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
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
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.
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:
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")
right_button.when_pressed = pressed
left_button.when_pressed = pressed
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:
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:
143
Your final program should look like this:
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.
145
Hurray! You have successfully created your own
physical game
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.
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.
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
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.
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.
155
from sense_hat import SenseHat sense = SenseHat()
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.
156
sense.show_message("Hello, World!", text_colour=(255,
255, 0), back_colour=(0, 0, 255), scroll_speed=(0.05))
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.
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.
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.
We have the first LED at the top-left corner with the last at
the bottom right.
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:
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)
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():
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:
165
sense.set_pixel(3, 6, (255, 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)
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.
167
the use of sense.set_pixels() function which is much easier
than trying to draw pixel by pixel.
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.
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.
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:
Environmental sensing
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:
sense = SenseHat()
sense.clear()
Type the line below to help take the reading from the
pressure sensor:
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.
temp = sense.get_temperature()
print(temp)
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.
htemp = sense.get_temperature()
ptemp = sense.get_temperature_from_pressure()
print(temp)
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.
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.
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:
orientation = sense.get_orientation()
pitch = orientation["pitch"]
roll = orientation["roll"]
yaw = orientation["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.
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.
x = round(x)
y = round(y)
z = round(z)
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.
182
If the opposite is done with the HDMI port pointing to the
ceiling, this will result in -1G on the Y-axis.
orientation = sense.get_gyroscope_raw()
183
Alter all the word acceleration available on the three lines
below it to orientation.
north = sense.get_compass()
print(north)
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
sense = SenseHat()
sense.clear()
While True:
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)
186
the joystick is being pushed down just like a push button
switch it will have middle printed.
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)
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.
189
What you will need
190
Raspberry Pi Camera Module
191
3. Insert the Camera Module ribbon cable with the panel
facing downward.
192
Boot the Raspberry Pi.
Open the main menu, then under preferences select the
Raspberry Pi Configuration tool.
erminal window:
raspistill -o Desktop/image.jpg
194
● Click Enter to run the command.
195
You can add more options to set the size and look of the
image the raspistill command takes.
raspistill -o Desktop/image-small.jpg -w 64
raspivid -o Desktop/video.h264
196
● Create and save the new file as camera.py.
camera = PiCamera()
camera.start_preview()
sleep(5)
camera.stop_preview()
197
● Save, then launch the program. The camera preview will
display for five seconds.
camera = PiCamera()
camera.rotation = 180
camera.start_preview(alpha=200)
198
Take still pictures with Python code
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.
camera.start_preview()
199
for i in range(5):
sleep(5)
camera.capture('/home/pi/Desktop/image%s.jpg' %
i)
camera.stop_preview()
200
camera.start_preview()
camera.start_recording('/home/pi/Desktop/video.h26
4')
sleep(5)
camera.stop_recording()
camera.stop_preview()
Note: Some settings will modify just the preview, some will
only modify your image and some can modify both.
camera.framerate = 15
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/max.jpg')
camera.stop_preview()
202
Use the command annotate_text to add text to your
image.
Write and launch the code to try it:
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/text.jpg')
camera.stop_preview()
camera.annotate_text_size = 50
203
● Change the code under the import line to the following:
camera.start_preview()
camera.annotate_background = Color('blue')
camera.annotate_foreground = Color('yellow')
sleep(5)
camera.stop_preview()
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.brightness = i
sleep(0.1)
camera.stop_preview()
camera.start_preview()
for i in range(100):
camera.contrast = i
sleep(0.1)
205
camera.stop_preview()
None
Negative
Solarize
Sketch
Denoise
Emboss
Oilpaint
Hatch
Gpen
Pastel
Watercolor
Film
Blur
Saturation
Colorswap
Washedout
Posterise
206
Colorpoint
Colorbalance
Cartoon
deinterlace1
deinterlace2
camera.start_preview()
camera.image_effect = 'colorswap'
sleep(5)
camera.capture('/home/pi/Desktop/colorswap.jpg')
camera.stop_preview()
camera.start_preview()
camera.image_effect = effect
camera.stop_preview()
off
auto
night
nightpreview
backlight
spotlight
sports
208
snow
beach
verylong
fixedfps
antishake
fireworks
camera.start_preview()
camera.exposure_mode = 'beach'
sleep(5)
camera.capture('/home/pi/Desktop/beach.jpg')
camera.stop_preview()
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
camera.start_preview()
camera.awb_mode = 'sunlight'
sleep(5)
210
camera.capture('/home/pi/Desktop/sunlight.jpg')
camera.stop_preview()
● 1 x Tactile button
211
Software
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:
212
The Camera
1.Insert the strip in the connector, with the blue side facing
the Ethernet port.
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.
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!):
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.
camera.rotation = 180
camera = PiCamera()
camera.rotation = 180
camera.start_preview()
sleep(3)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
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:
button = Button(17)
camera = PiCamera()
217
camera.start_preview()
button.wait_for_press()
camera.capture('/home/pi/image.jpg')
camera.stop_preview()
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.
camera.start_preview()
button.wait_for_press()
218
sleep(3)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
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.
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
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.
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.
Hardware
● Raspberry Pi 4
223
● This material covers aspects from the following strands
of the Raspberry Pi Digital Making Curriculum:
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.
raspistill -k
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.
226
The Python IDLE code editor will open, you will it use to
write the photo booth program.
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
camera.start_preview()
sleep(2)
camera.capture('/home/pi/selfie.jpg')
camera.stop_preview()
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.
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.
230
Since we are using Minecraft, we can use mc.postToChat
to send the coordinates to the Minecraft window.
mc = Minecraft.create()
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.
while True:
x, y, z = mc.player.getPos()
sleep(3)
232
I need a hint
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.
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:
sleep(1)
mc.postToChat("Smile!")
sleep(1)
camera.start_preview()
sleep(2)
camera.capture('/home/pi/selfie.jpg')
camera.stop_preview()
sleep(3)
234
Conclusion
235