100% found this document useful (4 votes)
688 views184 pages

Raspberry Pi The Complete Manual - September 2022

The document provides an overview of the Raspberry Pi, a credit-card sized computer ideal for learning programming and home hacking. It discusses the Raspberry Pi 2 Model B and Raspberry Pi 1 Model B+, noting their processors and specifications. Details are also given on the Raspberry Pi 3 Model B+, the most recent version which has Bluetooth and dual-band wireless LAN capabilities.

Uploaded by

Madar Nagy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
688 views184 pages

Raspberry Pi The Complete Manual - September 2022

The document provides an overview of the Raspberry Pi, a credit-card sized computer ideal for learning programming and home hacking. It discusses the Raspberry Pi 2 Model B and Raspberry Pi 1 Model B+, noting their processors and specifications. Details are also given on the Raspberry Pi 3 Model B+, the most recent version which has Bluetooth and dual-band wireless LAN capabilities.

Uploaded by

Madar Nagy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 184

The Complete Manual Series </>

Raspberry Pi
Coding & Projects
The essential step-by-step
manual to learning coding
skills with Raspberry Pi

OVER

760
GUIDES
& TIPS

OVER

180
PAGES!

Raspberry Raspberry Raspberry

Pi 4 400 Pico
100% Independent SEP 2022 EDITION
Want to master Raspberry Pi?
Then don’t miss our NEW Coding
magazine on now!

Visit us at: www.pclpublications.com


The Complete Manual Series

Raspberry Pi
Coding & Projects

Unlock and master the potential of your Raspberry Pi...

Thanks to the Raspberry Pi’s unique setup, operating system and


amazing community of imagineers, this little computer has become
one of the most important pieces of educational technology in the
world. It’s helped people learn how computers, coding and
electronics work, as well as helping science and engineering,
astronauts and technicians, young and old, teachers and students.

With our Raspberry Pi guide in your corner, you will learn and
discover how the Pi works, what you can do with it and where to
take your Pi adventures. We’ve got everything from setting up the
Pi to learning how to code on it using Python, and from learning
Linux to projects that’ll take you and your Pi to the next level.

Read on, and let’s unleash your imagination with the power of
the Raspberry Pi.
Contents

6 Raspberry Pi is Good For You!l


8 Say Hello to Raspberry Pi 32 Other SBCs to Use
10 Get to Know the Raspberry Pi 34 Raspbian: The Complete
12 Up Close with the Raspberry Operating System
Pi 4 Model B 36 Which Pi is Right for Me?
14 The Pi 400 – Up Close 38 Raspberry Pi in Numbers
16 Pi 400 – Return of the 80s 40 Kit You’ll Need and How to
Home Computer Set it Up
18 Ten Pi Projects and Ideas 42 Set Up Raspberry Pi Using
20 The Pi Pico – Up Close a Mac
22 Pico Power: the Tiny 44 Set Up Raspberry Pi Using a
Microcomputer Windows PC
24 The Pico and MicroPython 46 The Raspberry Pi Desktop:
What You Will Need
26 Pico Examples and How to
48 Debian Buster with
30 Pico Projects & Ideas
Raspberry Pi Desktop

50 Explore Raspbianl
52 Take a Tour of PIXEL 62 Get More from the
54 Exploring the Command Line Terminal App
56 Setting Up a Static IP 64 Using the File Manager
Address 66 Edit Images with GIMP
58 Connecting to the Pi Remotely
60 Using APT to Install and
Remove Programs

4 Raspberry Pi Coding & Projects


Contents

68 Python on the Pil


70 Starting Python for the First Time
72 Your First Code
74 Saving and Executing Your Code
76 Executing Code from the
Command Line
78 Numbers and Expressions
80 Using Comments
82 Working with Variables
84 User input
86 Creating Functions
88 Conditions and Loops
90 Python Modules
92 Python Errors
94 Python Graphics
96 Glossary of Terms

98 Python Code & Ideasl


100 Python File Manager
102 Number Guessing Game
104 Text Adventure Script
106 Python Digital Clock
108 Vertically Scrolling Text
110 Text to Binary Convertor
112 Hangman Game Script

114 Mastering Linuxl


116 What is Linux?
118 Using the Filesystem
120 Listing and Moving Files
122 Creating and Deleting Files
124 Create and Remove Directories
126 Copying, Moving and Renaming Files
128 Using the Man Pages 152 Pi Projectsl
130 Editing Text Files 154 Creating a Loading 170 Pi Projects: Desktop Pi
132 Getting to Know Users Screen 172 Pi Projects: Retro
134 Ownership and Permissions 156 Tracking the ISS Gaming
136 Useful System and Disk Commands with Python 174 Pi Projects: Media
138 Managing Programs and Processes 160 Text Animations Centre
140 Input, Output and Pipes 162 Retro Coding 176 Pi Projects: BBS Client
142 Fun Things to Do in the Terminal 164 Using Text Files for 178 Pi Projects: Weather
Animation Station
144 More Fun Things to Do in the Terminal
166 Stream Digital TV with a 180 Common Raspberry Pi
146 Linux Tips and Tricks HAT - Part 1 Problems
148 Command Line Quick Reference 168 Stream Digital TV with a
150 A-Z of Linux Commands HAT - Part 2

www.pclpublications.com 5
Raspberry Pi is Good For You!

6 Raspberry Pi Coding & Projects


Raspberry Pi is Good For You! INDEX

Raspberry Pi is
Good For You!
Your journey with this amazing little computer begins here. Say hello to the
Raspberry Pi; learn how it works, what kind of operating system it has, what
you need to get it up and running and much more. This is your first step into
the world of the Raspberry Pi.
In this section, you’ll discover what makes the Raspberry Pi such a fabulous
little computer and project board. There are in-depth guides to the hardware,
operating system, what you’ll need to begin with and enjoying the software the
Pi has to offer from your computer’s desktop. Now let’s see what this amazing
computer has to offer.
8 Say Hello to Raspberry Pi 34 Raspbian: The Complete Operating
10 Get to Know the Raspberry Pi System
12 Up Close with the Raspberry Pi 4 36 Which Pi is Right for Me?
Model B 38 Raspberry Pi in Numbers
14 The Pi 400 – Up Close 40 Kit You’ll Need and How to
16 Pi 400 – Return of the 80s Home Set it Up
Computer 42 Set Up Raspberry Pi Using
18 Ten Pi Projects and Ideas a Mac
20 The Pi Pico – Up Close 44 Set Up Raspberry Pi Using a Windows
22 Pico Power: the Tiny Microcomputer PC
24 The Pico and MicroPython 46 The Raspberry Pi Desktop: What You
Will Need
26 Pico Examples and How to
48 Debian Buster with
30 Pico Projects & Ideas Raspberry Pi Desktop
32 Other SBCs to Use

Say Hello to
8 Raspberry Pi
42 Set Up
Raspberry Pi
Using a Mac
Let’s take a look at
the best-selling British The easiest way to get up
computer ever. and running on a Mac.

www.pclpublications.com 7
Raspberry Pi is Good For You!

Say Hello to
Raspberry Pi
Let’s take a look at the best-selling British computer ever: the Raspberry Pi!
This bare-bones machine just looks like any other piece of circuitry, until
you realise it’s a full-blown credit-card sized computer, ideal for learning
programming and home hacking.

Raspberry Pi 2 Model B
Raspberry Pi 1 Model B+
The older Raspberry Pi 2 model can still be found on sale. It has the
same form factor as the Raspberry Pi 3 with 4 USB Ports, Ethernet
connection and Micro USB.
It may look the same but it has a slower 900 MHZ quad-core ARM
Cortex-A7 CPU and 1GB RAM. This brings it close in line to many
low-end desktop computers.
Complicating matters slightly is the existence of a Raspberry Pi Model
1 B+, which is identical in layout to the Raspberry Pi Model 2 but with
an even slower ARMv6 700MHz processor. If you are confused which
type you own then type cat /proc/cpuinfo at the command line. If it
lists four ARMv7 processors you are using a Raspberry Pi 2, if you see
just one with ARMv6 then you have the older Raspberry Pi Model 1 B+.

Raspberry Pi 3 Model B+
The Raspberry Pi 3 Model B+ was launched on 14 March -
International Pi day 2018. This is an improved version with a faster
1.4GHz, 64-bit quad-core ARM Coretx-A53 processor, a dual-band
802.11ac wireless LAN and Bluetooth 4.2 controller, faster Gigabit
Ethernet, improved mass storage, USB booting, improved thermal
management and Power-Over-Ethernet support. All other aspects
of the new Raspberry Pi are the same as the previous Pi 3 and as
such, all the previous content you come across is compatible. if
you’re new to the wonderful world of the Raspberry Pi, this is the
board we recommend you buy.

8 Raspberry Pi Coding & Projects


Say Hello to Raspberry Pi

The Raspberry Pi is a British built low cost computer on a single board that’s roughly attached to the USB socket. A smaller Micro
computer that enables everybody to learn the size of a credit card. Each Raspberry Pi USB connection is used to provide power to
computing, start programming and explore board features a processor made by ARM, the device. Most Raspberry Pi models feature
basic electronics. It’s the size of a credit which is similar to the models you find in a an Ethernet connection, and an Ethernet
card but capable of running a full operating mobile phone. The ARM processor is fast
cable is connected from your Raspberry Pi to
system and doing everything a desktop does. and lightweight but it runs a different set of
software than you might be used to. There a socket on your modem router.
More importantly, with the Raspberry Pi you
are many different operating systems (OS) Both the Raspberry Pi 3 and 4 models have
install your own operating system, connect all
available, but for most of this book we’ll built in wireless networking and Bluetooth,
your devices and create your own programs
focus on one called Raspberry Pi OS, which
using languages like Scratch and Python. making it easy to get online. You can attach
is the OS recommended by the Raspberry Pi
There’s no case so you can hook up electronic a USB Wi-Fi dongle or Ethernet adaptor to
Foundation.
circuits to the pins and control them to get older models.
input and output, so you can hack together There’s no hard drive on the Raspberry Pi,
electronic projects at home. instead the operating system is installed First it will help to know which Raspberry
on an SD Card (the cards typically used in Pi you are using. This can be tricky as there
Setting up a Raspberry Pi is pretty simple,
cameras). The operating system is installed have been several distinct models so far. The
and throughout this book we’ll take you step-
onto the SD Card by copying the files to the layouts opposite will help you determine
by-step from unboxing your Raspberry Pi to
SD Card using a computer. We’ll show you which Raspberry Pi you have.
setting it up and getting started.
how to set up the Raspberry Pi OS using a
There are many different models of Mac or Windows computer. This book covers all the different models, and
Raspberry Pi available and each has slightly
Once you have an OS installed on the SD they offer largely similar features, although
different features (see opposite). newer models offer additional extras. Once
Card you can set up your Raspberry Pi. The
The fundamentals of each Raspberry Pi are Raspberry Pi is connected to a monitor via a you know which Raspberry Pi you own, you
similar though. Each model is a lightweight HDMI socket whilst a keyboard and mouse is can get it up and running.

Raspberry Pi 4 Model B
Released on June 24th 2019, the Raspberry Pi 4 Model B
introduced a new direction in the layout and hardware
specification of the Pi. The Pi 4 Model B now comes in three
different memory size versions: 2GB, 4Gb, and 8GB. Obviously, the
8GB version is the most powerful of the three, and the Pi with the
highest amount of on-board memory. Subsequently, it was sold
out on the day of release and as such, has taken some time to get
into the hand of the mainstream Pi users.

There’s also an improved CPU, dual-monitor support in the form of


a pair of micro-HDMI ports, and improved connectivity. Overall, it’s
certainly a more capable Pi.

Raspberry Pi Zero
The new Raspberry Pi Zero is a super small, super cheap computer
that costs just £4. It’s half the size of the model A+ but has a
surprising amount of power, including a 1Ghz single-core CPU and
512MB RAM. It has the full 40-pin GPIO header but you’ll need to
buy the pins separately and solder them in. It uses the same
Micro-SD card as the other Raspberry Pi devices, so you can swap
SD cards between them. Last but not least, it draws an incredibly
low amount of power (Micro USB) making it ideal for small power
devices. The ports are smaller than you’d find on the larger
Raspberry Pi though, so you’ll need a mini-HDMI adaptor as well as
a micro-USB adaptor to connect devices. A four-port USB Hub and
Ethernet adaptor will come in handy too.

www.pclpublications.com 9
Raspberry Pi is Good For You!

Get to Know the


Raspberry Pi
While the Raspberry Pi 4 is the newest model, the Pi 3 models are the most popular among
the community. They’re cheaper, more compatible with current hardware and software, and
still pack a significant performance punch. Here’s what powers the fantastic Pi 3.

40 GPIO Pins

The GPIO (General Purpose Input Output) pins can be


accessed directly on the Raspberry Pi. These are used
in projects to connect the Raspberry Pi to electronic
circuits and control electric devices. Some can be
turned on and off while the Raspberry Pi is running.

ARM-Powered

At the heart of the Raspberry Pi 3 is a


Broadcom BCM2837 System on Chip
(SoC). It contains a powerful 1.2GHz
64-bit quad-core ARM Cortex-A53
CPU. This is 50-60 percent faster than
the Raspberry Pi 2 and ten times as
fast as the original Raspberry Pi.

DSI

The Display Interface (DSI) can be used to connect a


display directly to the Raspberry Pi board.

SD Card Slot USB Power

Instead of a hard drive you use A standard Micro USB power supply is
an SD Card with the Raspberry used to provide power to the Raspberry
Pi. The Raspberry Pi 3 (pictured Pi. You don’t get a power supply but can
here) uses a Micro SD Card. use any 5V 2000mA Micro USB power
Some older Raspberry Pi models supply and compatible cable, or buy an
use a regular SD Card. official power supply separately.

10 Raspberry Pi Coding & Projects


Get to Know the Raspberry Pi

USB ports

The Raspberry Pi USB Ports to connect


standard computing accessories such
as a keyboard, mouse and webcam.
Raspberry Pi 2 and 3 boards contain
four USB ports but you might need
a USB Hub to get more ports on the
Raspberry Pi A+ and Pi Zero.

Ethernet and Wi-Fi

Connect the Raspberry


Pi 3 to a network or
home modem router
using an Ethernet cable
and this connection. The
Raspberry Pi 3 has built in
wireless networking, but
you must add a USB Wi-Fi
adaptor to older models.

3.5mm Audio/Video jack

This 3.5mm audio jack is


normally used to attach
headphones or speakers. On
the Raspberry Pi 2 and 3 it also
carries composite video using a
compatible cable.

CSI (Camera Serial Interface)

You can attach the official Raspberry


Pi Camera Module directly to the
motherboard via this CSI connection.

HDMI

The HDMI connection enables you


to hook up the Raspberry Pi to most
modern monitors and digital televisions.
It carries both video and audio.

www.pclpublications.com 11
Raspberry Pi is Good For You!

Up Close with the


Raspberry Pi 4 Model B
Released at the end of June 2019, the Raspberry Pi 4 Model B is a significant improvement
in terms of hardware. Labelled the ‘Ultimate’ Raspberry Pi, this new generation offers true
desktop computing power.

FASTER AND CONNECTED


There’s a lot to like about the Raspberry Pi 4: Up to 8GB of on-board memory, a faster quad-core CPU, support for dual 4K displays
via a pair of micro-HDMI ports, and more. Let’s take a look at the Pi 4, and see what it’s got under-the-hood.

PRICING
Since the Raspberry Pi 4 now offers three different
versions within the new model, it stands to reason that the
pricing for it has changed slightly. The 1GB memory version
of the Pi 4 is priced at around £34, depending on where
you shop. The 2GB memory version is on sale for around
£44, while the top-end, 4GB memory version will set you
back in the region of £54. Together with the cost of the Pi
itself, you will also need to factor in one or two micro-HDMI
cables (depending on whether you want to connect one or
two monitors), each costing roughly £5-plus.

Improved GPU

With a VideoCore 6 GPU, the Pi 4 is capable of


4K resolutions at 60FPS (Frames per Second),
and thanks to some tweaks to the video codes in
both Raspbian and the version of VLC packaged
with Raspbian, the Pi 4 is now a pretty decent
media device.

Improved Processing

The 1.5GHz, 64-bit quad-core ARM Cortex-A72


CPU, is the driving force behind the Pi 4’s improved
performance. Thanks to this CPU, you’re able to
enjoy faster apps and content.

Dual Display

In a shock move the team behind the Pi 4 decided


to include a pair of micro-HDMI ports. This means
you’re able to connect two monitors for dual-
screen displays.

12 Raspberry Pi Coding & Projects


Up Close with the Raspberry Pi 4 Model B

PI 4 SPEC SHEET
• 1.5GHz 64-bit quad-core ARM Cortex-A72 CPU • 2× micro-HDMI ports (up to 4Kp60 supported)
(ARM v8, BCM2837) • H.265 (4Kp60 decode)
• 2GB, 4GB or 8GB RAM (LPDDR4)
• H.264 (1080p60 decode, 1080p30 encode)
• On-board wireless LAN - dual band 802.11 b/g/n/ac
• OpenGL ES, 3.0 graphics
• On-board Bluetooth 5.0, low-energy (BLE)
• DSI display port, CSI camera port
• 2x USB 3.0 ports, 2x USB 2.0 ports
• Gigabit ethernet • Combined 3.5mm analog audio and composite video jack
• Power-over-Ethernet (requires the Raspberry Pi POE HAT) • Micro-SD card slot
• 40-pin GPIO header • USB-C power

NEW POWER & VIDEO


There are two major differences to the Pi 4 over its older
siblings: the use of a USB-C power port, and the newly
introduced micro-HDMI ports. Therefore, if you’re going to be
getting hold of a Pi 4, then you’ll also need to source a micro-
HDMI cable, and the relevant USB-C power adapter – since the
power and HDMI from the older Pi models won’t work with this
USB 3.0
fourth generation Pi.
The inclusion of a couple
of USB 3.0 ports is an
excellent choice. The
faster data bandwidth of
USB 3.0 will, for example,
enable the Pi to read and
write that data, both to
and from an external
drive, far quicker than
ever before.

Connectivity

Now with Bluetooth 5.0,


alongside 802.11 b/g/n/
ac wireless, and a gigabit
Ethernet port, the Pi 4 is
certainly well connected.

Memory

The RPi4 now comes


with a choice of
memory: 2GB, 4GB
or a 8GB model. The
more memory means
you’re able to have
more applications open,
without degrading the
overall performance of
the Pi.

www.pclpublications.com 13
Raspberry Pi is Good For You!

The Pi 400 –
Up Close
The Raspberry Pi 400 is an
all-in-one keyboard Pi that was
released in November 2020,
offering the user a different
approach to their Pi lifestyle.
This compact and powerful Pi is
the flagship of a new kind of Pi,
and one we’ll hope to see more
of in the future.

Inside the Pi 400 is a modified Raspberry Pi 4. It’s


longer, spanning the width of the keyboard, with a large
heatsink to dissipate enough heat for the overclocked
processor. The Pi 4’s communication ports are spaced
along the back of the Pi 400 keyboard, minus a second
USB 2.0 port and a 3.5mm audio jack.

40-Pin GPIO

The slightly recessed GPIO port


is directly connected to the Pi
400 board inside the keyboard.
This means you can still attach microSD Card Slot
the usual Raspberry Pi HATs and
The microSD Card Slot is where you’ll insert
other devices as you would a
the card that contains the Raspberry Pi OS – or
bare-metal Raspberry Pi.
any other operating system you prefer to run
that’s compatible with the Raspberry Pi 4.

micro-HDMI Ports

As with the Raspberry Pi 4 bare-metal device, you’re


able to connect to a dual-monitor setup with the Pi
400 via the two micro-HDMI ports. Both are capable
of up to 4K at 60 frames-per-second.

14 Raspberry Pi Coding & Projects


The Pi 400 – Up Close

TECH SPECS
The Pi 400 has a slight advantage over the
Raspberry Pi 4 in terms of its processing power,
but it loses out in the overall memory department.
However, the specs are an impressive Broadcom
BCM2711 quad-core Cortex-A72 (ARM v8) 64-bit
USB-C Power 2x USB 3.0 Ports SoC, overclocked to 1.8GHz – and tests have shown
that the Pi 400 can be further overclocked to a
The Pi 400 is powered by the There are two fast USB 3.0 ports
stable 2.2GHz. And there’s 4GB of LPDDR4-3200
same USB-C connector power available on the rear of the Pi 400,
memory available too.
adapter as the Raspberry Pi 4, so you can attach projects, as well
offering a minimum of 3A. as game controllers and other Not bad for a mere £94, which includes the Pi
such devices. 400, micro-HDMI cable, power supply, and a 16GB
microSD card pre-programmed with the latest
Raspberry Pi OS.

Regional Keyboard

The Pi 400’s keyboard is available in a


number of regional variations: UK, US,
German, French, Italian and Spanish.

USB 2.0

There’s also a legacy


USB 2.0 port available. Wi-Fi
In case you’re
wondering, where the The Pi 400, like the Raspberry
Pi 4 had two USB 2.0 Gigabit Ethernet Pi 4, comes with dual-band,
ports, on the Pi 400 the 2.4GHz and 5GHz, IEEE
other USB 2.0 port is Gigabit Ethernet offers a fast 802.11b/g/n/ac wireless
hardwired as an internal connection for the Pi 400 to your home connectivity, along with
ribbon connected to, network and peripherals. Bluetooth 5.0.
and powering, the Pi
400’s keyboard.

www.pclpublications.com 15
Raspberry Pi is Good For You!

Pi 400: Return of the 80s


Home Computer
The 80s is considered the golden era of the home computer, a time when computing
components were small enough to fit inside the living room of a house, and versatile
enough to work on as well as play games. It was a wonderful time to experience, and the Pi
Foundation has kept that feeling alive with the Pi 400.
Released in November 2020, and while the UK and most of the world was still in lockdown, the Raspberry Pi 400 came at a time when we
were beginning to feel like there was no end to the pandemic and the restrictions it brought. Initial thoughts were that the Pi 400 was a new
small-board computer, in a similar vein to the Pi 4 and its predecessors. However, we were quite wrong.
The Pi 400 is a very different beast to that of its siblings. Rather than the naked board we’ve seen in the past, the Pi 400 came as a complete
keyboard package, with the Pi’s familiar ports lined up along the backplate of the keyboard.
This in itself was remarkably reminiscent of the home microcomputers of the 80s, the prime examples being the ZX Spectrum and the
Commodore 64. Indeed, the nostalgia was strong with this one, and it brought a smile to more than one retro fan’s face.

The overclock is thanks to the inclusion of a large, internal


THE REINVENTION OF THE aluminium heatsink, that spreads across the entire internal
MICROCOMPUTER space of the keyboard. This, and thanks to a couple of air vents
It’s more than sheer aesthetics that makes the Pi 400 hark back to on the bottom of the keyboard, are what allows the Pi 400 to be
a simpler age of computing. Inside the keyboard is a Raspberry Pi 4, overclocked to the default 1.8GHz. In fact, we even took the Pi 400
albeit one that’s had a facelift and some hardware alterations. The to an impressive 2.2GHz, and it remained stable and cool enough
Pi 4’s ports, which are the twin micro HDMI and USB 3.0 ports, USB for continual operation.
2.0, Gigabit Ethernet and microSD card slot, take up the rear of the
The heat dissipation from the large heatsink is a great idea – and one
keyboard together with a port that connects directly to the 40 GPIO
that was previously seen in the Commodore 64. There’s also a thermal
pins – and resembling an older style communications port from the
sticky pad on the top of the heatsink, that’s attached to the Pi 400’s
rear of an XT or earlier machine.
processor and helps to lift as much heat as possible from the CPU. If
In terms of hardware, the Pi 4 inside the Pi 400 has been expanded to you get inside, you’ll also see why the Pi 400 is missing a USB 2.0 port;
fit most of the width of the keyboard. The processor is the same ARM since it only features a single 2.0 port over the Pi 4’s dual USB 2.0 ports.
v8 Cortex-A72 as found in the bare Raspberry Pi board, but in this One of the Pi 400’s USB 2.0 ports has been used as a hard-wired ribbon
instance it’s been overclocked to 1.8GHz; 300Mhz faster than the bare connector to the keyboard section of the unit. Again, those of you
board. There’s also 4GB of LPDDR4 RAM installed, but sadly no sign of familiar with the internals of an 80s home computer will recall ribbons
an 8GB version – which the Pi 4 bare model has on offer. being attached to keyboard membranes.
The keyboard itself is available in different language layouts: UK, US,
Germany, France, Italy and Spain. Essentially, it’s the same keyboard
that the Pi Foundation has been selling for some time, except this time
there’s an actual Raspberry Pi inside of it as opposed to it simply being
a multi-port USB hub.

16 Raspberry Pi Coding & Projects


Pi 400: Return of the 80s

PI 400 DESKTOP COMPUTING


One of the prime benefits of having the Pi 400 keyboard
setup is the fact that it can be quickly plugged into a monitor
and working from the moment you hit the power key. The Pi
4 bare board, for example, requires a separate keyboard and
mouse, and, let’s be honest here, not many folk want to see
a bare circuit board on their desk. True, there are some great
design Pi 4 cases around these days, but the Pi 400 already
comes in a neat package.
The extra overclock brings a decent amount of oomph to the but if you’re limited to wired models, then you could be looking to
Pi 400, and as such it’s perfectly reasonable to use the Pi 400 buy upgrades.
as a standard desktop computer. However, there comes with However, with all that in mind, the Pi 400 is another step closer to
it some negatives in this respect. becoming the only computer you’ll ever need.
While a great device, the Pi 400 is a little too small for
comfort, specifically a typical working day’s use. It’s roughly
the same size as a laptop keyboard, but the keys don’t feel
THE ZX PI 64
as good – a bit too squishy for our tastes. But, as with most There’s a good feeling of nostalgia when plugging in a Pi 400 to
things, we’ll probably get used to it over time. a monitor or TV. It’s like you’re back to being 10 years old again
and plugging in the Spectrum or the C64 for a spot of gaming or
Another caveat that’s worth mentioning, is that the Pi 400
homework, before having to unplug it all when your Mum calls
lacks a 3.5mm audio port. Where the Pi 4 model had one, this
through that dinner is ready.
doesn’t, instead opting to output sound via the HDMI port(s).
While this isn’t a deal-breaker for most, it does mean that for Thankfully, these days, it’s easy to save where you were – and the
personal listening you’ll need to hook up a set of headphones entire thing doesn’t crash when the kettle is switched on!
to your monitor, or find another solution. The built-in Overall, the Pi 400 is a great addition to the Foundation’s stable,
Bluetooth will connect to headphones with that technology, and one that we’re sure you’ll come to love and use daily.

www.pclpublications.com 17
Raspberry Pi is Good For You!

Ten Pi 400 Projects


and Ideas
You may think that a Raspberry Pi 4 inside a keyboard would create some limitations,
however that’s not the case. Indeed, you won’t be able to utilise the Pi 400 in quite the same
way as a standard Pi 4, but there’s a lot you can get to grips with.

EVERYONE LOVES PI
We’ve put together ten possible projects that you could use your Pi 400 with; that will entertain and keep you busy while helping you learn
more about coding, the Pi and computing.

With the Pi 400 being very similar to Since we’ve mentioned the ZX Spectrum, it’s only fair
RETRO COMPUTING C64 LOVE
that of the great home computers of that we include the other great 8-bit home computer
the 80s, we thought we’d start these ideas with a simple retro-themed from the 80s, the Commodore 64. The Pi uses a program called
project. Fuse is a ZX Spectrum emulator that’s available for the c64-raspi for C64 emulation, and can be installed via https://
Raspberry Pi. Install it, and you can enjoy some of the greatest games c64emulator.111mb.de/index.php?site=pp_
ever created. raspi&lang=en&group=c64.

It’s possible to stream any game While we’re on the subject of streaming
STREAM PC GAMES GOOGLE STADIA
installed on your powerful gaming PC games, if you own a Google Stadia, then
to a Raspberry Pi. All you need is to ensure that your home network is you’re able to stream games to the Pi via the Chromium browser.
up to scratch – use Ethernet connections between the two if you can You’ll need a good network connection, and some games may well be
– and to install Parsec from https://parsec.app/downloads. a bit laggy, but it’s worth a try.

18 Raspberry Pi Coding & Projects


Ten Pi 400 Projects and Ideas

The Pi 400’s 1.8GHz processor is adequate Since lockdown started in 2020, folk have been
OVERCLOCKING DESKTOP PC
for most tasks, but thanks to the large, coming up with novel ways in which they can
metal heatsink inside the keyboard, it’s possible to get that clock work and educate at home on a budget. The arrival of the Pi 400
speed even higher. There’s a great YouTube tutorial on how to was a great boost for home working, and it makes for a great
overclock the Pi 400 to 2.2GHz at https://www.youtube.com/ desktop PC. Just add a mouse, dual monitors and you can even use
watch?v=DqZ99mGbSR0. Teams via Chromium.

Yes, it’s possible to run a version of The default Raspberry Pi OS isn’t


RUN WINDOWS 10 INSTALL A DIFFERENT OS
Windows 10 on the Pi 400. There are the only operating system
going to be some limitations; there’s no sound, Wi-Fi or Bluetooth, but available for the Raspberry Pi. We’ve already seen RetroPi, but there’s
it’s a fun project that’s definitely going places. Check out the install also a version of Ubuntu, an entertainment OS called LibreElec,
video courtesy of Lepspvideo at https://www.youtube.com/ RISCOS, the original ARM OS and many more to discover.
watch?v=xbRBovkmZvU&t=0s.

The Pi 4 made for a great platform on which The Pi 400 makes for a great under-the-TV
CODING BASE MEDIA CENTRE
to learn how to code, but thanks to the media centre. You don’t specifically need a
neater approach of the Pi 400, it’s now an even better base on media-centric operating system, the Raspberry Pi OS will suffice. With
which to code. You can learn how to code with Python, it you can watch network-stored movies, browse the Internet, watch
MicroPython, C and C++ and many more languages. Check out YouTube content and much more.
our coding guides at https://bdmpublications.com.

www.pclpublications.com 19
Raspberry Pi is Good For You!

The Pi Pico –
Up Close
The Pi Pico isn’t your normal Raspberry Pi. Instead,
this is a tiny microcontroller, designed to help
enthusiasts control and utilise connected appliances
and electronics projects. From displaying an LCD to
controlling LEDs, using MicroPython and C++.

The Pi Pico may be small, but it packs a decent punch. With it you can
expand your electronics projects, and incorporate a whole new level
of functionality that you weren’t able to before with the traditional
Raspberry Pi units.

micro-USB Port

The Pi Pico’s micro-USB provides both power, as


well as communications between the Pico and a
Raspberry Pi or other computer. Here you’ll be able
to upload programs and projects on to your Pico.

PICO SPECIFICATIONS Boot Selection Switch


• 21mm × 51mm form factor • 8 × Programmable I/O (PIO) state
machines for custom peripheral support
The small button labelled
• RP2040 microcontroller chip designed by BOOTSEL, Boot Selection, will
Raspberry Pi in the UK • Supported input power 1.8–5.5V DC switch the Pico between two
• Dual-core Arm Cortex-M0+ processor, • Operating temperature -20°C to +85°C start-up states enabling you
flexible clock running up to 133 MHz • Castellated module allows soldering to access the Pico as a storage
• 264KB on-chip SRAM direct to carrier boards device on your computer or
Raspberry Pi.
• 2MB on-board QSPI Flash • Drag-and-drop programming using mass
• 26 multifunction GPIO pins, including 3 storage over USB
analogue inputs • Low-power sleep and dormant modes
• 2 × UART, 2 × SPI controllers, 2 × I2C • Accurate on-chip clock
controllers, 16 × PWM channels • Temperature sensor
• 1 × USB 1.1 controller and PHY, with host • Accelerated integer and floating-point
and device support libraries on-chip

The Pico is a great little project board, with plenty of potential for those who love to tinker with
electronics and stretch their knowledge of everything that’s connected.

20 Raspberry Pi Coding & Projects


The Pi Pico – Up Close

Memory & Storage

The Pico comes with 264KB on-chip SRAM


memory, as well as 2MB on-board QSPI
Flash memory; to store your code and
projects.

CPU

The processor of the Pi Pico is an RP2040


microcontroller, a custom designed
integrated circuit built specifically for
the Raspberry Pi Foundation. It’s a dual-
core ARM Cortex-M0+ processor, with a
flexible clock speed up of to 133MHz.

GPIO Pins

The cutouts located down both


sides of the Pico are its GPIO
ports – which work in much the
same way as the Raspberry Pi’s
GPIO ports. There are 26 of
them, including three analogue
inputs.

www.pclpublications.com 21
Raspberry Pi is Good For You!

Pico Power:
The Tiny Microcontroller
When is a computer not a computer: when it’s a microcontroller. To be fair, a computer, by its
true definition, is an electronic device for storing and processing data, which is what the Pico
does. But for most users, a computer is defined as a device that sits on a desk, something
you can work and play on. This is where the Pico differs.
The Pico is something entirely different from the Raspberry Pi Foundation’s usual releases. Whereas the Raspberry Pi, now on version 4, is a
small computer, and even the Compute Module and the Pi 400 are still just computers, the Pico is actually a microcontroller.
A microcontroller is a processing unit that’s designed to work with programmable peripherals, and has input and output modules alongside
a small amount of memory and storage capabilities. The processors are often scaled down, compared to the processor on a Raspberry Pi, or
even inside your desktop computer, but powerful enough to complete basic tasks.
Examples of a microcontroller in action can be found inside a washing
machine, or traffic lights. A washing machine has no need for a quad-core
processor, 8GB of memory, and the ability to output to a 4K monitor.
Instead, it has a set of microcontrollers, that are connected to various parts
of the washing machine – such as the pump, or motor. When a signal is sent
to an input on the washing machine’s microcontroller, it knows – through
some clever programming stored in its limited memory – that it needs to
send a signal output to the valves to allow in a certain amount of water, A basic microcontroller
circuit board inside a
then activate the motor for the drum and so on. washing machine.

The same can be applied in the traffic light example. A powerful computer
isn’t necessary, so a microcontroller will activate the red, amber and green
lights in sequence, or switch to red to stop traffic when someone presses the
Walk button.
While it would probably be interesting to have a powerful computer inside
your washing machine, it’s overkill. A microcontroller takes up less space,
uses less energy, and isn’t prone to the kind of crashes or in need of the

frequent updates that a traditional computer


requires. They simply sit there, act on inputs
that come their way, process that data, and
output whatever is required depending on the
input actions.
Power use is the main reason why
microcontrollers are in action everywhere we
look. There’s often limited supply to devices, or
situations. A microcontroller can work effectively
with the limited amount of energy drawn from
a small solar cell – even in the most overcast
of northern climes. For example, on-board the
International Space Station, there are thousands
of microcontrollers in action: monitoring air
quality, monitoring radiation levels, distributing
power and keeping track on the crew. If each of
these units were a more powerful computing
device, the power draw on the ISS would be
immense; so microcontrollers are the way forward
– at least until we work out how to build a warp
core with near unlimited energy, that is.

22 Raspberry Pi Coding & Projects


Pico Power: The Tiny Microcontroller

The Raspberry Pico GPIO


mapping.

PROGRAMMABLE PICO
The main difference between the microcontrollers inside your
everyday appliances and the Pico, is that where the microcontrollers
within your washing machine are pre-programmed with their
instructions, the Pico isn’t and can be programmed by you.
This means that you can use the Pico’s USB port to connect to a
computer, write some code to control something, upload the code to
the Pico’s RP2040 microcontroller, and watch as it does what you’ve
asked it do.
The 26 multi-function GPIO pins, located down the long sides of the
Pico, can be used to solder electronics projects to. And with some
clever coding, you’re able to control the input and output of devices
depending on their state via the Pico microcontroller.
Each of the Pico’s GPIO pins have specific uses, as you can see from
the pinout chart. This means that certain electronic components
soldered to the pins, can be programmed using the Pico’s primary
microcontroller language, MicroPython (or C++).

REMEMBER, IT’S NOT A PI


It’s worth mentioning that the Raspberry Pico isn’t designed the
same as, or can replace, a Raspberry Pi. This is a different type
of device altogether. Where you’ll use your Pi to browse the
Internet, play a game, do some coding and so on, the Pico can’t do
that. It’s designed for use with physical components and projects,
such as lighting LEDs or responding to a button push, controlling
motors and the like.

If you want more versatility for your projects, then the Raspberry
Pi is still the perfect device to use. If you’ve got something
specific in mind, and you want to expand into electronics and
microcontrollers, then the Pico will fit the bill. But, you’ll also
need a computer, or Raspberry Pi, in order to program the Pico to
begin with.

www.pclpublications.com 23
Raspberry Pi is Good For You!

The Pico and MicroPython


The beauty of the Pico is that it’s a blank microcontroller, meaning that it’s free from any pre-
installed code or routines. This allows you to program the Pico to whatever tasks or projects
you have planned for it. But first, you’ll need to set it up and get it ready to use MicroPython.
The Pico uses MicroPython or C/C++ code in order to communicate
with the devices it will be attached to. The code will, when MICROPYTHON
uploaded to the Pico, run a specific set of instructions depending MicroPython is a Python 3-based coding language that’s designed to
on the electronics that are soldered to the Pico. For example, in be executed on the RP2040 microcontroller – the one that’s powering
MicroPython, with an LED attached to the Pico, you would initialise the Pi Pico. It’s a highly efficient language, and thanks to the Pico’s
and import the Pin and Timer modules, tell the Pico which GPIO larger than average memory and capacity – for a microcontroller
the LED is attached to, then setup a routine that will use the Timer – it’s the ideal language to start learning. If you already have some
function to send a signal to the LED – let’s say every couple of experience with Python 3, then MicroPython should be relatively
seconds. The end result would be a blinking LED, which goes on and easy to follow; since they’re essentially the same. If you’ve never used
off every two seconds. Python before, then we’d recommend you take a look at one of our
Naturally, the more complex the electronics attached to the Pico are, coding titles at, https://bdmpublications.com.
then the more complex the MicroPython code will be to make them Before you can use MicroPython, though, you’ll need to flash the
work in the way you want.
Pico with the latest version of MicroPython. This means downloading
MicroPython is probably the best language to begin with when it the latest version of MicroPython and uploading it onto the Pico. The
comes to programming the Pico. Like Python, it’s a bit easier to get process is remarkably easy, however.
your head around – when compared to C or C++ - and it’s probably
Start by connecting one end of a USB cable to the Pico. Then press
slightly easier to get up and running. There’s also the added
and hold the BOOTSEL button on the Pico, while at the same time
advantage of there being more examples of it online, so you can dip
plugging the other end of the USB cable into your computer, or a
into the various sites around the Internet and take the code snippets
you need to make certain devices and peripherals work. Raspberry Pi. Count to five, then let go of the BOOTSEL button.
Within a few seconds the computer, or Raspberry Pi, will display a
notification that an external, or removable, drive has been attached
– in the same fashion as when you plug in a USB flash drive.
If you open your File Manager or Explorer window, and navigate to
the newly installed Pico storage, you’ll see two files present: INDEX.
HTM and INFO_UF2.TXT.
The INFO_UF2.TXT file contains information regarding your Pico,
and the INDEX.HTM is a web-based page that contains all the
information you’ll need to get the Pico connected and installed with
MicroPython.

24 Raspberry Pi Coding & Projects


The Pico and MicroPython

Alternatively, you can open a browser and navigate to https://www.


raspberrypi.org/documentation/pico/getting-started/. Scroll down
until you get to the Getting started with MicroPython section, and
follow the on-screen instructions. Click on the Download UF2 file
button – at the bottom of the Getting Started info box.
Once the UF2 file has been downloaded, locate it in the Downloads
folder on your computer, and click and drag it into the Pico storage
drive; as you would drag and drop a file from your computer to a
standard USB flash drive.
After a few seconds, the Pico storage drive will disappear – you may
get a warning stating that the device wasn’t unplugged correctly,
but ignore that. This process has now ‘flashed’ the Pico with the
MicroPython firmware. The Pico disappearing from the File Manager
means that it has rebooted and is now in MicroPython mode. This is
essentially all you need to do for the moment. The Pico is now ready
to start coding on to using MicroPython.

GET READY TO PICO CODE


While the Pico is in MicroPython mode, it doesn’t do much. You
need to get access to the MicroPython layer through an Integrated
Development Environment (IDE). The Raspberry Pi Foundation has
adopted Thonny as its default IDE for use with MicroPython, since
it’s already built-in to the Raspberry Pi OS; as found on the Pi 4, Pi
400 and so on.
What you need to do is open Thonny – make sure the Pico is still
connected to your Raspberry Pi – then when it’s loaded, click on the
Python label in the bottom-right of the Thonny window; it’s going to
say Python followed by a version number, such as ‘Python 3.7.3’.
This is the current interpreter that Thonny is using for the process of
taking the code you enter and converting it into instructions that the elements due to the fact that it’s designed to work on a much-lesser
computer can understand and execute. When you click the Python processor – most of the usual Python syntax command will work,
label, you’ll notice a small menu appear, in which will be listed such as print(“Hello, world!”) and so on. You can also run loops and
‘MicroPython (Raspberry Pi Pico)’. Click the MicroPython entry. This other such repetitive routines, as well as store variables.
will change the Shell window, the lower-portion of the Thonny app, The Shell portion of Thonny can be used to ‘talk’ directly to the Pico’s
to read MicroPython, followed by the version number. MicroPython interpreter, whereas the blank upper-section of Thonny
Thonny and the Pico are now ready to be coded on to. Since can be used to write multiple lines of code which can then be saved
MicroPython is based on Python 3 – with some scaled-down to the Pico and executed later.

GET DISCOVERING
The world of the Pico is now open to you. From here, you can run through many of the examples that are available online, connect electronic
elements to the Pico and have them function through MicroPython, or even stretch your learning and discover how the Pico works with the C
and C++ programming languages.

www.pclpublications.com 25
Raspberry Pi is Good For You!

Pico Examples and How To


With the Pico now ready to accept MicroPhython code, it’s useful to understand some of
the basics and how to get started. We’ve put together some foundation examples with
MicroPython, to help you begin to get to grips with this wonderful microcontroller.
When you flash the Pico with the latest MicroPython the Pico will enter a wait state, waiting for instructions from you through MicroPython.
You can easily start to upload a pre-created Python file, a .py file, on to the Pico’s storage, however, you can start to ‘talk’ to the Pico
immediately via REPL.
REPL, pronounced ‘ripple’, stands for Read, Evaluate, Print, Loop. Read means that MicroPython is waiting for you to enter code; Evaluate will
interpret the code and begin to execute it; Print displays the results of the last executed line of code; Loop returns to the start, prompting
you for more code.
You can access the Pico via the command line, through a tool called Minicom, but since we’ve already got Thonny up and running, it makes
sense to stick with the path of least resistance and code the Pico (communicate with it) using Thonny’s interface.

What you’ve just done is communicate directly with the Pico, and
HELLO, WORLD! through MicroPython on the Pico, it’s recognised the command you’ve
The most popular first lines of code is the good old “Hello, world!”. entered and acted on it.
In Thonny, click into the lower Shell section, to the right of the three Just for fun, enter the command again, but this time intentionally
right-facing greater-than signs ‘>>>’. Now, enter the following:
miss out the last bracket. You’ll notice that the Shell doesn’t want
print(“Hello, world!”) to continue without the bracket, so therefore it’s an error. While
using MicroPython, or most other programming languages, you’ll
Users of Python will undoubtedly recognise the syntax, but if you’ve need to be careful what you type. The slightest mistake can have
never coded with Python before, then let’s explain what’s going on in dire consequences to your code – or, more than likely, it’ll just stop
this simple line. it from working.
The print command, as you probably assume, is used to print, or
For the next example, click the upper part of Thonny, where the number
display, something to the screen for the user to read. If you want
‘1’ is. Now enter the Hello, world code again. When you hit Enter this
to say something to the user, then you’ll need to enclose your text
time, you’ll notice that instead of running the code through the Pico,
inside a pair of brackets and quotation marks. In this example, we’re
Thonny has created a second line and is waiting for more input.
displaying the words Hello, world!. When the MicroPython
interpreter reads the Print command it will naturally assume that While using the Shell is great, it’s not so good for creating multi-line
something is being displayed, and look for a number of acceptable code. This is where the upper section comes in. To execute the code in
outcomes. The first bracket and opening quotation mark means the upper section you’ll need to do the following: Click the Run button;
there’s going to be some text, so the interpreter will look for a closing this opens a new window asking for a save location (This computer or
set of quotation marks and bracket. the Raspberry Pi Pico). This is because any code that’s been entered
Press Enter, and the words Hello, world! will appear in the Shell in the upper section of Thonny needs to be saved first, as a .py file,
section of Thonny. before it can be executed.

26 Raspberry Pi Coding & Projects


Pico Examples and How To

Select the Pico as the save location, then when asked, create a name for
the .py file – in this case call it HelloWorld.py – and click the OK button.
BLINKING LEDS!
MicroPython, as with Python, uses modules to enhance the code
As soon as you’ve saved the file, it will automatically run and you’ll see
you’re writing. A module is simply further code, but when called
the output from the code displayed in the Shell box.
upon by your code it will operate to specific parameters. For
Alternatively, you can open a browser and navigate to https://www. example, there are modules available that are designed to handle
raspberrypi.org/documentation/pico/getting-started/. Scroll down graphics, while others handle complex mathematical operations.
until you get to the Getting started with MicroPython section, and Using these modules saves you from having to invent the code and
follow the on-screen instructions. Click on the Download UF2 file place it among the many lines you’re typing in. All you need do is call
button – at the bottom of the Getting Started info box. up the module, and pass any variables and parameters through the
Once the UF2 file has been downloaded, locate it in the Downloads module to get the result you want.
folder on your computer, and click and drag it into the Pico storage In MicroPython, and in the Pico’s case, there are modules that can
drive; as you would drag and drop a file from your computer to a be called upon that handle the physical hardware side of things. The
standard USB flash drive. Pico-specific modules will handle input and output through the GPIO
After a few seconds, the Pico storage drive will disappear – you may ports, or utilise some of the Pico’s inherent sensors. For example,
get a warning stating that the device wasn’t unplugged correctly, here’s some code that will light up the built-in LED on the Pico:
but ignore that. This process has now ‘flashed’ the Pico with the
MicroPython firmware. The Pico disappearing from the File Manager
from machine import Pin
means that it has rebooted and is now in MicroPython mode. This is
led = Pin(25, Pin.OUT)
essentially all you need to do for the moment. The Pico is now ready
led.on()
to start coding on to using MicroPython.

Type it into the upper section of Thonny, save it as LED.py (for


example) and run the code. The LED will light up. But, let’s explain
what’s going on here.
To begin with we have, from machine import Pin. This means that the
code is going to open the built-in module called Machine, of which a
certain class within it is called Pin. This particular set of external code
is designed to ‘talk’ to and handle the input and output of the Pico’s
GPIO pins.
The next line, led = Pin(25, Pin.OUT). What we’ve done here is
create a variable called led, which we’ve told to hold the information
regarding the Pin class, in particular the number 25, as an Output. The
GPIO pin on the Pico is hardwired to the LED, so essentially we’ve told
MicroPython that Pin 25 is going to have Output data sent to it, and
it’s going to be called led.
The final line, led.on(), is a trigger that sets Pin 25 Output to a high
value – in this case, On. The result is that the LED on the Pico will be
turned on. Try and alter the code, so the last line reads:

led.off()
As you would expect, this turns the LED off. Now
try:
led.toggle()

www.pclpublications.com 27
Raspberry Pi is Good For You!

What toggle() does is every time the code is executed, if the LED is on
it will switch off, and if it’s off it’ll switch on. Interesting stuff, isn’t it.
Let’s expand our LED code further and include a loop with another
kind of module:

from machine import Pin


from utime import sleep
led = Pin(25, Pin.OUT)
for i in range(5):
led.toggle()
sleep(1)
led.toggle()
sleep(1)

When you execute this new code, it will blink the LED five times –
based on whether the LED was previously on or off using the led.
toggle() syntax we looked at a moment ago. Let’s take a moment to
break down the new elements of the code, though.
From utime import sleep, as you probably suspect, this is using
a new module called utime, from which we want to use the sleep
class. Utime holds code that can be used for timing, and the sleep class
enables the code to pause for a specific number of seconds.
For i in range(5), is a new line which is the beginning of a loop.
Basically, we’ve asked MicroPython to count to 5, and anything after
the colon is repeated five times. Providing what code we’ve entered in
the loop is okay, it’ll do it five times before stopping. Note: The indent
after the colon. This means that the code in the indent is directly
controlled by the for loop. Indents in Python are as important as
spelling and getting the correct characters in order.
The final new element is sleep(1), which pauses the code for the
count of one, or one second. Feel free to mess around with the code
you’ve created. Extend the number of seconds, use led.on and led.off
instead of toggle, and extend the for loop to more than five.

28 Raspberry Pi Coding & Projects


The Pico and MicroPython

TEMPERATURE READINGS
The Pico also comes with a built-in temperature sensor, and is
connected to one of the Pico’s analogue pins. The analogue pins on
the Pico are actually called ADC’s – or Analogue to Digital Converter
– whereas the GPIOs are digital. The difference is that a digital pin
reads only two states: High or Low (or One and Off), and an analogue
pin can read a range of values from zero 65535 (through the use
of MicroPython, the Pico’s ADC really reads from zero to 4096).
This means that anything that’s read through the analogue pins
can be from 0 to the value of 65536, which makes it perfect for a
temperature sensor.
The temperature on the Pico is hardwired into ADC4 – or analogue
pin 4. So we can extract the data from the temperature sensor using
the following code:

from machine import ADC


tempsensor = ADC(4)
temperature = tempsensor.read_u16()

print (temperature)

There’s a lot going on here, and the displayed number that appears
in the Shell probably won’t make much sense, so let’s have a look at
the code.
First we’re using the machine module and from it the ADC class.
Then we’ve created a tempsensor variable which will pull the data
from ADC pin 4 – which is the Pico’s temperature sensor. The third
line of the code creates a temperature variable, which stores the
value of ADC4 and applies a 16-bit data range to it so we can have a
value from 0 to 65535. And finally, we’re printing the currently held the already read temperature variable and multiplied that by the
value of temperature in the Shell. volts value. We’ve then created a Celsius variable, which we’ve used
Now here’s the part that will make your head hurt. the above numbers to store the value of 27, minus the temperature
value, minus 0.706 and divided by 0.001721. This will give us a
The Pico’s microcontroller runs at 3.3 volts. So when there’s a full reasonably accurate conversion of volts to
3.3V being applied, the ADC will read a value of 65535, and when Celsius, which the code will then print
there’s no voltage it will read zero. The temperature sensor on into the Shell section of Thonny.
ADC4 works by sending voltage to ADC4 that is proportional to the
environmental temperature. So if the environment the Pico is in is 27 As you can see from the
degree Celsius, the Pico sends a voltage of 0.706V. So, using the 3.3V screenshot, the room we ran
maximum at the value of 65535 and the operational specifications this code in was a balmy 20.49
of 27 degrees Celsius as being a voltage of 0.706V, we can work degrees Celsius. When we
out code that will convert the original value you got from the looked at the temperature on the
temperature variable into degrees Celsius. digital thermostat in the same room, it
read 21 degree Celsius, so only half a degree out,
Before our brains dribble out, here’s the rest of the code: which isn’t too bad.

from machine import ADC

tempsensor = ADC(4)
THE WORLD OF THE PICO AWAITS…
temperature = tempsensor.read_u16() This is only a small example of the type of projects and coding that
can be achieved with the Pico and MicroPython. There are numerous
volts = 3.3 / 65535 extras, such as motors, sensors, LEDS and even LED screens that can
temperature = temperature * volts be attached to the Pico’s GPIO ports with some neat soldering and
the use of a handy electronics kit.
celsius = 27 - (temperature - 0.706) / 0.001721 What we’ve looked at here is a taster, and the foundations on how to
call up the Pico’s GPIO pins and how to use MicroPython in Thonny.
print (celsius) From here, we’d recommend you learn more about how the Raspberry
Pi functions as well as some more Python coding, which will give you a
Let’s run through the code. We’ve created a volts variable which better insight into how the Pico and MicroPython will work.
takes the maximum 3.3V and divides it by 65535, then we’ve taken Have fun, and let us know what Pico projects you’ve created.

www.pclpublications.com 29
Raspberry Pi is Good For You!

Pico Projects & Ideas


There are some interesting projects you can apply your Pico to. Thanks to its
combination of processing power, GPIO pins, and MicroPython language, the only real
barrier is your own imagination.

PICO POWER!
Here are ten ideas and projects that you could look into achieving with your Raspberry Pi Pico. You may need to enhance your electronics
skills, but there’s plenty of help online if you hunt around for it.

Can you create a Pico-powered microcontroller to MOTORS In addition to the robotics idea, a Pico can be used to
ROBOTICS
work different aspects of a robot? You could use the control motors. Again, depending on the input to the
Pico to drive the robot, or control an element on it depending on Pico, the output can spin up a motor and move an object, stop it, or
where it is in your home. even power something else.

TEMPERATURE GAUGE The Pico’s RP2040 processor has a Why not hook up some coloured LEDs, and
TRAFFIC LIGHTS
built-in ADC to convert analogue to use the Pico microcontroller as a set of
digital signals. It also has a built-in temperature sensor, so it’s possible traffic lights. You can even incorporate a button, that when pushed
to utilise the Pico as a temperature gauge. will act as a Walk button and stop the traffic for pedestrians.

30 Raspberry Pi Coding & Projects


Pico Projects and Ideas

Using an infrared sensor, you can wire up If you’ve got the


MOTION SENSORS MOON TRACKING TELESCOPE
and solder your own motion detection know-how, then the
sensor. Which means you can create a burglar alarm, or include it with Pico, together with a phototransistor sensor, and a telescope, could
the robot idea to allow some form of autonomy. be used to create a scope that can track the passage of the Moon
through the night sky.

Using buttons and LEDs, you can With the infrared motion
BUTTON PUSH GAME NATURE PHOTO CAPTURE
create a simple button push reaction sensor, you could attach the
game, for multiple players. Perhaps you could attach a buzzer that Pico to an outdoor camera – or camera within a weather-proof
signifies the winner or loser. container – to activate when something passes the sensor; capturing
that neighbour’s pesky cat in the act!

Most home automation tasks are There are a number of Pico-built RGB
HOME AUTOMATION ATTACH A DISPLAY
run through microcontrollers, so LED displays available online. You can
the Pico is suitably placed for those who have setup some advanced use one to display messages, create some form of interactive
home automation devices. Elements such as turning the heating or game, or display data that’s coming from one of the input GPIOs
lights on, or opening the garage door, for instance. attached to a sensor.

www.pclpublications.com 31
Raspberry Pi is Good For You!

Other SBCs to Use


Although the Raspberry Pi is the king of the single-board computing market, it’s not the only
device that you can work, play and conduct experiments on. In fact, there are quite a lot of
SBCs out there that are worth looking into.
An SBC, or Single-Board Computer, is a complete computer system that’s built on a single piece of circuit board; consisting of memory,
storage and input and output ports. The Raspberry Pi is a prime example of a modern SBC, and the one that has easily become the most
popular.
However, there are a number of other SBCs available that vary in size, capacity, performance, price and expandability. Some of them are
x86-based, which means they’re basically very small PCs on which you can install Windows 10; others utilise different makes of processor or
microprocessors and offer a varied number of operating systems that will work on them, such as Android or Linux.
While the Raspberry Pi is the SBC that offers some of the best opportunities in terms of project work, and flexibility, it’s certainly not the only
one of its kind. We’ve listed some of our favourite boards, that you may consider taking a look at if the Raspberry Pi isn’t fulfilling your goals.

UDOO BOLT
The Udoo brand has been active since 2013, when it launched its first SBC via
Kickstarter. These days the company is at the forefront of developing some of
the most powerful SBCs on the market; in particular, the Udoo Bolt.
The Udoo Bolt measures 120mm x 120mm and features an ultra-powerful AMD
Ryzen V1605B, quad-core/eight thread CPU, running at a maximum of 3.6GHz.
The built-in GPU is the AMD Radeon VEGA 8, and there’s support for two dual-
channel SO-DIMM DDR4 memory units to a maximum of 32GB.
There’s also a 32GB EMMC 5.0 flash module installed,
but with a pair of M.2 sockets for M.2 SSDs.
In terms of connectivity, there’s a gigabit
Ethernet port, with Bluetooth and Wi-Fi, two
USB 3.0 ports, two USB-C ports, a single USB
3.1 port, two full-sized HDMI ports and power
input via USB-PD.
The I/O for projects is Arduino Leonardo-
compatible, with 12 analogue ports, up to 23
digital ports, and a single UART, 12C and SPI.
It’s a remarkably impressive board, that can
run Windows or Linux. But, all that power and
IO comes at a price. The Bolt V8, the board we
mentioned above, comes in at $418, roughly
£300. Which is pretty expensive compared to
the Raspberry Pi; but this tiny board is more
powerful than most desktop computers.

32 Raspberry Pi Coding & Projects


Other SBCs to Use

The Banana Pi M5 is a tad more powerful than the Raspberry Pi 4,


BANANA PI and the 4GB memory option copies the more common Pi available.
Launched in 2014, the Banana Pi is a Raspberry Pi-compatible board Although you will have extra RAM if you were lucky enough to get
that has seen many releases since its initial conception. These are hold of the 8GB memory Pi. You can install both Linux or Android on
ARM-based SBCs developed in China and sold via a number of the M5, and it’s even Raspberry Pi OS compatible.
international distributors. It costs $53 – at the time of writing – which equates to around £38; so
The latest version of the Banana Pi, the BPI-M5, looks remarkably not too far from the cost of a Raspberry Pi.
similar to the Raspberry Pi 3B. It features an Amlogic S905X3 quad-core
Cortex-A55 CPU running at a decent 2GHz, together with a Mali G31
GPU. There’s 4GB of LPDDR4 memory, 16GB of eMMC flash storage on-
board and a MicroSD slot with support for up to 256GB cards.
Connectivity comes in the form of a gigabit Ethernet port, full-
sized HDMI, 3.5mm audio jack, four USB 3.0 ports and a USB-C
port for power input.
The I/O mimics the Raspberry Pi’s 40-pin GPIO, but there’s
no extra connectivity for cameras and such; as found on the
Raspberry Pi.

ROCK PI
Developed by Radxa, the Rock Pi has been a direct competitor to
the Raspberry Pi for some years now; and it’s certainly not looking
like it’s slowing down any time soon.
The latest version is the Rock Pi 4 Model C, which sports a hexa-
core CPU with a dual-core Cortex-A72 at 1.8GHz and a quad core ARE THEY WORTH IT?
Cortex-A53 at 1.4GHz together with a Mali T860MP4 GPU. Models The question of whether to use a different board other than the
A and B feature 1GB, 2GB and 4GB memory options; but the Model Raspberry Pi is purely up to you as an individual and what you’re
C comes with only 4GB of LPDDR4 memory. There’s an eMMC flash planning on using the SBC for. For most folk, who buy a Raspberry Pi
module available, in 8GB, 16GB, 32GB, 64GB and 128GB options, as for emulation or as a media server – which are the two most popular
well as a MicroSD card slot with support for 128GB cards, and an M.2 projects used by users – then they’d probably get more mileage out
connector for M.2 SSDs. of the aforementioned boards. True, the expense is considerable in
As for connectivity, there’s HDMI, gigabit Ethernet, two USB 3.0 the case of the Udoo, but it’ll do a far better job of processing than
ports, two USB 2.0 ports, 3.5mm audio jack, USB-C for power, and the Raspberry Pi will ever do.
Bluetooth and Wi-Fi.
For project work, there’s a 40-pin GPIO, as well as a MIPI CSI slot for The real argument comes down to cost. If you’re willing to pay a little
camera attachments. It’s also interesting to note that the Ethernet more for the extra performance, then the alternative SBCs will suit
port supports Power-over-Ethernet (with an additional HAT). Not bad you fine. But when you compare them to the Raspberry Pi, the Pi
for a board that measures 85mm x 54mm. does seem to come on top in terms of cost-versus-performance.
The Rock Pi Model C costs $59 or £42, and while a little more
expensive than the Raspberry Pi, it out-performs the Pi in nearly Needless to say there are countless more SBCs available. Some
every benchmark. are smaller, even more powerful than the Pi; and cost does vary
wildly from one product to the next. For most users, though – and
especially for the beginner – the best bet is to stick to the Raspberry
Pi. When your skills improve, and you have more specific projects
in mind, then look to the other boards for the specifications and
features you need.

www.pclpublications.com 33
Raspberry Pi is Good For You!

Raspbian: The Complete


Operating System
The main Raspberry Pi operating system is Raspbian, which is a Linux-based OS. While
the Pi is primarily an educational and project board, with Raspbian, it does become a fully-
functional desktop computer.

POWERING THE PI
The Raspbian OS has been powering the Raspberry Pi since its release commands). You will need to know your Linux commands in order to
back in 2013. At its core, Raspbian is a Linux operating system, based on get the most from the Lite version, so for most beginners it’s not a
the hugely popular Debian flavour of Linux. good place to start. The more advanced users will, however, be able
Mike Thompson and Peter Green created Raspbian in 2012, to work on to setup their Pi projects without the unnecessary baggage of all the
the low-performance ARM CPUs found in the early Pi models. Toward other applications clogging up the Pi’s precious system resources. It’s
the end of 2014, Raspbian was further improved to work on the then worth noting that the Lite edition can be made up to a fully functional
new model Pi, the Raspberry Pi 2; utilising the 3.18 Linux kernel while desktop version by installing all the relevant software manually.
still having Debian 7 (codenamed Wheezy) as the base. The Minimal edition is now the default version
Mid-way through 2015, Raspbian started using Debian recommended for most new Raspberry Pi users.
8 (Jessie) as the base, with kernels 4.1, 4.4, and 4.9. This version is around 1GB in size and includes
Kernel 4.9 was also used from 2017’s Raspbian the PIXEL desktop, Chromium web browser,
release, which has since used Debian 9 new hardware accelerated VLC player and
(Stretch) as the foundation distribution. Python. It does not include LibreOffice,
Scratch, Sonic Pi and many of the other
More recently, from November 2018,
tools, programs and applications that
the Raspberry Pi Foundation has split
previous versions of Raspbian included.
the Raspbian OS project into three
It’s a perfect start for most users and
separate distributions. Although these
those who are more familiar with
are essentially the same core operating
the workings of Raspbian and Linux
system, those available now are a Lite,
can easily add more apps later, as
Minimal and Full desktop set of images.
they require.
One of the primary reasons for the three-
way split is due to the overall size of the The Full desktop version is 1.8GB in size
continually improving Raspbian. In its early (at the time of writing) and as you imagine,
years, the Raspbian desktop image size contains pretty much everything you can
was a little under 1GB. This image contained squeeze into Raspbian. You get the PIXEL
everything the Pi user of the time needed to get desktop, LibreOffice, VLC, browser, games,
their projects up and running, as well as enjoying programming resources and much more.
third-party applications such as LibreOffice. Slowly, So, which version should you download and use on your
as the Pi itself evolved, the Raspbian image increased. These Pi? Normally, as recommended by the Raspberry Pi Foundation,
days the image weighs in at around 1.8GB and it’s likely to continue most new Pi users are best opting for the Minimal desktop; but that
to expand over the coming years as new software is improved on and depends greatly on what your plans are for using your Raspberry Pi.
added, alongside changing hardware. However, the three-way split We recommend new users begin with the Full desktop version, as this
addresses the issue of an ever-expanding OS image, while still enabling is the version that gives you the complete Pi experience along with all
the user to get the most from their Raspberry Pi. the associated software; even if you only use a small percentage of it.
The Lite version image comes in at roughly 350MB in size. While In fact, this entire book was written using the Full desktop version on a
it may seem like a logical choice to opt for the Lite version, it’s not Raspberry Pi 3 Model B+.
recommended for every user. The Lite version basically installs without As you learn more about the Raspberry Pi, Raspbian and Linux and
any of the software you expect from the previous versions of Raspbian; begin to form your Pi into a working project, you can easily downgrade
it doesn’t even come with the graphical desktop. This makes it an the version of Raspbian to reflect your use. One day, you may even opt
incredibly streamlined and efficient version of the OS that’s ideal for for the Lite, command line only version, occasionally connecting to it
those who run headless Pi servers (a Pi without a monitor, keyboard or remotely and issuing a few commands. As with most things Pi-related,
mouse attached, that the user remotely connects to in order to input it’s purely up to you.

34 Raspberry Pi Coding & Projects


Raspbian: The Complete Operating System

The Minimal installation is the


newly recommended version
for Pi users.

The Lite version doesn’t even


have a graphical desktop; it’s
command line only.

The Full desktop version


contains all the software you’ll
need for a complete OS.

We recommend beginners try the Full desktop


version first, then downgrade when they know
more about the Pi and its OS.

www.pclpublications.com 35
Raspberry Pi is Good For You!

Which Pi is Right for Me?


With several models of Raspberry Pi available to purchase, you can be forgiven for any
confusion over which model you should buy. So, to help save you time and money, let’s see
which Pi is best for your needs.

THE POWER OF PI
With many different versions across four generations of models, the Raspberry Pi is certainly a busy little board. But while each Pi offers
something slightly different, for the newcomer it’s a confusing medley of hardware specifications and model numbers. Which, Pi, then is best
for you?
Naturally, that questions depends greatly on what it is you want to do with your Raspberry Pi. If you have a particular project in mind, such
as a home media centre server, then you’d probably opt for the more powerful and hardware-capable model of Raspberry Pi. If you want to
setup a wireless security camera project, using the Raspberry Pi as the core hardware, then perhaps the Pi Zero W would be a better fit. To
begin with, let’s have a brief look at the models available.

FIRST GENERATION: SECOND GENERATION:


Although now quite old, in computing terms, the first generation There are two Pi 2, second generation models available: the
Raspberry Pi models are still available to purchase. These are the Model B and the Model B version 1.2. Although, you may be hard
Raspberry Pi 1 Model A+ and Pi 1 Model B+. pressed to find an original Pi 2 Model B (without the 1.2 version),
The Pi 1 Model A+ was released in November 2014, and replaced the so we will solely refer to the Pi 2 Model B as the 1.2 version that
original Model A. It features the now standard 40-pin GPIO, Micro SD was released mid-2016 instead.
Card, lower power consumption, and better audio circuitry. It’s also a The Pi 2 Model B offered the user a more powerful Pi experience.
smaller package than the original Pi, while having a 700MHz processor With 1GB of memory, an upgraded 900MHz quad-core ARM
and 512MB of memory. Cortex-A7 processor, and an improved HDMI port. As with the
While a worthy Pi, it does lack the built-in networking of its newer previous first generation Model B, this version also comes with a
model counterparts; both Ethernet and Wi-Fi. The processor is built-in 100Mb Ethernet port and four 2.0 USB port hub.
somewhat lacking in the performance department, which can be an Overall, this is a better choice of Raspberry Pi over the first
important factor if you are thinking of using this model for any serious generation models. The extra processing power, even though it’s
CPU-related projects. In short, it’s probably worth avoiding the Pi 1 only 200MHz, does make a difference, alongside the extra 512MB
Model A+. of memory, too. If you find one that’s significantly cheaper than a
The Pi 1 Model B+ is a far more capable design than its sibling more recent Pi, then it’s worth considering.
Model A+. Released in July 2014, the Pi 1 Model B+ boasts
built-in 100Mb Ethernet and four USB 2.0 ports.
It does, however, still feature the same
lacklustre processor as the Pi 1 Model
A+, but it’s extra USB and Ethernet
ports make up for any lack in available
hardware.
The first generation models are
decent enough, providing
you’re doing some low-
level project with them.
Although you can pick
them up from a variety
of online stores slightly
cheaper than the
current models, they
probably aren’t worth
the savings.

36 Raspberry Pi Coding & Projects


Which Pi is Right for Me?

THIRD GENERATION: FOURTH GENERATION: ZEROS:


The third generation Pi models are Introduced on 24th June 2019, the IIn between the first and second generation
significantly more capable than the previous, Raspberry Pi 4 Model B is a significant Raspberry Pi models, the foundation launched
but they may cost slightly more than the leap in terms of Pi performance, and the Pi Zero and Zero W.
second generation model. However, you do hardware specifications. It was also one The Raspberry Pi Zero was a significant
get more Pi for your money. of the quickest models, aside from the release, as the extremely popular Pi was
The first third generation model to be released original Pi, to sell out. now even smaller. Measuring at just 65 x
was the Pi 3 Model B, in February 2016. A With a new 1.5GHz, 64-bit, quad-core 30 x 5mm, the Zero still managed to pack
newer quad core 1.2GHz Broadcom BCM2837 ARM Cortex-A72 processor and a in a single core 1GHz processor, 512MB
64-Bit processor, 1GB of memory, and a 4-pole choice of either 2GB, 4GB or 8GB of memory, a mini-HDMI port, micro USB
stereo output and composite video port meant memory versions, the Pi 4 is one-step port, 40-pin GPIO and a micro-SD card
that this was the power-Pi to have. It’s still a closer to becoming a true desktop slot. However, it lacked wireless and other
very good model to use, and can do most of computer. In addition, the Pi 4 was networking capabilities, so you would need to
the tasks its younger sibling, the Pi 3 Model B+ launched with the startling decision to factor in a USB hub and network hardware.
can do. include dual-monitor support, in the The Raspberry Pi Zero W, on the other
The second of the third generation models form of a pair of two micro-HDMI ports. hand, is a far better choice. The processor
released was the upgrade to the Model B, the You’ll also find a pair of USB 3.0 ports, and memory are the same, as are the other
Pi 3 Model B+, released in March 2018. With an Bluetooth 5.0, and a GPU that’s capable hardware items, but, as the W indicates, this
impressive 1.4GHz quad core processor, 1GB of handing 4K resolutions and OpenGL model comes with wireless networking built-
of faster LPDDR2 memory, dual frequency ES 3.0 graphics. in. With a 2.4GHz single-band Wi-Fi module
built-in Wi-Fi and a gigabit Ethernet port, the Pi In short, the Pi 4 is the most powerful as well as Bluetooth 4.1, the Pi Zero W is an
3 Model B+ is the most powerful Raspberry Pi of the current Raspberry Pi models. impressive slim bit of hardware.
to date, and will be capable of running all your However, the different memory While the Pi Zeros may sound like a logical
projects without any problems. versions have an increased cost. The choice, considering their far smaller footprint,
The newest member of the third generation 1GB version costs £34, 4GB is £54, and they do lack the performance power of
Pi models is the replacement for the second the 8GB version will set you back £74. the newer third generation models. We’d
generation A+. Released in November 2018, Remember to also factor in one or two recommend you opt for a Pi Zero W over the
the Pi 3 Model A+ enjoys the same processor micro-HDMI cables with your order. older Pi Zero, as networking is available out of
as the more powerful Pi 3 Model B+, but has the box.
half the available memory, at 512MB. It also In conclusion, the Pi 4 Model B is the main
loses the Ethernet port, and three of the USB Raspberry Pi worth considering if you want
ports, but it does boast dual band Wi-Fi, and a The Pi 3 Model A+ the full Pi experience; use it for programming,
far smaller footprint than previous models. was released in gaming, projects, connectivity and so on. The
Out of the third generation models, the ones November 2018 and Pi 3 Model A+ can be used for projects that
to look out for are the Model B+ and Model greatly improves over require more power, but where a smaller size is
the previous Model A.
A+. The B+ will give you a more powerful Pi needed. And the Pi Zero W for projects where
experience, but it costs slightly more. Whereas a much smaller footprint and lower power
the Model A+ is much smaller, but lacks the draw are needed, and CPU performance isn’t
extra memory and additional USB ports. too important

Of the Pi models available,


The Raspberry Pi 3 Model we’d recommend the Pi 4
B+ is one of the best Pi Model B, Pi 3 Model B+
models available. and Pi Zero W.

The Raspberry Pi Zero W, with


built-in Wi-Fi and Bluetooth, is
a great project Pi.

www.pclpublications.com 37
Raspberry Pi is Good For You!

Raspberry Pi in Numbers
The Raspberry Pi was one of the most successful launches of a
computer in decades. With the perfect mix of hardware, cost,
connectivity, and development, plus a good, stable Linux OS
to back it up, the Pi has proved itself to be a near-perfect
educational platform. Here’s some facts and figures for our
favourite flavour of Pi.

3.14159265358979...
There are
over
2,500
Raspberry Pi
Certified
Educators
It’s estimated
that over
There’s a
Raspberry in 250,000
Antarctica, young people
where it’s every week are
as cold as learning how to
-42C (-45F) code with a Pi

The Pi 4 is between It is estimated that


three to four times there are over 50,000
more powerful than code clubs across
the Pi 3 Model B+ the world using the
Raspberry Pi

During the
eruption of the
Kilauea volcano
in Hawaii in It was originally
2018, a Raspberry going to be called
Pi was used as a Raspberry Py, as it
seismometer was only designed
to run Python
Sources: The Raspberry Pi Foundation, The Guardian, readwrite.com, Popular Mechanics, CNN, BBC.

38 Raspberry Pi Coding & Projects


Raspberry Pi in Numbers

It was Pi Zeros are used


originally as small cameras,
designed placed on the
for school backs of Green
children Sea Turtles, to
to learn monitor habitation
electronics
and coding

February 2019
marked the point
where the
25 millionth
Raspberry Pi
was sold

In 2017 two There are


Pi’s went several
onboard the ISS Raspberry Pi’s
and ran code in Borneo’s
developed by Rainforests,
school children monitoring
biodiversity

The The two most used


Pi 4 is Pi projects are
powerful retro emulation and
enough as a media centre
to run
Windows 10
as a Thin
Client Stacked end
to end, all
the Raspberry
Pi’s would
It is estimated that be taller
there are over 50,000 than the
code clubs across Empire State
the world using the Building
Raspberry Pi.

www.pclpublications.com 39
Raspberry Pi is Good For You!

Kit You’ll Need


and How to Set it Up
The Raspberry Pi is as bare bones as a computer can get. You get a motherboard, but not
much else. So you’ll need a few extras to get it up and running but they’re things you’re likely
to have or at least find it easy to get your hands on.

ASK AROUND
The kit list required to set up a Raspberry Pi is pretty basic: keyboard, mouse, HDMI monitor, SD Card and an optional case. Many of these
items you’ll already have, but don’t rush out and buy those you don’t. Ask around to see if anybody you know has spares.

The most important thing you need is an SD Card. You’ll need a HDMI cable to connect your
STEP 1 STEP 3
These are the storage cards commonly found in digital Raspberry Pi to a monitor or television set; these
cameras. All modern Raspberry Pi boards, including the Raspberry Pi 3 cables are used with modern televisions and video game
and Pi Zero, use Micro SD cards but the older boards may use a larger consoles, so you shouldn’t find it too hard to pick up a spare. If
SD Card. you own a Pi Zero, or you’ve got a Pi 4, you’ll need a micro-HDMI
cable in order to connect to a monitor or TV.

The SD Card plugs into the SD Card socket. On the You’ll want to connect your Raspberry Pi to the
STEP 2 STEP 4
Raspberry Pi 4, 3, and Pi Zero, you push the card in Internet. The Raspberry Pi 4 and Pi 3 Model B+, have
and pull it out. On some older models, you push the SD Card in again built in wireless networking and Ethernet. The Model A+ and
to eject it. All SD Cards have a notch on one corner that ensures it Raspberry Pi 2 include an Ethernet socket, but the Pi Zero and older
only goes in one way round. Unless you bought a card with NOOBS boards will require either an Ethernet adaptor or a Wi-Fi dongle to
preinstalled, you’ll need to install the software on it first. get online.

40 Raspberry Pi Coding & Projects


Kit You’ll Need and How to Set it Up

Both the Pi 4 and 3 come with four USB sockets but if


STEP 5
you own a Pi Zero, you may need to purchase a USB GETTING EVERYTHING CONNECTED
Hub. These connect into the USB socket, and provide four (or more)
USB connections. Typically, you need to connect a keyboard and a Now that you’ve got all the basics you’ll need to get everything
mouse, so at least two USB ports are required. set up. If you haven’t installed the NOOBS files on your SD Card,
then it’s best to do that first (see the next few pages).

Connect your Raspberry Pi to the monitor using the


STEP 1
HDMI cable. Now attach the keyboard and mouse
to separate USB ports. If your Raspberry Pi only has one USB port,
connect the mouse and keyboard to the USB hub and attach it.

Now, if required, connect the Ethernet cable to the


STEP 2
Raspberry Pi. Connect the other end of the cable
directly into your modem/router or into a network socket.

Two things that should be easy to find are a USB


STEP 6
Keyboard and USB Mouse. We routinely prefer USB
devices that plug directly into the Raspberry Pi, but devices with
wireless dongles generally work just as well. Only the Raspberry Pi 4
and 3 Model B+ come with Bluetooth as standard, so you’re best bet
is to opt for USB, if possible.

Finally connect a Micro USB cable to the power


STEP 3
supply and attach the other end to a 5V USB power
adapter. This is the type used to power most modern smartphones,
so you should be able to source a spare. Press the On button to
power up your Raspberry Pi.

You can also choose to house your


Raspberry Pi in one of many enclosures
like the official one pictured here.

Consider a case to hold your Raspberry Pi


STEP 4
together. Raspberry now makes an official case
that you can use to hold all the components and protect it from
knocks and drops.

www.pclpublications.com 41
Raspberry Pi is Good For You!

Set Up Raspberry Pi
Using a Mac
You should install NOOBS (New Out Of Box Software) on your SD Card before you go
any further. This feature looks at how to format an SD Card and copy the software
using an Apple Mac computer.

GETTING TO KNOW NOOBS


The easiest way to get up and running is to use NOOBS, a software program created by the Raspberry Pi Foundation. You can buy a NOOBS
SD Card from Raspberry Pi but it’s easy to make your own with an old unused SD Card (8GB recommended).

We’re going to use a utility called SD Card Formatter 5 Make sure the card is present in the Select Card area;
STEP 1 STEP 3
to erase the SD Card with correct formatting. You can you should only have one SD Card inserted into your
download this app from https://www.sdcard.org/downloads/ Mac. Open SDFormatter and choose the Overwrite Format option to
formatter_4/. Click Download SD Formatter for Mac and Accept. Click ensure that all the old data is removed from the card. Enter a name for
the SDFormatter.pkg file in your Downloads folder and follow the the card in the Name field to help you identify it; although this isn’t
instructions to install the app. necessary for the installation process.

Use an SD Card of at least 8GB capacity to install the Click the Format button when you are ready to wipe
STEP 2 STEP 4
operating system on your Raspberry Pi. The card the card. There are other ways to format SD Cards in
needs to be formatted, which will erase all the data on it, so make macOS (in particular Disk Utility) but the advantage of SD Card
sure you have copied any files from it you want to save. Insert the formatter is that it wipes SD Cards with the correct FAT32 format and
SD Card into your Mac, either directly into the SD Card slot or with doesn’t affect the protected partition. It can take a while to format the
an SD Card adaptor. SD Card, but the progress bar will show you how the process is going.

42 Raspberry Pi Coding & Projects


Set Up Raspberry Pi Using a Mac

When SD Card formatter has finished formatting the Now it’s time to download the NOOBS software from
STEP 5 STEP 6
SD Card it will be mounted so you can access it. By the Raspberry Pi website. Open Safari and enter
default mounted volumes appear as an icon on the desktop. If not www.raspberrypi.org/downloads/ into the Smart Search Field. Scroll
open a new Finder window and check for it under Devices. Check that down to find the NOOBS section (not NOOBS LITE) and click
the SD Card is accessible and click Close in SDFormatter. Download Zip. A zip file containing the NOOBS files will be placed in
your Downloads folder.

COPY THE SOFTWARE


Transfer the NOOBS files to your SD Card to continue the setup process.

Open the Downloads folder and click on the NOOBS Wait for all of the files to be copied from your
STEP 1 STEP 3
zip file to unzip it. A NOOBS folder should appear in Downloads folder to the SD Card. After the files have
your downloads; it will be marked with the version number you finished copying open the SD Card and check that all of the files are in
downloaded from the Raspberry Pi Downloads page. Click on the the root. You should see “bootcode.bin” and “BUILD-DATA” files, and a
folder to open it and view all the files contained inside. “defaults” folder among other files.

Press Command-A to select all the files inside the Make sure you eject the SD Card properly. Do not just
STEP 2 STEP 4
NOOBS folder. Now drag and drop all the files from remove it from the Mac. Instead, drag the SD Card
the NOOBS folder to the SD Card. This will copy all of these files to the icon to the Trash to eject it from your system. Or open a new Finder
root (the base) of the SD Card. Make sure you copy the files and not window and locate the SD Card under Devices, click the small Eject
the NOOBS folder containing them. icon next to it. Now remove the SD Card from your Mac. It is ready to
be inserted into your Raspberry Pi.

www.pclpublications.com 43
Raspberry Pi is Good For You!

Set Up Raspberry Pi Using


a Windows PC
It’s easy to set up your Raspberry Pi with a Windows PC by downloading and copying
NOOBS. This installs a selection of OS’s onto the Raspberry Pi. So let’s format your SD Card
and install NOOBS using a Windows PC.

SETTING UP WITH NOOBS


NOOBS (New Out Of Box Software) is a program used to make setting up a Raspberry Pi simple. You can buy SD Cards with NOOBS
preinstalled, but here we’ll look at how to format your SD Card and install NOOBS using a Windows computer.

We’re going to use a utility called SD Card Formatter The Drive letter will be automatically assigned
STEP 1 STEP 3
to erase the SD Card with correct formatting. You can depending on the drive(s) in your PC. Click Refresh if it
download this app from https://www.sdcard.org/downloads/ can’t find your SD Card. Ensure the Quick Format option is selected.
formatter/eula_windows/index.html. Click the Accept button to start Enter a name in the Volume Label field to make it easier to identify the
the download of the latest version of the software. Extract the card (we used “SD Card”).
software, and double-click the executable to install and run the app.

We’re going to use an 8GB SD Card to install the Click the Format button and Yes when you are ready to
STEP 2 STEP 4
operating system on our Raspberry Pi. The card needs to wipe the card. There are other ways to format SD
be formatted, which will erase all the data on it, so make sure you have Cards in Windows, but the advantage of SD Card formatter is that it
copied any files from it you want to save. Insert the SD Card into your PC, wipes SD Cards with the correct FAT32 format, and doesn’t affect the
either directly into the SD Card slot or using an SD Card adaptor. protected partition. Click OK again, when the format is complete.

44 Raspberry Pi Coding & Projects


Set Up Raspberry Pi Using a Windows PC

Click Exit to close down the SDFormatter program. Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
Click Start > File Explorer and choose the SD Card Raspberry Pi website. Open a web browser and enter
in the sidebar. The drive should be empty, but we will copy the https://www.raspberrypi.org/downloads/noobs/ into the URL field.
files to it in the next steps. For now just make sure that you can Scroll down to find the NOOBS section (not NOOBS LITE) and click
access the empty root of the SD Card. Download Zip and Save. A zip file containing the NOOBS files is copied to
your Downloads folder. Click Open Folder when it is done.

COPY THE SOFTWARE


Continue making your SD card by copying the files across.

A NOOBS folder should appear in your downloads. It Wait for all of the files to be copied from your
STEP 1 STEP 3
will be marked with the version number that you Downloads folder to the SD Card. The files that are
downloaded from the Raspberry Pi Downloads web site. Double- copied will install an operating system of your choice on the Raspberry
click the NOOBS zip file in your Downloads folder to view the Pi when you first boot it up. It is important that the files are copied to
contents. These are the files you need to copy to the root (base) of the root (base) of the SD Card and are not inside another folder such
your SD Card. as the NOOBS folder.

Click Extract All to expand the zipped file and extract Click Start > File Explorer and choose “SD CARD (F:)” in
STEP 2 STEP 4
its contents. Click Browse in the Select a Destination the sidebar to display the contents. It should now
and Extract Files folder and choose “SD Card(F:)” in the Select a contain all the files NOOBS needs to setup an operating system on
Destination window. Click Select Folder and Extract. The files will now your Raspberry Pi. Check that you can see a Defaults folder, bootcode
be copied directly from the zip file to your SD Card. and BUILD-DATA files along with the other files shown here. Remove
the SD Card from your Windows PC. It’s now ready to be inserted into
the Raspberry Pi.

www.pclpublications.com 45
Raspberry Pi is Good For You!

The Raspberry Pi Desktop:


What You Will Need
Did you know that there is a way in which you can run the full Raspbian OS desktop without
even needing a Raspberry Pi? The Raspberry Pi Desktop edition is a fully working, Debian-
based installation of Raspbian that can run on a standard PC.
In 2016, the Raspberry Pi Foundation started work on an x86 Since then, the Raspberry Pi Desktop, or as it’s correctly called:
version of its popular Raspbian operating system. By the end of Debian Stretch with Raspberry Pi Desktop, has followed the same
the following year, there was a link on the Downloads page and release path as its Pi-based sibling. However, there are some
non-Pi owners could now install and use Raspbian in almost the differences you need to be aware of prior to throwing your Pi
exact same way as if they were in front of a Raspberry Pi. away and opting for this version instead.

The Raspberry Pi Desktop (x86 version) allows you to view the


same desktop and pre-installed software as the Full Desktop
version available for the Raspberry Pi. You can install it on any
decent PC, or laptop, one that’s at least six or seven years old
would be perfect and as a PC that age usually struggles with
the latest version of Windows 10, you can now install Raspbian
instead of boxing that old kit and resigning it to a life of
gathering dust in the loft.

The major difference is that this version has been compiled to run
on x86 processors, that’s Intel and AMD PC processors. Whereas,
the version of Raspbian that you will find on a Raspberry Pi has been
compiled and created exclusively for ARM processors; the type of Another caveat worth mentioning is that you won’t have access to
CPU a Raspberry Pi uses. These CPUs use a different architecture the 40-pin GPIO that the Raspberry Pi features, as this isn’t a standard
to that of an Intel or AMD CPU, so the software required to run on piece of hardware on a normal PC. There is, however, a way around
one won’t run on the other unless the developer has specifically this. If you own a Raspberry Pi Zero (either with or without the W),
made either an x86 or ARM version. In short, if you’ve found a piece then you’re able to connect the Zero to a spare USB port on the PC,
of software that you enjoy using on your Raspberry Pi, you won’t via the Zero’s micro USB port and the Raspberry Pi Desktop OS will
be able to use it on the Raspberry Pi Desktop x86 version – UNLESS, recognise the Zero as extended hardware and allow you access to the
there’s a dedicated x86 version of the software. Zero’s 40-pin GPIO, which, you have to admit, is pretty clever stuff.

46 Raspberry Pi Coding & Projects


The Raspberry Pi Desktop: What You Will Need

WHAT YOU WILL NEED


Here’s a list of items needed if you want to test out the latest version of the Debian Stretch with Raspberry Pi Desktop OS on your PC.

Naturally you’ll need the Raspberry Pi Desktop OS, just The best method of transferring the ISO to a PC for
THE OS USB STICK
as you would with Raspbian or the Pi. Open a browser installation is to use a combination of a tool such as
and download the ISO file that contains the OS from: https://www. Rufus (found at: https://rufus.ie/en_IE.html), which is a piece of
raspberrypi.org/downloads/raspberry-pi-desktop/. software that can create a bootable USB driver from an ISO file and, at
least, an 8GB USB stick.

An older desktop PC or laptop is an ideal Although not strictly a necessity, a


A COMPUTER RASPBERRY PI ZERO
candidate for running the Raspberry Pi Desktop spare Raspberry Pi Zero will allow you
OS. While you can easily use the latest PC/laptop, it’s a bit overkill for to access the 40-pin GPIO from within the Raspberry Pi Desktop OS. If,
this particular operating system. however, you don’t have a spare Zero, it’s not a problem as there’s still
plenty you can do with Raspbian on a PC.

HOW TO SET UP THE


RASPBERRY PI DESKTOP
Setting up the Raspberry Pi Desktop version on a PC or
laptop is very simple, and follows roughly the same method
as the previous Mac and Windows setups for the Pi. Begin by
downloading the ISO image from https://www.raspberrypi.
org/downloads/raspberry-pi-desktop/, then download Rufus
from https://rufus.ie/en_IE.html. Insert an 8GB USB stick
and run Rufus, then follow the on-screen instructions to
locate the downloaded Desktop ISO. Once the image has
transferred to the USB stick, remove it from the computer
and insert it in the spare laptop/PC. Select Boot from USB
from your system’s BIOS/UEFI then follow the instructions to
use and install the Raspberry Pi Desktop OS.

www.pclpublications.com 47
Raspberry Pi is Good For You!

Debian Buster with


Raspberry Pi Desktop
You can be forgiven for thinking that a version of the Pi OS that isn’t on a Raspberry Pi is
somehow lacking, and therefore a bit pointless in its use. However, there’s a lot that you can
do with the Debian Buster with Raspberry Pi Desktop version.

10 THINGS TO DO WITH X86 RASPBERRY PI OS


There’s just as much you can do with this version of Raspberry Pi OS as with the dedicated Pi version. Here’s ten great projects, and things to
do with Debian Buster with Raspberry Pi Desktop.

This version of Raspbian apes the Full Desktop version As the x86 version of Raspbian follows the Full
CODING FULL DESKTOP
for the Raspberry Pi, so that means it comes with all Desktop Pi version, there’s an entire office
the necessary programming languages out of the box. Learn Python, suite pre-installed. That means you can use that old laptop or PC as a
C++, use the HAT emulator, and even learn JAVA. It’s all there under fully functional desktop replacement for Windows or macOS.
the Programming menu option. LibreOffice is also Microsoft Office compatible.

Hook up a Pi Zero without an SD installed, and As with most modern operating systems,
HARDWARE WEB BROWSING
select GPIO Expansion Board from the options, you can also browse the Internet exactly the
and you will be able to talk to the Zero’s 40-pin GPIO via the likes of same as you would with the likes of Windows 10 or the latest macOS.
Python or Scratch. By doing so, you’ll have all the benefits of a As this is a Linux-based OS, there’s also an added element of security,
Raspberry Pi, with the power of your laptop. as Windows-targeted viruses won’t affect it.

48 Raspberry Pi Coding & Projects


Debian Buster with Raspberry Pi Desktop

LINUX X86-BASED SOFTWARE As this is a Debian based


MINECRAFT The Raspberry Pi, even the Pi 3 Model B+, isn’t
version of Linux, you can the most powerful computing device available.
naturally install any of the tens of millions of Linux x86-based software Your older laptop is probably significantly more powerful, and as
currently available. Remember though, only software that has both an such, you will be able to play the likes of Minecraft without too
ARM and an x86 version will work on both the Pi version and this much trouble.
version of Raspberry Pi OS.

The Recommended If retro gaming is more to your tastes, then


RECOMMENDED SOFTWARE RETRO GAMING
Software option is also Debian has a huge number of retro
available with the version of the PI OS. This tool allows you to pick and emulators available covering consoles and home computers. You will
choose which of the Pi-favoured software you can add or remove. need legal ROMs, however, to play the games, but these are widely
Simply tick the box next to the name of the app. available from reputable sites.

It’s easy to use SSH from within the Raspberry Pi GAMING Of course, there’s also an equally large selection of
SSH
Configuration tool. Select the Enabled option, then use modern gaming available for Debian; most of which
a client such PuTTY to SSH into the OS. Here we’ve enabled SSH will run perfectly well under the Pi OS in an x86 environment. You will
and have connected from another Windows PC, using PuTTY as need to Google what’s available, and try out a few examples, the list is
the SSH client. simply too big to mention.

www.pclpublications.com 49
Explore Raspbian

50 Raspberry Pi Coding & Projects


Explore Raspbian INDEX

Explore Raspbian
The Raspbian operating system is a Linux distribution that comes pre-packed
with a fantastic collection of programs and apps to help you get the most
from your Pi. Raspbian enables the Raspberry Pi to become a fully functioning
desktop computer, and with it, you can code in the latest version of Python,
C++ and more. There’s even an entire office suite for free, called LibreOffice,
that’s Microsoft Office compatible if you install the Full Desktop version
of Raspbian.
Raspbian allows you to connect to your existing home network, surf the
Internet, play music and videos, edit documents, send emails and much
more. With a few simple tricks you can easily install more free software that,
for instance enables you to edit images and videos or even connect to other
computers and control the desktop.
This section of the book introduces many of the skills, tricks and hacks you
need to take full command of the Raspberry Pi. Skills that you will use time
and time again when creating your own Pi projects.

52 Take a Tour of PIXEL 62 Get More from the Terminal App


54 Exploring the Command Line 64 Using the File Manager
56 Setting Up a Static IP Address 66 Edit Images with GIMP
58 Connecting to the Pi Remotely
60 Using APT to Install and Remove
Programs

52 Take
PIXEL
a Tour of
66 Edit Images
with GIMP
The desktop Use GIMP to create
environment for your icons, images and
Raspberry Pi. works of art for
your programs.

www.pclpublications.com 51
Explore Raspbian

Take a Tour of PIXEL


PIXEL is the desktop environment for your Raspberry Pi. It’s built on top of Raspbian, the core
OS, which is itself designed around the Linux distribution - Debian, specifically, Debian Buster.
PIXEL is fine-tuned to run on the Raspberry Pi, taking advantage of its unique hardware.

PIXEL
PIXEL stands for “Pi Improved Xwindow Environment, Lightweight”. It’s a lightning fast and energy saving desktop that looks good too. It
contains almost everything you’ll ever need to work with the Pi 4.

The PIXEL interface is a module that’s installed You’ll notice that within the Main menu,
THE DESKTOP PRODUCTIVITY
on top of the core OS. It has seen some there’s a category named Office. In here,
improvements over the years, and with the release of the Pi 4 and you’ll find a pre-installed suite of programs called LibreOffice, that are
Raspbian Buster, it now looks like this. Microsoft Office compatible; there’s a word processor, database,
drawing, presentation and spreadsheet program.

The programs that come pre-installed with FILE MANAGER To view the files stored on your Raspbian OS,
THE PROGRAMS
Raspbian are easily located by clicking on click on the File Manager icon in the
the Raspberry Pi logo in the upper left corner of the desktop. Once Application Launch Bar (the one that is shaped like a pair of files). This
there, you can select from the sub-menu categories, followed by the opens a window displaying all the files in your home directory. The
program name. Directory Tree gives quick access to common folders, such as Desktop
and Documents.

52 Raspberry Pi Coding & Projects


Take a Tour of PIXEL

It is possible to remove and add items to the It’s important that you switch off your Raspberry
MENU EDITOR SHUTDOWN
Application Menu using the Main Menu Editor. Pi safely. When you are finished with your
Choose Menu > Preferences > Main Menu Editor, then add or remove Raspberry Pi session click Menu > Shutdown. Three options appear:
ticks next to programs and sections you want to include\exclude. Use Shutdown, Reboot, and Logout. Click Shutdown. Always wait for the
Move Up and Move Down to rearrange items in the Menu. screen to go blank before removing the USB power.

CUSTOMISE THE DESKTOP


As with any other operating system desktop, you’re able to customise the Raspberry Pi’s PIXEL interface, making it more personal and more you.

YOUR PIXEL Choose Menu > Preferences > Appearance The second tab in the Appearance Settings window
MENU BAR
Settings to open the Appearance Settings allows you to adjust the menu bar that runs along
window. There are four sections: Desktop, Menu Bar, System, and the top of the desktop. You can change its size, colour, and even its
Defaults. You can use these to adjust the various options for your location from the top to the bottom of the screen.
system, such as colours, layout, and so on.

The most common change is that of The System tab in the Appearance Settings window will
DESKTOP WALLPAPER FONTS
the desktop wallpaper, or desktop enable you to change the core system font, as well as the
background. The default is called ‘Temple’, however, by clicking on mouse cursor size. There are numerous fonts to choose from and, if
temple.jpg in the Picture section of the Appearance Settings, you you want, you can even install your own.
have other images available. Naturally, you can opt for your own.

www.pclpublications.com 53
Explore Raspbian

Exploring the
Command Line
If you’ve grown up with Windows or the Mac OS then you might never have encountered the
command line. This part of the operating system sits beneath the desktop and is used to control a
computer using text commands. You’ll need to get familiar with it to use your Raspberry Pi.

USING TERMINAL
Despite its graphical PIXEL interface, Raspbian is a Linux operating system and this means you’ll spend a lot of time working with text
commands. Using the command line is an important part of learning to use a Raspberry Pi computer.

By default the Raspberry Pi boots directly into the Another way to switch to a command line environment
STEP 1 STEP 3
PIXEL interface. Here you use a visual metaphor, files, is to press Control+Alt and F2. This gets rid of the
buttons and so on, to make changes to your computer. The command desktop completely and you see just a black screen with text. This is
line is where you control a computer by entering text commands. Click known as a virtual environment and you’re now in tty2 (“tty” is a
Terminal in the Menu bar to view the console. throwback to teletext writers). You’ll need to enter your login name
(“pi” by default) and password (“raspberry” by default).

You can enter commands into the Terminal to make There are six different virtual environments
STEP 2 STEP 4
changes to the computer. This works alongside the available. Press Control-Alt-F3 to switch to the third,
PIXEL interface. Enter: mkdir Desktop/testfolder and press and Control-Alt-F4 to go to the fourth, and so on. You’ll need to log
return. Notice a new folder appears below the Trash on the desktop. on to each one in the first instance but can then jump back and forth
Drag it to trash to get rid of it. You can use the Terminal and PIXEL between them.
environments alongside each other.

54 Raspberry Pi Coding & Projects


Exploring the Command Line

Press Control-Alt-F1 to return to the PIXEL interface. Some users prefer to use just the command line.
STEP 5 STEP 6
One thing to realise is that PIXEL is just a program Open Menu > Preferences > Raspberry Pi
running on top of the tty1 session. Open Terminal and enter: pkill configuration and choose To CLI and click OK and Yes. The
lxsession. Ouch, there goes your desktop. Don’t worry, enter: Raspberry Pi will now boot into the command line interface. Enter:
startx to get it back again. Most of the time you just enter startx to get back to PIXEL, open Raspberry Pi Configuration and
commands into the Terminal window on top of the PIXEL environment. choose To Desktop to go back to normal.

USING SUDO
Discovering the power of the super user.

One of the most important command line instructions The first time you enter sudo you’ll be given a warning
STEP 1 STEP 3
to know is sudo. This command stands for “substitute message. Commands to make, edit and delete files
user do”, sometimes incorrectly called “super user do” and allows you prefaced with sudo can be used to change any file on the system.
to run a command as another user. Typically this is the root user Sometimes with powerful, or disastrous, results. Be careful. Enter your
account, which has more access privileges than your user account. password and press return.

When you start a command with sudo it is run as Be especially careful of any set of commands that use
STEP 2 STEP 4
the root user and is often used when changing sudo –i. This takes you to root mode, where every
files outside of your user account, such as installing new command is run as sudo. Your name (normally “pi”) is replaced with
programs. When you enter sudo you will be asked to enter your “”root”. Root mode is generally considered a bad place to be, so enter
user password. Enter: sudo -v and press enter. exit to get out of it as soon as possible.

www.pclpublications.com 55
Explore Raspbian

Setting Up a Static
IP Address
Setting up a static IP address comes with several advantages, the main one being you’ll
always know what your Pi’s network address is – should you decide to operate it without
a keyboard, mouse, or monitor. It’s easy to set up too, but it’s not a critical process.

DHCP RESERVATION
Now that you’ve set up your Raspberry Pi and connected it to the network, you should take time to fix its IP address. This will make it a lot
easier for you to connect to the Raspberry Pi from a Mac or Windows computer and share files.
When you To find out what number your Raspberry Pi is using
STEP 1 STEP 3
connect click on the Terminal icon and enter: ifconfig and
your Raspberry Pi to a press Return. You should find it next to “inet addr:”. The challenge is
network, the router (or that the router assigns this number using DHCP (Dynamic Host
modem/router) assigns it a Configuration Protocol). When the Raspberry Pi is unplugged it
number, known as its IP reuses the number and your Raspberry Pi may get a different number
(Internet Protocol) address. next time.
This is a block of four digits
and the first three are
usually 192.168.0. After
that is a digit for each
electronic device.

The router typically takes the first address, so it is It’s better all-round if you can get the Raspberry Pi to
STEP 2 STEP 4
usually found at 192.168.0.1. That number is reserved use the same IP address every time you connect it to
for the router. Often you’ll find this number on your router marked the network. You do this using DHCP Reservation. This is where you
“web address”. The router then assigns similar IP address numbers to tell your router to remember the Raspberry Pi address, and only use
the other devices you own as they are added to the network, so that address from now on. Start by opening the Chromium Browser
192.168.0.2 might be your computer, 192.168.0.3 your smartphone and and entering 192.168.0.1 to connect to your router’s web interface.
so on.

56 Raspberry Pi Coding & Projects


Setting Up a Static IP Address

We’re using a Virgin Broadband router but the Select the device using the check box on the right and
STEP 5 STEP 6
process is similar on most routers. Google the name scroll down to the Add Reservation section. It should
of your router and “DHCP Reservation” to find the router you’re have filled in the Device Name, MAC Address and IP Address fields. If
looking for. Enter your admin password (our default password was the Device name is “unknown” change it to “raspberry-pi”. Click Add
listed on the back of the router). Click Advanced Settings > DHCP Reservation to ensure it always uses that IP Address. Click Apply to
Reservation. In the DHCP Settings section you will find all of the enforce the changes.
devices connected to your network. Scroll down and find the one with
the same IP Address listed in Step 3.

MANAGING YOUR DHCP DEVICES


Now that you have set up a DHCP Reservation, you need to understand how to manage the different devices that may need to use it and
connect to the IP.

Now that you have set up your Raspberry Pi with a Your Raspberry Pi will still have the same IP Address
STEP 1 STEP 3
DHCP Reservation it will always connect to the router but it isn’t guaranteed to keep it. Restart your
using that IP Address. You can check this at any time by entering: Raspberry Pi by entering: sudo shutdown -r now into a Terminal
ifconfig into terminal. The router always knows that it is your window. When it has restarted enter: ifconfig and you’ll find you still
Raspberry Pi by checking its MAC address. This is the set of six use the same IP Address. Over time the router will use other slots for
hexadecimal numbers next to “HWaddr” in ifconfig. new devices until it reaches its maximum (255 by default). Then it will
recycle disconnected devices.

If you decide to free up that IP Address so other Setting up DHCP Reservation is good practice because
STEP 2 STEP 4
devices can use it, you can remove it from the router. it ensures you Raspberry Pi is always going to use the
Open the router web interface (192.178.0.1) and click Advanced same IP Address. It’s also a good idea to write it down or use a label
Settings > DHCP Reservation. Scroll down to the IP Lease Table to find printer to create a label for the Raspberry Pi. You will need this
the Raspberry Pi. Select the check-box next to it and click Apply number to connect to the Raspberry Pi via SSH, VPN or FPT
and Yes. (techniques we will use throughout this book).

www.pclpublications.com 57
Explore Raspbian

Connecting to the
Pi Remotely
A ‘Headless’ Pi – a Raspberry Pi that doesn’t have a keyboard, mouse, or monitor
connected – can easily be controlled remotely using VNC (Virtual Network Computing).
Everything is built-in to the Pi, so it’s an easy process to set up and use.

REMOTE CONTROL
The Raspberry Pi is easy to set up and use in projects around the home and, surprisingly, many of these projects don’t need a keyboard,
mouse or a monitor; these are known as Headless devices. VNC lets you control a Headless Pi from another computer.

You will first need to ensure that your Pi is connected In the upper right corner of the menu bar you’ll notice
STEP 1 STEP 3
to a keyboard, mouse and monitor, and is connected a VNC icon (next to the Bluetooth icon). This is the
to your Wi-Fi router, before you attempt to connect to it remotely. built-in VNC server, click the icon in the menu bar once to open the
Start by clicking on the Raspberry Pi menu, then scroll down to VNC Server window.
Preferences > Raspberry Pi Configuration.

With the Raspberry Pi Configuration window open, Make a note of the IP Address of the Raspberry Pi as
STEP 2 STEP 4
click on the Interfaces tab, and ensure that the VNC detailed in the left-hand section of the VNC Server
option is Enabled. Click on the radio button next to Enabled to window; our example is 192.168.1.244. Now click on the three
activate, then click on the OK button to close the window. horizontal lines in the top right of the VNC Server window. From the
sub-menu that appears, click on the Options entry. This will open a
new window pop-up.

58 Raspberry Pi Coding & Projects


Connecting to the Pi Remotely

With the Security option highlighted on the left, While still in the Options window, click on
STEP 5 STEP 6
ensure that the Encryption option, to the right, is set Connections in the left hand pane. In the right hand
to Prefer On, and that Authentication is VNC Password. This may ask pane, ensure that the Allow Direct VNC Connections Over TCP is
you to enter a password, which you will use when connecting ticked, and that the Port is set to 5900. It usually is, but sometimes it
remotely from another computer. Enter a password you’ll remember. can be unticked if an update to software has been applied.

REMOTE VIEWING
The Pi-side of things has now been set up. Just remember the Pi’s IP address, and get to your PC or Mac for this next part.
Reboot the Pi, then disconnect the keyboard, mouse In the new pop-up window, enter the password you
STEP 1 STEP 3
and monitor; but keep the power connected. From created through the Raspberry Pi’s VNC Server
your PC or Mac, open a browser and navigate to: https://www.realvnc. options page. You can choose to Remember Password if you want, but
com/en/connect/download/viewer/. Choose your operating system if the computer you’re using is shared, you can always opt to leave the
and click the Download VNC Viewer app. option unticked. Click OK when ready.

Follow the on-screen instruction to install VNC Viewer You may be asked to confirm connection to a remote
STEP 2 STEP 4
on your system, when it’s finished, launch the app and computer, click Continue to make the connection. You
choose whether you want to send anonymous data. In the main VNC are now connected remotely to your Raspberry Pi. As long as the Pi is
Viewer window, enter the IP Address of the Raspberry Pi; ours was powered up, and has access to the Wi-Fi signal of the router, then you
192.168.1.244. Hit Enter when you’ve typed in the IP address. can place it anywhere and get access without using a mouse,
keyboard, or monitor.

www.pclpublications.com 59
Explore Raspbian

Using APT to Install


and Remove Programs
When you start to get serious with your Raspberry Pi, you’ll need to install software that is available
for Linux, but not part of the Pi Store. These programs are installed from the command line using a
service called APT. Learning how to use APT is a vital part of using your Pi.

ADVANCED PACKAGING TOOL


Add / Remove Software is great for finding and installing software but most of the time you manage apps on a Raspberry Pi using a program
called APT (Advanced Packaging Tool) using the apt command.

To manage the apps on your Raspberry Pi you’ll need The command used to add new software to your
STEP 1 STEP 3
to use a tool included with Raspbian called APT Raspberry Pi is apt install followed by the name
(Advanced Packaging Tool). APT is a command line tool so you need to of the package you want. However, because apt adds (or removes)
either start your Raspberry Pi in the command line or click on the files outside of your home directory you need to preface apt with the
Terminal icon. word sudo. Almost all of the time you will need to type sudo apt
when using this tool.

The command used to control packages in Raspbian is Beginning a command with “sudo” runs the command
STEP 2 STEP 4
apt Type apt into the terminal and press Return to as a super user, “super” meaning the one above your
get a description of what the app does. The instructions tell us that Pi account, rather than one with super-hero properties. However, if it
the “most frequently used commands are update and install”. You may helps you to think of it that way that’s fine. So to install a new program
also hear about “apt-get” which is an older version of the same tool. It you type: sudo apt install followed by the name of the app
works in much the same way. you want.

60 Raspberry Pi Coding & Projects


Using APT to Install and Remove Programs

You’re going to install a chess game called You can use apt-cache to search for apps you can
STEP 5 STEP 6
Dreamchess. Enter: sudo apt install install and remove. Enter: apt-cache pkgnames to
dreamchess and press Return. Descriptive text will run up the screen. view all the packages available. Typing apt-cache pkgnames |
You may see “Do you want to continue [Y/n]?” Enter: y and press less enables you to view a page at a time (press any key to scroll).
Return to install the application. You’ll find it by choosing: You can use apt-cache search to find packages, enter: apt-cache
Menu > Games > Dreamchess. search pong to view a list of Pong games you can install.

MORE APT COMMANDS


The apt command is also used to list, and delete, any apps you have installed.

Sometimes you will try to install an app only to get an Packages are uninstalled from your Raspberry Pi
STEP 1 STEP 3
error that the file cannot be found. In this case you using the remove command. Enter: sudo apt
need to update apt so it has the latest links. Enter: sudo apt remove dreamchess to start deleting the chess game that you
update. This doesn’t update the apps you’ve installed, it just gets a installed. An alert saying “Do you want to continue [Y/n]?| appears,
newer listing of apps. To update your apps to the latest versions enter: enter: y and press Return to delete the program.
sudo apt upgrade. You’ll often find both commands rolled into
one: sudo apt update && sudo apt upgrade.

To view the packages you’ve installed you use a Uninstalled packages using apt doesn’t remove all
STEP 2 STEP 4
different command called dpkg. Enter: dpkg of the files. Some are left in case you decide to
--get-selections | grep -v deinstall to view all of the reinstall the program later. To completely remove a package from
packages on your Raspberry Pi. Place | less after it to view one your Raspberry Pi use the purge command. Enter: sudo apt
page at a time. Or dpkg --get-selections | grep -v purge dreamchess to remove all of the supporting files. You
deinstall > ~/Desktop/packages.txt to save the list as a can also use sudo apt clean to tidy up your packages and free
text file on your desktop. up some drive space.

www.pclpublications.com 61
Explore Raspbian

Get More from the


Terminal App
Terminal is an app in Raspbian that enables you to access the command line and issue text
commands to your Pi. You’ll spend a lot of time in Terminal, so it’s a great idea to get to know
the app and set it up to work your way.

CUSTOM TERMINAL
The Terminal gives you access to the command line, where the real power of the Linux OS lies. Getting used to the Terminal is key to
mastering the Pi and your projects.

Start Terminal by clicking the Terminal icon in the Naming tabs makes them much easier to recognise.
STEP 1 STEP 3
Application Launch Bar. You can also start Terminal Choose Tabs > Name Tab and enter a name for the tab
by pressing Control-Alt-T or choosing Menu > Accessories > such as “Home” or “Downloads”. Click OK to set the name. You can
Terminal. Terminal emulates the old style video terminals from quickly switch between tabs using Control-Page Up and Control-Page
before desktop interfaces; so by default it displays bright (mostly Down and rearrange them using the Tabs Move Tab Left / Move Tab
green) on a black background. Right options.

The first thing most people overlook is the ability Choose Edit > Preferences to personalise the look and
STEP 2 STEP 4
to run multiple terminals at once in different tabs. feel of LXTerminal. One of the best tricks is to click
Choose File > New Tab (Shift-Control-T) to create a new tab. Background and drag the Opacity slider to the half-way point. This
Navigating multiple directories simultaneously can be a challenge enables you to view through the terminal background and see the
in Terminal and tabs makes it that much easier. windows below. You can also personalise the colour of the background.

62 Raspberry Pi Coding & Projects


Get More from the Terminal App

While still in Preferences click the Display tab. Here you If you prefer a more minimalist approach try moving the
STEP 5 STEP 6
can adjust the Tab panel positions, placing them on the Tabs to the bottom and selecting the Hide scroll bar,
Left makes them more prominent. You can also adjust the scroll-back Hide menu bar and Hide Close button options. When combined with a
line count. This is the number of lines you can scroll up with using the low opacity background this makes for a subtle terminal window. You
mouse, not the history accessed by the Up and Down arrows. can still access menu settings using a right-click on the mouse.

CONNECT USING SSH


Use a different computer to control your Raspberry Pi.

If you have your Raspberry Pi on the same network Switch back to Terminal on your Mac or Linux
STEP 1 STEP 3
as a Mac or Linux-based computer, you can control it machine and enter: ssh [email protected]
using the Terminal program on that computer. We’re going to use (using your own IP address). The “pi” bit is the name of the default
Terminal in macOS here but the process is the same on a Linux user account, so if you have changed that it needs to match your
machine. Open the Terminal app on your computer. user account on the Raspberry Pi. You’ll be asked for a password.
This is the password that you use to log in to the Raspberry Pi (not
your Mac or Linux computer).

Enter: ifconfig into the Terminal app on your You are now logged in to your Raspberry Pi and
STEP 2 STEP 4
Raspberry Pi. This will let you know which IP address can enter commands directly into the Terminal on
it is using. Look for the four blocks of digits following “inet addr:’. your Mac or Linux computer. Unlike remote networking you
They should begin with 192.168.0 followed by a three-digit number. don’t see the commands being entered on the screen of the
Ours is 192.168.0.179. You need to use that number in Terminal on Raspberry Pi, you are accessing the computer from behind the
your Mac to connect. scenes. Many people prefer to set up the Raspberry Pi so they
can control it from a more powerful computer. Enter: exit to
close the connection.

www.pclpublications.com 63
Explore Raspbian

Using the File Manager


Because you’ll be creating programs on your Raspberry Pi, you’ll need to know more about
the file system than you would on other computers. One vital tool to become familiar with is
the File Manager. This is used to find, move and remove files from your Raspberry Pi.

VIEWING AND MOVING FILES


You can move, manage and delete files using the Command Line but like all modern operating systems Raspbian has a program to help you
manage your files. Discover how to use the File Manager app.

Raspbian includes a great file management program In the left-hand part of the File Manager sits the Side
STEP 1 STEP 3
called “File Manager PCManFM” or just “File Manager” Pane. By default this displays the Directory Tree,
for short. Click on the FileManager PCManFM icon in the Launch Bar or which is another way of navigating the folders on your hard drive.
choose Menu > Accessories > File Manager. Alternatively click the Side Pane menu and choose Places. Now the
Side Pane displays common locations such as Home Folder, Desktop,
Rubbish Bin (also known as the Wastebasket), Applications and your
SD Card.

File Manager displays the folders in your Home folder You can create a new folder in the current location by
STEP 2 STEP 4
(this should match your user name, ‘Pi’ by default). By choosing File > Create New > Folder or press
default you should have Desktop, Documents, Downloads, Music, Shift-Control-N. Enter a name for the folder and click OK. Files and
Pictures, Public, python_games, Scratch and folders. Double-click any folders can be dragged on top of one another to move them around.
folder to open it and view its contents. Click the Parent Folder icon or You can also drag files to the folders in the Side Pane, which is an easy
press Alt-Up Arrow to head back up. way to move them back up the folder tree.

64 Raspberry Pi Coding & Projects


Using File the Manager

Double-click a file in File Manager to open it with the Drag items you no longer want to the Wastebasket
STEP 5 STEP 6
default app. You can also right-click a file to view to delete them or right-click and choose Move to
compatible applications in Raspbian. Pick an application from the list Trash. To empty the wastebasket and permanently delete the
provided to open it. Click Properties and use the Open with menu to unwanted files double click Wastebasket to open it. Now right-click
automatically open that type of file with that app in future. the black space in File Manager and choose Empty Rubbish Bin. Click
Yes in the alert window and the files will be removed.

ADVANCED FILE MANAGER TRICKS


These handy tricks and tips make File Manager more powerful.

As you start to move files around you will find It’s worth taking time to explore the View menu in File
STEP 1 STEP 3
navigating between the same folders tiresome. It is Manager. Here you’ll find a Show Hidden option, which
possible to open locations in File Manager as tabs, so you can quickly enables you to view hidden files, as well as Sort Files. You can also
jump back and forth. Click the Create new tab for this folder icon, just adjust the Folder View Mode as well as Toolbar, Path Bar, Side Pane
below the File menu, and the current folder opens as a tab. Click the and Status Bar.
tabs to jump between locations.

To view the properties of a file right-click and choose There are times when you will want to move files but
STEP 2 STEP 4
Properties. Here you can view information about the find you can’t because you don’t have root (sudo)
File Type and the Open With application. More importantly, if you access in File Manager. If you want to open File Manager with root
click Permissions you can view the permissions associated with that mode choose Menu > Run and enter: gksu pcmanfm. File Manager
file. The concept of file permissions, especially the ‘Execute’ setting, will open and display root and boot() folders. Be careful when running
becomes increasingly important as you become more advanced in File Manager in root mode, and close it when you are finished.
using your Raspberry Pi.

www.pclpublications.com 65
Explore Raspbian

Edit Images with GIMP


The name may be funny, but this image editing app is incredibly serious. The Raspberry Pi is
perfectly adept at photo editing, and you can use GIMP to create icons, images and works of
art for your programs.

GET TO KNOW GIMP


Your Raspberry Pi can display images with its built-in Image View app but for any image editing you’ll need GIMP (GNU Image Manipulation
Program). GIMP is a powerful software package for photo editing and is a great tool to install on your Raspberry Pi.

Open terminal and enter: sudo apt install gimp Images can be opened in GIMP using File > Open or by
STEP 1 STEP 3
to download and install the GIMP package. An alert right-clicking on files in File Manager and choosing
will appear saying: “after this operation, 117 MB of additional disk GNU Image Manipulation Program. You can open multiple images at
space will be used. Do you want to continue [Y/n]?” Enter: y and press once in GIMP but each opens inside a different window. Choose
Return. GIMP will now be installed in Raspbian. GIMP is a lot larger Window > Single Window Mode to gather them together. Click on the
than most programs you’ll install, so the installation takes longer. tabs at the top of the screen to switch from one image to another.

When the installation has completed you will find You can perform powerful edits in GIMP but we
STEP 2 STEP 4
GIMP under Menu > Graphics > GNU Image don’t have space to go over them all. Probably the
Manipulation Program. It has a more detailed interface than many most useful you’ll find is Colours > Levels. This window enables you
Linux programs with two boxes, Tool Options and Brushes offering a to adjust the tonal range and colour balance of an image. Drag the
range of image editing options. Users of software like Adobe left and right handles in slightly and slide the centre handle to the
Photoshop will feel right at home and it’s ideal for image editing. right to improve the contrast of an image.

66 Raspberry Pi Coding & Projects


Edit Images with GIMP

To crop an image click the Rectangle Select Tool and There are a huge range of image effects and filters
STEP 5 STEP 6
drag a square on the image. Choose Image > Crop you can add to images using GIMP. Far more than
To Selection to remove the unwanted parts of the image. Use the we have room to cover here. Try Filters > Artistic > Cartoon to give
Image > Scale Image and Image > Canvas Size options to adjust the your image a black outline or Filters > Artistic > Oilify to simulate a
image to specific sizes. Cropping and resizing images is a vital painted artwork. Take a look at www.gimp.org/tutorials for
technique to know when working on websites. creative inspiration.

EXPORTING IMAGES
Save your images for use in a website.

Images are saved using File > Save As in the xcf format The Export Image as JPEG window appears, displaying
STEP 1 STEP 3
(Experimental Computing Facility). This is GIMP’s a Quality slider. The Quality range is from 0 (very
native format so should only be used to save files you want to view poor) to 100 (perfect). While you might be tempted to set the quality
and work on in GIMP. at 100, reducing it slightly will create much smaller files. Smaller files
ensure that your web page loads much more quickly. You can typically
reduce the Quality to 80 and get a much smaller file with little
discernible difference.

If you want to save files for use in projects, such as Right-click a JPEG image in the File Manager and
STEP 2 STEP 4
websites, use File > Export. Click the File Type option choose Open With. Expand Internet and choose
and choose a file type; typically you will use JPEG for web images. Chromium Web Browser and OK. This enables you to see how it will
Choose a Name and location and click Export. appear when you add it to your website. You can also view images
more quickly by right clicking and choosing Image Viewer. You can use
Save File As in Image Viewer to quickly change the image format.

www.pclpublications.com 67
Python on the Pi

68 Raspberry Pi Coding & Projects


Python on the Pi INDEX

Python on the Pi
Being able to code is part of making not just the Raspberry Pi, but all the
connected devices that can access the Internet, do what you want them
to. The Raspberry Pi is a perfect coding base that comes pre-installed
with the latest version of one of the world’s most popular programming
languages, Python.
Python is a powerful yet easy to understand programming language that
enables you to do anything, from displaying simple messages on the screen
to producing action-packed arcade games. In this section of the book, you will
learn how to get Python working and how to code your first Python program.
Learning the tricks, hacks and fixes of Python will enable you to create
something brilliant that can be shared with everyone who owns a Raspberry Pi.

70 Starting Python for the First Time 84 User input


72 Your First Code 86 Creating Functions
74 Saving and Executing Your Code 88 Conditions and Loops
76 Executing Code from the 90 Python Modules
Command Line 92 Python Errors
78 Numbers and Expressions 94 Python Graphics
80 Using Comments 96 Glossary of Terms
82 Working with Variables

78 Numbers and
Expressions
88 Conditions
and Loops
See just how powerful Conditions and loops
Python is as a calculator. are what make a
program interesting.

www.pclpublications.com 69
Python on the Pi

Starting Python for the


First Time
If you’re using the new Raspberry Pi, together with its latest release of Raspbian, then you will
need to manually install the Python IDLE. This is due to the Pi team removing the core Python
IDLE in favour of replacing it with their own coding text editor.

STARTING PYTHON
For those using the Pi 4 and new Raspbian, drop into a Terminal and enter: sudo apt-get install idle3. Older versions of Raspbian
already have the official Python IDLE pre-installed.

With the Raspbian desktop loaded, click on the Menu For example, in the Shell enter: 2+2
STEP 1 STEP 3
button followed by Programming > Python 3 (IDLE). After pressing Enter, the next line will display the
This will open the Python 3 Shell. Windows and Mac users can find the answer: 4. Basically, Python has taken the ‘code’ and produced the
Python 3 IDLE Shell from within the Windows Start button menu and relevant output.
via Finder.

The Shell is where you can enter code and see the The Python Shell acts very much like a calculator, since
STEP 2 STEP 4
responses and output of code you’ve programmed code is basically a series of mathematical interactions
into Python. This is a kind of sandbox, where you’re able to try out with the system. Integers, which are the infinite sequence of whole
some simple code and processes. numbers can easily be added, subtracted, multiplied and so on.

70 Raspberry Pi Coding & Projects


Starting Python for the First Time

While that’s very interesting, it’s not particularly The Python IDLE is a configurable environment. If you
STEP 5 STEP 8
exciting. Instead, try this: don’t like the way the colours are represented, then
print(“Hello everyone!”) you can always change them via Options > Configure IDLE and clicking
Just enter it into the IDLE as you’ve done in the previous steps. on the Highlighting tab. However, we don’t recommend that as you
won’t be seeing the same as our screenshots.

This is a little more like it, since you’ve just produced Just like most programs available, regardless of the
STEP 6 STEP 9
your first bit of code. The Print command is fairly operating system, there are numerous shortcut keys
self-explanatory, it prints things. Python 3 requires the brackets as available. We don’t have room for them all here but within the Options
well as quote marks in order to output content to the screen, in this > Configure IDLE and under the Keys tab, you can see a list of the
case the Hello everyone! bit. current bindings.

You may have noticed the colour coding within the The Python IDLE is a powerful interface, and one
STEP 7 STEP 10
Python IDLE. The colours represent different that’s actually been written in Python using one of
elements of Python code. They are: the available GUI toolkits. If you want to know the many ins and outs
Black – Data and Variables Blue – User Functions for the Shell, we recommend you take a few moments to view www.
Green – Strings Dark Red – Comments docs.python.org/3/library/idle.html, which details many of the
Purple – Functions Light Red – Error Messages IDLE’s features.
Orange – Commands

www.pclpublications.com 71
Python on the Pi

Your First Code


Essentially, you’ve already written your first piece of code with the ‘print(“Hello everyone!”)’
function from the previous tutorial. However, let’s expand that and look at entering your code
and playing around with some other Python examples.

PLAYING WITH PYTHON


With most languages, computer or human, it’s all about remembering and applying the right words to the right situation. You’re not born
knowing these words, so you need to learn them.

If you’ve closed Python 3 IDLE, reopen it in whichever You can see that instead of the number 4, the output
STEP 1 STEP 3
operating system version you prefer. In the Shell, is the 2+2 you asked to be printed to the screen. The
enter the familiar following: quotation marks are defining what’s being outputted to the IDLE
print(“Hello”) Shell; to print the total of 2+2 you need to remove the quotes:
print(2+2)

Just as predicted, the word Hello appears in the Shell You can continue as such, printing 2+2, 464+2343 and
STEP 2 STEP 4
as blue text, indicating output from a string. It’s fairly so on to the Shell. An easier way is to use a variable,
straightforward and doesn’t require too much explanation. Now try: which is something we will cover in more depth later. For now, enter:
print(“2+2”) a=2
b=2

72 Raspberry Pi Coding & Projects


Your First Code

What you have done here is assign the letters a and b Now let’s add a surname:
STEP 5 STEP 8
two values: 2 and 2. These are now variables, which surname=”Hayward”
can be called upon by Python to output, add, subtract, divide and so print(surname)
on for as long as their numbers stay the same. Try this: You now have two variables containing a first name and a surname
print(a) and you can print them independently.
print(b)

The output of the last step displays the current values If we were to apply the same routine as before, using
STEP 6 STEP 9
of both a and b individually, as you’ve asked them to the + symbol, the name wouldn’t appear correctly in
be printed separately. If you want to add them up, you can use the the output in the Shell. Try it:
following: print(name+surname)
print(a+b) You need a space between the two, defining them as two separate
This code simply takes the values of a and b, adds them together and values and not something you mathematically play around with.
outputs the result.

You can play around with different kinds of variables In Python 3 you can separate the two variables with a
STEP 7 STEP 10
and the Print function. For example, you could assign space using a comma:
variables for someone’s name: print(name, surname)
name=”David” Alternatively, you can add the space ourselves:
print(name) print(name+” “+surname)
The use of the comma is much neater, as you can see. Congratulations,
you’ve just taken your first steps into the wide world of Python.

www.pclpublications.com 73
Python on the Pi

Saving and Executing


Your Code
While working in the IDLE Shell is perfectly fine for small code snippets, it’s not designed for
entering longer program listings. In this section you’re going to be introduced to the IDLE
Editor, where you will be working from now on.

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the IDLE Editor will
allow you to save and execute your Python code.

First, open the Python IDLE Shell and when it’s up, You can see that the same colour coding is in place in
STEP 1 STEP 3
click on File > New File. This will open a new window the IDLE Editor as it is in the Shell, enabling you to
with Untitled as its name. This is the Python IDLE Editor and within it better understand what’s going on with your code. However, to
you can enter the code needed to create your future programs. execute the code you need to first save it. Press F5 and you get a
Save…Check box open.

The IDLE Editor is, for all intents and purposes, a Click on the OK button in the Save box and select a
STEP 2 STEP 4
simple text editor with Python features, colour coding destination where you’ll save all your Python code.
and so on; much in the same vein as Sublime. You enter code as you The destination can be a dedicated folder called Python or you can
would within the Shell, so taking an example from the previous just dump it wherever you like. Remember to keep a tidy drive though,
tutorial, enter: to help you out in the future.
print(“Hello everyone!”)

74 Raspberry Pi Coding & Projects


Saving and Executing Your Code

Enter a name for your code, ‘print hello’ for example, Let’s extend the code and enter a few examples from
STEP 5 STEP 8
and click on the Save button. Once the Python code is the previous tutorial:
saved it’s executed and the output will be detailed in the IDLE Shell. In a=2
this case, the words ‘Hello everyone!’. b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5 now you’ll be asked to save the file, again, as it’s been
modified from before.

This is how the vast majority of your Python code will If you click the OK button, the file will be overwritten
STEP 6 STEP 9
be conducted. Enter it into the Editor, hit F5, save the with the new code entries, and executed, with the
code and look at the output in the Shell. Sometimes things will differ, output in the Shell. It’s not a problem with just these few lines but if
depending on whether you’ve requested a separate window, but you were to edit a larger file, overwriting can become an issue.
essentially that’s the process. It’s the process we will use throughout Instead, use File > Save As from within the Editor to create a backup.
this book, unless otherwise stated.

If you open the file location of the saved Python code, Now create a new file. Close the Editor, and open a
STEP 7 STEP 10
you can see that it ends in a .py extension. This is the new instance (File > New File from the Shell). Enter
default Python file name. Any code you create will be whatever.py and the following and save it as hello.py:
any code downloaded from the many internet Python resource sites a=”Python”
will be .py. Just ensure that the code is written for Python 3. b=”is”
c=”cool!”
print(a, b, c)
You will use this code in the next tutorial.

www.pclpublications.com 75
Python on the Pi

Executing Code from


the Command Line
Although we’re working from the GUI IDLE throughout this book, it’s worth taking a look at
Python’s command line handling. We already know there’s a command line version of Python
but it’s also used to execute code.

COMMAND THE CODE


Using the code we created in the previous tutorial, the one we named hello.py, let’s see how you can run code that was made in the GUI at
the command line level.

Python, in Linux, comes with two possible ways of Now you’re at the command line we can start Python.
STEP 1 STEP 3
executing code via the command line. One of the ways For Python 3 you need to enter the command python3
is with Python 2, whilst the other uses the Python 3 libraries and so on. and press Enter. This will put you into the command line version of the
First though, drop into the command line or Terminal on your Shell, with the familiar three right-facing arrows as the cursor (>>>).
operating system.

Just as before, From here you’re able to enter the code you’ve looked
STEP 2 STEP 4
we’re using a at previously, such as:
Raspberry Pi: Windows users a=2
will need to click the Start print(a)
button and search for CMD, You can see that it works exactly the same.
then click the Command Line
returned search; and macOS
users can get access to their
command line by clicking Go >
Utilities > Terminal.

76 Raspberry Pi Coding & Projects


Executing Code from the Command Line

Now enter: exit() to leave the command line The result of running Python 3 code from the Python
STEP 5 STEP 8
Python session and return you back to the 2 command line is quite obvious. Whilst it doesn’t
command prompt. Enter the folder where you saved the code error out in any way, due to the differences between the way Python
from the previous tutorial and list the available files within; 3 handles the Print command over Python 2, the result isn’t as we
hopefully you should see the hello.py file. expected. Using Sublime for the moment, open the hello.py file.

From within the same folder as the code you’re going Since Sublime Text isn’t available for the Raspberry Pi,
STEP 6 STEP 9
to run, enter the following into the command line: you’re going to temporarily leave the Pi for the
python3 hello.py moment and use Sublime as an example that you don’t necessarily
This will execute the code we created, which to remind you is: need to use the Python IDLE. With the hello.py file open, alter it to
a=”Python” include the following:
b=”is” name=input(“What is your name? “)
c=”cool!” print(“Hello,”, name)
print(a, b, c)

Naturally, since this is Python 3 code, using the syntax Save the hello.py file and drop back to the command
STEP 7 STEP 10
and layout that’s unique to Python 3, it only works line. Now execute the newly saved code with:
when you use the python3 command. If you like, try the same with python3 hello.py
Python 2 by entering: The result will be the original Python is cool! statement, together with
python hello.py the added input command asking you for your name, and displaying it
in the command window.

www.pclpublications.com 77
Python on the Pi

Numbers and Expressions


We’ve seen some basic mathematical expressions with Python, simple addition and the like.
Let’s expand on that now and see just how powerful Python is as a calculator. You can work
within the IDLE Shell or in the Editor, whichever you like.

IT’S ALL MATHS, MAN


You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths
is the driving force behind the code.

Open up the GUI version of Python 3, as mentioned You can use all the usual mathematical operations:
STEP 1 STEP 3
you can use either the Shell or the Editor. For the divide, multiply, brackets and so on. Practise with a
time being, you’re going to use the Shell just to warm our maths few, for example:
muscle, which we believe is a small gland located at the back of the 1/2
brain (or not). 6/2
2+2*3
(1+2)+(3*4)

In the Shell enter the following: You’ve no doubt noticed, division produces a decimal
STEP 2 STEP 4
2+2 number. In Python these are called floats, or floating
54356+34553245 point arithmetic. However, if you need an integer as opposed to a
99867344*27344484221 decimal answer, then you can use a double slash:
You can see that Python can handle some quite large numbers. 1//2
6//2
And so on.

78 Raspberry Pi Coding & Projects


Numbers and Expressions

You can also use an operation to see the remainder This will be displayed as ‘0b11’, converting the integer
STEP 5 STEP 8
left over from division. For example: 10/3 into binary and adding the prefix 0b to the front. If
Will display 3.333333333, which is of course 3.3-recurring. you want to remove the 0b prefix, then you can use:
If you now enter: 10%3 format(3, ‘b’)
This will display 1, which is the remainder left over from dividing 10 The Format command converts a value, the number 3, to a formatted
by 3. representation as controlled by the format specification, the ‘b’ part.

Next up we have the power operator, or


STEP 6
exponentiation if you want to be technical. To work
out the power of something you can use a double multiplication
symbol or double-star on the keyboard:
2**3
10**10
Essentially, it’s 2x2x2 but we’re sure you already know the basics
behind maths operators. This is how you would work it out in Python.

A Boolean Expression is a logical statement that will


STEP 9
either be true or false. We can use these to compare
data and test to see if it’s equal to, less than or greater than. Try this in
a New File:
a = 6
b = 7
print(1, a == 6)
print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
Numbers and expressions don’t stop there. Python
STEP 7 print(8, not (a == 7 and b == 6))
has numerous built-in functions to work out sets of
print(9, not a == 7 and b == 6)
numbers, absolute values, complex numbers and a host of
mathematical expressions and Pythagorean tongue-twisters. For Execute the code from Step 9, and you can see a series
example, to convert a number to binary, use: STEP 10
of True or False statements, depending on the result
bin(3) of the two defining values: 6 and 7. It’s an extension of what you’ve
looked at, and an important part of programming.

www.pclpublications.com 79
Python on the Pi

Using Comments
When writing your code, the flow, what each variable does, how the overall program will
operate and so on is all inside your head. Another programmer could follow the code line by
line but over time, it can become difficult to read.

#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the programmer
comments on what it’s supposed to do, for example. It’s just good practise.

Start by creating a new instance of the IDLE Editor Resave the code and execute it. You can see that the
STEP 1 STEP 3
(File > New File) and create a simple variable and print output in the IDLE Shell is still the same as before,
command: despite the extra lines being added. Simply put, the hash symbol (#)
a=10 denotes a line of text the programmer can insert to inform them, and
print(“The value of A is,”, a) others, of what’s going on without the user being aware.
Save the file and execute the code.

Running the code will return the line: The value of A is, Let’s assume that the variable A that we’ve created is
STEP 2 STEP 4
10 into the IDLE Shell window, which is what we the number of lives in a game. Every time the player
expected. Now, add some of the types of comments you’d normally dies, the value is decreased by 1. The programmer could insert a
see within code: routine along the lines of:
# Set the start value of A to 10 a=a-1
a=10 print(“You’ve just lost a life!”)
# Print the current value of A print(“You now have”, a, “lives left!”)
print(“The value of A is,”, a)

80 Raspberry Pi Coding & Projects


Using Comments

While we know that the variable A is lives, and that the Inline comments are comments that follow a section
STEP 5 STEP 8
player has just lost one, a casual viewer or someone of code. Take our examples from above, instead of
checking the code may not know. Imagine for a moment that the code inserting the code on a separate line, we could use:
is twenty thousand lines long, instead of just our seven. You can see a=10 # Set the start value of A to 10
how handy comments are. print(“The value of A is,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)

Essentially, the new code together with comments The comment, the hash symbol, can also be used to
STEP 6 STEP 9
could look like: comment out sections of code you don’t want to be
# Set the start value of A to 10 executed in your program. For instance, if you wanted to remove the
a=10 first print statement, you would use:
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-1
# Inform player, and display current value of A
(lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)

You can use comments in different ways. For example, You also use three single quotes to comment out a
STEP 7 STEP 10
Block Comments are a large section of text that Block Comment or multi-line section of comments.
details what’s going on in the code, such as telling the code reader Place them before and after the areas you want to comment for them
what variables you’re planning on using: to work:
# This is the best game ever, and has been developed ’’’
by a crack squad of Python experts This is the best game ever, and has been developed
# who haven’t slept or washed in weeks. Despite by a crack squad of Python experts who haven’t slept
being very smelly, the code at least or washed in weeks. Despite being very smelly, the
# works really well. code at least works really well.
’’’

www.pclpublications.com 81
Python on the Pi

Working with Variables


Variables are where all the action takes place in your code. A Variable can be anything, from the
number of lives in a game, that changes as you progress through the game, to a person’s name,
age and address. Variables can be static or alter depending on what you want the code to do.

VARIOUS VARIABLES
You’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, open Python 3 or close down the previous IDLE Shell to
clear up any old code.

In some programming languages you’re required to use You’ve seen previously that variables can be
STEP 1 STEP 3
a dollar sign to denote a string, which is a variable made concatenated using the plus symbol between the
up of multiple characters, such as a name of a person. In Python this variable names. In our example we can use: print (name + “: “ +
isn’t necessary. For example, in the Shell enter: name=”David Hayward” title). The middle part between the quotations allows us to add a
(or use your own name, unless you’re also called David Hayward). colon and a space, as variables are connected without spaces, so we
need to add them manually.

You can check the type of variable in use by You can also combine variables within another
STEP 2 STEP 4
issuing the type () command, placing the name of the variable. For example, to combine both name and title
variable inside the brackets. In our example, this would be: variables into a new variable we use:
type (name). Add a new string variable: title=”Descended from character=name + “: “ + title
Vikings”. Then output the content of the new variable as:
print (character)
Numbers are stored as different variables:
age=44
Type (age)
Which are integers, as we know.

82 Raspberry Pi Coding & Projects


Working with Variables

However, you can’t combine both strings and integer This presents a bit of a problem when you want to
STEP 5 STEP 8
type variables in the same command, as you would a set work with a number that’s been inputted by the user,
of similar variables. You need to either turn one into the other or vice as age + 10 won’t work due to being a string variable and an integer.
versa. When you do try to combine both, you get an error message: Instead, you need to enter:
print (name + age) int(age) + 10
This will TypeCast the age string into an integer that can be
worked with.

This is a process known as TypeCasting. The Python The use of TypeCasting is also important when dealing
STEP 6 STEP 9
code is: with floating point arithmetic; remember: numbers
print (character + “ is “ + str(age) + “ years that have a decimal point in them. For example, enter:
old.”) shirt=19.99
or you can use: Now enter: type(shirt) and you’ll see that Python has allocated the
print (character, “is“, age, “years old.”) number as a ‘float’, because the value contains a decimal point.
Notice again that in the last example, you don’t need the spaces
between the words in quotes as the commas treat each argument to
print separately.

Another example of TypeCasting is when you ask for


STEP 7
input from the user, such as a name. for example, enter:
age= input (“How old are you? “)
All data stored from the Input command is stored as a string variable.
When combining integers and floats Python usually
STEP 10
converts the integer to a float, but should the reverse
ever be applied it’s worth remembering that Python doesn’t return
the exact value. When converting a float to an integer, Python will
always round down to the nearest integer, called truncating; in our
case instead of 19.99 it becomes 19.

www.pclpublications.com 83
Python on the Pi

User Input
We’ve seen some basic user interaction with the code from a few of the examples earlier, so
now would be a good time to focus solely on how you would get information from the user
then store and present it.

USER FRIENDLY
The type of input you want from the user will depend greatly on the type of program you’re coding. For example, a game may ask for a
character’s name, whereas a database can ask for personal details.

If it’s not already, open the Python 3 IDLE Shell, and Now that we have the user’s name stored in a couple
STEP 1 STEP 3
start a New File in the Editor. Let’s begin with of variables we can call them up whenever we want:
something really simple, enter: print(“Welcome”, firstname, surname, “. I hope you’re
print(“Hello”) well today.”)
firstname=input(“What is your first name? “)
print(“Thanks.”)
surname=input(“And what is your surname? “)

Save and execute the code, and as you already no Run the code and you can see a slight issue, the full
STEP 2 STEP 4
doubt suspected, in the IDLE Shell the program will stop after the surname follows a blank space. To
ask for your first name, storing it as the variable firstname, followed eliminate that we can add a plus sign instead of the comma in
by your surname; also stored in its own variable (surname). the code:
print(“Welcome”, firstname, surname+“. I hope you’re
well today.”)

84 Raspberry Pi Coding & Projects


User Input

You don’t always have to include quoted text within What you’ve created here is a condition, which we will
STEP 5 STEP 8
the input command. For example, you can ask the user cover soon. In short, we’re using the input from the
their name, and have the input in the line below: user and measuring it against a condition. So, if the user enters David
print(“Hello. What’s your name?”) as their name, the guard will allow them to pass unhindered. Else, if
name=input() they enter a name other than David, the guard challenges them to
a fight.

The code from the previous step is often regarded as Just as you learned previously, any input from a user is
STEP 6 STEP 9
being a little neater than having a lengthy amount of automatically a string, so you need to apply a
text in the input command, but it’s not a rule that’s set in stone, so do TypeCast in order to turn it into something else. This creates some
as you like in these situations. Expanding on the code, try this: interesting additions to the input command. For example:
print(“Halt! Who goes there?”) # Code to calculate rate and distance
name=input() print(“Input a rate and a distance”)
rate = float(input(“Rate: “))

It’s a good start to a text adventure game, perhaps? To finalise the rate and distance code, we can add:
STEP 7 STEP 10
Now you can expand on it and use the raw input from distance = float(input(“Distance: “))
the user to flesh out the game a little: print(“Time:”, (distance / rate))
if name==”David”: Save and execute the code and enter some numbers. Using the
print(“Welcome, good sir. You may pass.”) float(input element, we’ve told Python that anything entered is a
else: floating point number rather than a string.
print(“I know you not. Prepare for battle!”)

www.pclpublications.com 85
Python on the Pi

Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle
functions. You’ve already used a few functions, such as the print command but Python
enables you to define your own functions.

FUNKY FUNCTIONS
A function is a command that you enter into Python to do something. It’s a little piece of self-contained code that takes data, works on it and
then returns the result.

It’s not just data that a function works on. They can do You can pass variables through functions in much the
STEP 1 STEP 3
all manner of useful things in Python, such as sort same manner. Let’s assume you want the number of
data, change items from one format to another and check the length letters in a person’s surname, you could use the following code (enter
or type of items. Basically, a function is a short word that’s followed by the text editor for this example):
brackets. For example, len(), list() or type(). name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in it.”)
Press F5 and save the code to execute it.

A function takes data, usually a variable, works on it Python has tens of functions built into it, far too many
STEP 2 STEP 4
depending on what the function is programmed to do to get into in the limited space available here.
and returns the end value. The data being worked on goes inside the However, to view the list of built-in functions available to Python 3,
brackets, so if you wanted to know how many letters are in the word navigate to www.docs.python.org/3/library/functions.html. These
antidisestablishmentarianism, then you’d enter: len(“antidisesta are the predefined functions, but since users have created many more,
blishmentarianism”) and the number 28 would return. they’re not the only ones available.

86 Raspberry Pi Coding & Projects


Creating Functions

Additional functions can be added to Python through To use a function from a module enter the name of
STEP 5 STEP 6
modules. Python has a vast range of modules the module followed by a full stop, then the name of
available that can cover numerous programming duties. They add the function. For instance, using the Math module, since you’ve just
functions and can be imported as and when required. For example, to imported it into Python, you can utilise the square root function. To do
use advanced mathematics functions enter: so, enter:
import math math.sqrt(16)
Once entered, you have access to all the Math module functions. You can see that the code is presented as module.function(data).

FORGING FUNCTIONS
There are many different functions you can import, created by other Python programmers, and you will undoubtedly come across some
excellent examples in the future; you can also create your own with the def command.

Choose File > New File to enter the editor, let’s create a To modify it further, delete the Hello(“David”) line, the
STEP 1 STEP 3
function called Hello, that greets a user. Enter: last line in the script and press Ctrl+S to save the new
def Hello(): script. Close the Editor and create a new file (File > New File). Enter the
print (“Hello”) following:
Hello() from Hello import Hello
Press F5 to save and run the script. You can see Hello in the Shell, type Hello(“David”)
in Hello() and it returns the new function. Press F5 to save and execute the code.

What you’ve just done is import the Hello function from


STEP 4
the saved Hello.py program and then used it to say hello
Let’s now expand the function to accept a variable, the
STEP 2 to David. This is how modules and functions work: you import the
user’s name for example. Edit your script to read:
module then use the function. Try this one, and modify it for extra credit:
def Hello(name):
def add(a, b):
print (“Hello”, name)
result = a + b
Hello(“David”)
return result
This will now accept the variable name, otherwise it prints Hello David.
In the Shell, enter: name=(“Bob”), then: Hello(name). Your
function can now pass variables through it.

www.pclpublications.com 87
Python on the Pi

Conditions and Loops


Conditions and loops are what makes a program interesting; they can be simple or rather
complex. How you use them depends greatly on what the program is trying to achieve; they
could be the number of lives left in a game or just displaying a countdown.

TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let’s start then by checking if something
is TRUE, then doing something else if it isn’t.

Let’s create a new Python program that will ask the Now you can use an if statement to check if the
STEP 1 STEP 3
user to input a word, then check it to see if it’s a word_length variable is equal to four and print a
four-letter word or not. Start with File > New File, and begin with the friendly conformation if it applies to the rule:
input variable: word=input(“Please enter a four-letter word: “)
word=input(“Please enter a four-letter word: “) word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
The double equal sign (==) means check if something is equal to
something else.

Now we can create a new variable, then use the len The colon at the end of IF tells Python that if this
STEP 2 STEP 4
function and pass the word variable through it to get statement is true do everything after the colon that’s
the total number of letters the user has just entered: indented. Next, move the cursor back to the beginning of the Editor:
word=input(“Please enter a four-letter word: “) word=input(“Please enter a four-letter word: “)
word_length=len(word) word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
else:
print (word, “is not a four-letter word.”)

88 Raspberry Pi Coding & Projects


Conditions and Loops

Press F5 and save the code to execute it. Enter a Now expand the code to include another conditions.
STEP 5 STEP 6
four-letter word in the Shell to begin with, you should Eventually, it could become quite complex. We’ve
have the returned message that it’s the word is four letters. Now press added a condition for three-letter words:
F5 again and rerun the program but this time enter a five-letter word. word=input(“Please enter a four-letter word: “)
The Shell will display that it’s not a four-letter word. word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

LOOPS
A loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same block of code
a number of times, usually with the support of a condition.

Let’s start with a simple While statement. Like IF, this The For loop is another example. For is used to loop
STEP 1 STEP 3
will check to see if something is TRUE, then run the over a range of data, usually a list stored as variables
indented code: inside square brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10: for word in words:
print (x) print (word)
x = x + 1

The difference between if and while is when while gets The For loop can also be used in the countdown
STEP 2 STEP 4
to the end of the indented code, it goes back and checks example by using the range function:
the statement is still true. In our example x is less than 10. With each for x in range (1, 10):
loop it prints the current value of x, then adds one to that value. When x print (x)
does eventually equal 10 it stops. The x=x+1 part isn’t needed here because the range function creates a
list between the first and last numbers used.

www.pclpublications.com 89
Python on the Pi

Python Modules
We’ve mentioned modules previously, (the Math module) but as modules are such a large
part of getting the most from Python, it’s worth dedicating a little more time to them. In this
instance we’re using the Windows version of Python 3.

MASTERING MODULES
Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules
available and as we’ve seen, you can even make your own.

Although good, the built-in functions within Python The result is an error in the IDLE Shell, as the Pygame
STEP 1 STEP 3
are limited. The use of modules, however, allows us to module isn’t recognised or installed in Python. To
make more sophisticated programs. As you are aware, modules are install a module we can use PIP (Pip Installs Packages). Close down the
Python scripts that are imported, such as import math. IDLE Shell and drop into a command prompt or Terminal session. At an
elevated admin command prompt, enter:
pip install pygame

Some modules, especially on the Raspberry Pi, are The PIP installation requires an elevated status due it
STEP 2 STEP 4
included by default, the Math module being a prime installing components at different locations. Windows
example. Sadly, other modules aren’t always available. A good users can search for CMD via the Start button and right-click the result
example on non-Pi platforms is the Pygame module, which contains then click Run as Administrator. Linux and Mac users can use the Sudo
many functions to help create games. Try: import pygame. command, with sudo pip install package.

90 Raspberry Pi Coding & Projects


Python Modules

Close the command prompt or Terminal and relaunch Multiple modules can be imported within your code.
STEP 5 STEP 8
the IDLE Shell. When you now enter: import To extend our example, use:
pygame, the module will be imported into the code without any import random
problems. You’ll find that most code downloaded or copied from the import math
internet will contain a module, mainstream of unique, these are for I in range(5):
usually the source of errors in execution due to them being missing. print(random.randint(1, 25))
print(math.pi)

The modules contain the extra code needed to The result is a string of random numbers followed by
STEP 6 STEP 9
achieve a certain result within your own code, as we’ve the value of Pi as pulled from the Math module using
previously experimented with. For example: the print(math.pi) function. You can also pull in certain functions from
import random a module by using the from and import commands, such as:
Brings in the code from the random number generator module. You from random import randint
can then use this module to create something like: for i in range(5):
for i in range(10): print(randint(1, 25))
print(random.randint(1, 25))

This code, when saved and executed, will display ten This helps create a more streamlined approach to
STEP 7 STEP 10
random numbers from 1 to 25. You can play around programming. You can also use import module*,
with the code to display more or less, and from a great or lesser range. which will import everything defined within the named module.
For example: However, it’s often regarded as a waste of resources but it works
import random nonetheless. Finally, modules can be imported as aliases:
for i in range(25): import math as m
print(random.randint(1, 100)) print(m.pi)
Of course, adding comments helps to tell others what’s going on.

www.pclpublications.com 91
Python on the Pi

Python Errors
It goes without saying that you’ll eventually come across an error in your code, where Python
declares it’s not able to continue due to something being missed out, wrong or simply
unknown. Being able to identify these errors makes for a good programmer.

DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to
keep looking, experimenting and testing. Eventually your code will be bug free.

Code isn’t as fluid as the written word, no matter how Thankfully Python is helpful when it comes to
STEP 1 STEP 3
good the programming language is. Python is displaying error messages. When you receive an error,
certainly easier than most languages but even it is prone to some in red text from the IDLE Shell, it will define the error itself along with
annoying bugs. The most common are typos by the user and whilst the line number where the error has occurred. Whilst in the IDLE
easy to find in simple dozen-line code, imagine having to debug Editor this is a little daunting for lots of code; text editors help by
multi-thousand line code. including line numbering.

The most common of errors is the typo, as we’ve Syntax errors are probably the second most common
STEP 2 STEP 4
mentioned. The typos are often at the command level: errors you’ll come across as a programmer. Even if the
mistyping the print command for example. However, they also occur spelling is correct, the actual command itself is wrong. In Python 3 this
when you have numerous variables, all of which have lengthy names. often occurs when Python 2 syntaxes are applied. The most annoying
The best advice is to simply go through the code and check your spelling. of these is the print function. In Python 3 we use print(“words”),
whereas Python2 uses print “words”.

92 Raspberry Pi Coding & Projects


Python Errors

Pesky brackets are also a nuisance in programming An excellent way to check your code step-by-step
STEP 5 STEP 8
errors, especially when you have something like: is to use Python Tutor’s Visualise web page, found at
print(balanced_check(input())) www.pythontutor.com/visualize.html#mode=edit. Simply paste your
Remember that for every ‘(‘ there must be an equal number of ‘)’. code into the editor and click the Visualise Execution button to run the
code line-by-line. This helps to clear bugs and any misunderstandings.

There are thousands of online Python resources, code Planning makes for good code. Whilst a little old
STEP 6 STEP 9
snippets and lengthy discussions across forums on school, it’s a good habit to plan what your code will do
how best to achieve something. Whilst 99 per cent of it is good code, before sitting down to type it out. List the variables that will be used
don’t always be lured into copying and pasting random code into your and the modules too; then write out a script for any user interaction
editor. More often than not, it won’t work and the worst part is that or outputs.
you haven’t learnt anything.

Indents are a nasty part of Python programming that a


STEP 7
lot of beginners fall foul of. Recall the If loop from the
Conditions and Loops section, where the colon means everything Purely out of interest, the word debugging in
indented following the statement is to be executed as long as it’s STEP 10
computing terms comes from Admiral Grace Hopper,
true? Missing the indent, or having too much of indent, will come back who back in the ‘40s was working on a monolithic Harvard Mark II
with an error. electromechanical computer. According to legend Hopper found a
moth stuck in a relay, thus stopping the system from working.
Removal of the moth was hence called debugging.

www.pclpublications.com 93
Python on the Pi

Python Graphics
While dealing with text on the screen, either as a game or in a program, is great, there
will come a time when a bit of graphical representation wouldn’t go amiss. Python 3 has
numerous ways in which to include graphics and they’re surprisingly powerful too.

GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on, or you can use one of the many Python modules available, to bring out some
spectacular effects.

One of the best graphical modules to begin learning The command turtle.circle(50) is what draws the circle
STEP 1 STEP 3
Python graphics is Turtle. The Turtle module is, as the on the screen, with 50 being the size. You can play
name suggests, based on the turtle robots used in many schools, that around with the sizes if you like, going up to 100, 150 and beyond; you
can be programmed to draw something on a large piece of paper on can draw an arc by entering: turtle.circle(50, 180), where the
the floor. The Turtle module can be imported with: import turtle. size is 50, but you’re telling Python to only draw 180° of the circle.

Let’s begin by drawing a simple circle. Start a New File, The last part of the circle code tells Python to keep the
STEP 2 STEP 4
then enter the following code: window where the drawing is taking place to remain
import turtle open, so the user can click to close it. Now, let’s make a square:
turtle.circle(50) import turtle
turtle.getscreen()._root.mainloop() print(“Drawing a square…”)
As usual press F5 to save the code and execute it. A new window will for t in range(4):
now open up and the ‘Turtle’ will draw a circle. turtle.forward(100)
turtle.left(90)
turtle.getscreen()._root.mainloop()
You can see that we’ve inserted a loop to draw the sides of the square.

94 Raspberry Pi Coding & Projects


Python Graphics

You can add a new line to the square code to add Now let’s get the code by importing the Pygame
STEP 5 STEP 8
some colour: module:
turtle.color(“Red”) import pygame
Then you can even change the character to an actual turtle by pygame.init()
entering: img = pygame.image.load(“RPi.png”)
turtle.shape(“turtle”) white = (255, 255, 255)
You can also use the command turtle.begin_fill(), and turtle. w = 900
end_fill() to fill in the square with the chosen colours; red outline, h = 450
yellow fill in this case. screen = pygame.display.
set_mode((w, h))
screen.fill((white))
screen.fill((white))
screen.blit(img,(0,0))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

You can see that the Turtle module can draw out some
STEP 6
pretty good shapes and become a little more complex
as you begin to master the way it works. Enter this example:
from turtle import *
color(‘red’, ‘yellow’)
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break In the previous step you imported pygame, initiated
end_fill()
STEP 9
the pygame engine and asked it to import our saved
done() Raspberry Pi logo image, saved as RPi.png. Next you defined the
It’s a different method, background colour of the window to display the image and the
but very effective. window size as per the actual image dimensions. Finally you have a
loop to close the window.

Another way in which you can display graphics is by


STEP 7
using the Pygame module. There are numerous ways
in which pygame can help you output graphics to the screen but for
now let’s look at displaying a predefined image. Start by opening a
browser and finding an image, then save it to the folder where you
Press F5 to save and execute the code and your image
save your Python code. STEP 10
will be displayed in a new window. Have a play around
with the colours, sizes and so on and take time to look up the many
functions within the Pygame module too.

www.pclpublications.com 95
Python on the Pi

Glossary of Terms
Just like most technology, Python contains many confusing words and acronyms. Here then,
for your own sanity, is a handy glossary to help you keep on top of what’s being said when
the conversation turns to Python programming.

conditions within the program.


Argument
The detailed extra information used by Python to perform more
detailed commands. Can also be used in the command prompt to
Expression
Essentially, Python code that produces a value of something.
specify a certain runtime event.

Block Float
An immutable floating point number used in Python.
Used to describe a section or sections of code that are
grouped together.
Function
Break Used in Python to define a sequence of statements that can be
called or referenced at any time by the programmer.
A command that can be used to exit a for or while loop. For example,
if a key is pressed to quit the program, Break will exit the loop.
GitHub
A web-based version control and collaboration portal designed for
Class software developers to better manage source code.
A class provides a means of bundling data and functionality
together. They are used to encapsulate variables and functions into a
single entity.
Global Variable
A variable that is useable anywhere in the program.
Comments Graphics
A comment is a section of real world wording inserted by the
The use of visual interaction with a program, game or operating
programmer to help document what’s going on in the code. They
system. Designed to make it easier for the user to manage the
can be single line or multi-line and are defined by a # or ‘’’.
program in question.
Debian GUI
A Linux-based distro or distribution that forms the Debian Project.
Graphical User Interface. The interface which most modern
This environment offers the user a friendly and stable GUI to
operating systems use to enable the user to interact with the core
interact with along with Terminal commands and other forms of programming of the system. A friendly, easy to use graphical
system level administration. desktop environment.

Def High-Level Language


Used to define a function or method in Python. A programming language that’s designed to be easy for
people to read.
Dictionaries
A dictionary in Python is a data structure that consists of key and IDLE
value pairs. Stands for Integrated Development Environment or Integrated
Development and Learning Environment.
Distro
Also Distribution, an operating system that uses the Linux Kernel Immutable
as its core but offers something different in its presentation to Something that cannot be changed after it is created.
the end user.
Import
Editor Used in Python to include modules together with all the
An individual program, or a part of the graphical version of Python, accompanying code, functions and variables they contain.
that enables the user to enter code ready for execution.
Indentation
Exceptions Python uses indentation to delimit blocks of code. The indents
Used as a means of breaking from the normal flow of a code are four spaces apart, and are often created automatically after a
block in order to handle any potential errors or exceptional colon is used in the code.

96 Raspberry Pi Coding & Projects


Glossary of Terms

Integer Python
A number data type that must be a whole number and not An awesome programming language that’s easy to learn and use,
a decimal. whilst still being powerful enough to enjoy.

Interactive Shell Random


The Python Shell, which is displayed whenever you launch the A Python module that implements a pseudo-random character
graphical version of Python. generator using the Mersenne Twister PRNG.

Kernel Range
The core of an operating system, which handles data processing, A function that’s used to return a list of integers, defined by the
memory allocation, input and output, and processes information arguments passed through it.
between the hardware and programs.
Root
Linux The bottom level user account used by the system itself. Root is
An open source operating system that’s modelled on UNIX. the overall system administrator and can go anywhere, and do
Developed in 1991 by Finnish student Linus Torvalds. anything, on the system.

Lists Sets
A Python data type that contains collections of values, which can Sets are a collection of unordered but unique data types.
be of any type and can readily be modified.
Strings
Local Variable Strings can store characters that can be modified. The contents of
A variable that’s defined inside a function and is only useable a string are alphanumerical and can be enclosed by either single
inside that function. or double quote marks.

Loop Terminal
A piece of code that repeats itself until a certain condition is met. Also Console or Shell. The command line interface to the
Loops can encase the entire code or just sections of it. operating system, namely Linux, but also available in macOS.
From there you can execute code and navigate the filesystem.
Module
A Python file that contains various functions that can be used Tkinter
within another program to further extend the effectiveness A Python module designed to interact with the graphical
of the code. environment, specifically the tk-GUI (Tool Kit Graphical
User Interface).
Operating System
Also OS. The program that’s loaded into the computer after the Try
initial boot sequence has completed. The OS manages all the A try block allows exceptions to be raised, so any errors can be
other programs, graphical user interface (GUI), input and output caught and handled according to the programmer’s instructions.
and physical hardware interactions with the user.
Tuples
Output An immutable Python data type that contains an ordered set of
Data that is sent from the program to a screen, printer or other either letters or numbers.
external peripheral.
UNIX
PIP A multitasking, multiuser operating system designed in
Pip Installs Packages. A package management system used to the ‘70s at the Bell Labs Research Centre. Written in C and
install and manage modules and other software written in Python. assembly language

Print Variables
A function used to display the output of something to the screen. A data item that has been assigned a storage location in the
computer’s memory.
Prompt
The element of Python, or the Command Line, where the user X
enters their commands. In Python it’s represented as >>> in the Also X11 or X-windows. The graphical desktop used in Linux-
interactive shell. based systems, combining visual enhancements and tools to
manage the core operating system.
Pygame
A Python module that’s designed for writing games. It includes Zen of Python
graphics and sound libraries and was first developed in When you enter: import this into the IDLE, the Zen of Python
October 2000. is displayed.

www.pclpublications.com 97
Python Code and Ideas

98 Raspberry Pi Coding & Projects


Python Code and Ideas INDEX

Python Code
and Ideas
To help you get the most from your Pi and Python, we’ve included some type-in
code that you can use in your own programming projects. Use the code, take it
apart, improve it and see what amazing things you can create through Python
and the Raspberry Pi.
This code repository is available from https://pclpublications.com/code-
portal/, and features all the listings in these pages and more. Here, you’ll find
code for games, scrolling animations and even a file manager.
This is a great resource, so sign up, get the code and let us know what
creative coding content you’ve developed with your Raspberry Pi.

100 Python File Manager 108 Vertically Scrolling Text


102 Number Guessing Game 110 Text to Binary Convertor
104 Text Adventure Script 112 Hangman Game Script
106 Python Digital Clock

106 Python
Clock
Digital
112 Hangman
Game Script
Create a Python Hangman is a great game
digital clock that to program into Python.
can be a companion
desktop widget.

www.pclpublications.com 99
Python Code and Ideas

Python File Manager


This file manager program displays a list FILEMAN.PY
of options that allow you to read a file, Copy the code below into a New > File and save it as FileMan.py.
write to a file, append to a file, delete a Once executed it will display the program title, along with the
file, list the contents of a directory and current time and date and the available options.

much more. It’s remarkably easy to edit


and insert into your own code, or add to. import shutil
import os
import time 1
import subprocess

def Read():
path=input(“Enter the file path to read:”)
file= open(path,”r”)
print(file.read()) 2
input(‘Press Enter...’)
file.close()

def Write():
path=input(“Enter the path of file to write or create:”)
if os.path.isfile(path):
print(‘Rebuilding the existing file’)
else:
print(‘Creating the new file’)
text=input(“Enter text:”)
file= open(path,”w”)
file.write(text)

def Add():
path=input(“Enter the file path:”)
text=input(“Enter the text to add:”)
file= open(path,”a”)
file.write(‘\n’+text)

def Delete():
This part of the code imports the necessary modules. path=input(“Enter the path of file for deletion:”)
1 The OS and Subprocess modules deal with the if os.path.exists(path):
print(‘File Found’)
operating system elements of the program.
os.remove(path)
print(‘File has been deleted’)
Each def XXX() functions store the code for each else:
2 of the menu’s options. Once the code within the print(‘File Does not exist’)
function is complete, the code returns to the main
menu for another option. def Dirlist():
path=input(“Enter the Directory path to display:”)
This is part of the code that checks to see what OS sortlist=sorted(os.listdir(path))
3 the user is running. In Windows the CLS command i=0
clears the screen, whereas in Linux and macOS, the while(i<len(sortlist)):
print(sortlist[i]+’\n’)
Clear command wipes the screen. If the code tries
i+=1
to run CLS when being used in Linux or macOS, an
error occurs, which then prompts it to run the Clear def Check():
command instead. fp=int(input(‘Check existence of \n1.File \n2.
Directory\n’))
These are the options, from 1 to 12. Each executes if fp==1:
4 the appropriate function when the relevant number path=input(“Enter the file path:”)
is entered. os.path.isfile(path)

80 Raspberry Pi Coding & Projects


Python File Manager

if os.path.isfile(path)==True: 5.List files in a directory


print(‘File Found’) 6.Check file existence
else: 7.Move a file
print(‘File not found’) 8.Copy a file
if fp==2: 9.Create a directory
path=input(“Enter the directory path:”) 10.Delete a directory
os.path.isdir(path) 11.Open a program
if os.path.isdir(path)==False: 12.Exit
print(‘Directory Found’)
else: ‘’’))
print(‘Directory Not Found’) if dec==1:
Read()
def Move(): if dec==2:
path1=input(‘Enter the source path of file to move:’) Write()
mr=int(input(‘1.Rename \n2.Move \n’)) if dec==3:
if mr==1: Add()
path2=input(‘Enter the destination path and file name:’) if dec==4:
shutil.move(path1,path2) Delete()
print(‘File renamed’) if dec==5:
if mr==2: Dirlist()
path2=input(‘Enter the path to move:’) if dec==6:
shutil.move(path1,path2) Check()
print(‘File moved’) if dec==7: 4
Move()
def Copy(): if dec==8:
path1=input(‘Enter the path of the file to copy or rename:’) Copy()
path2=input(‘Enter the path to copy to:’) if dec==9:
shutil.copy(path1,path2) Makedir()
print(‘File copied’) if dec==10:
Removedir()
def Makedir(): if dec==11:
path=input(“Enter the directory name with path to make Openfile()
\neg. C:\\Hello\\Newdir \nWhere Newdir is new if dec==12:
directory:”) exit()
os.makedirs(path) run=int(input(“1.Return to menu\n2.Exit \n”))
print(‘Directory Created’) if run==2:
exit()
def Removedir():
path=input(‘Enter the path of Directory:’)
treedir=int(input(‘1.Deleted Directory \n2.Delete
Directory Tree \n3.Exit \n’))
if treedir==1:
os.rmdir(path)
if treedir==2:
shutil.rmtree(path)
print(‘Directory Deleted’)
if treedir==3:
exit()

def Openfile():
path=input(‘Enter the path of program:’)
try:
os.startfile(path)
except:
print(‘File not found’)

run=1 Imports
while(run= =1): There are three modules to import here: Shutil, OS and
try: Time. The first two deal with the operating system and file
os.system(‘clear’)
except OSError: 3 management and manipulation; and the Time module simply
displays the current time and date.
os.system(‘cls’)
print(‘\n>>>>>>>>>>Python 3 File Manager<<<<<<<<<<\n’)
print(‘The current time and date is:’,time.asctime()) Note how we’ve included a try and except block to check if
print(‘\nChoose the option number: \n’) the user is running the code on a Linux system or Windows.
dec=int(input(‘’’1.Read a file Windows uses CLS to clear the screen, while Linux uses clear.
2.Write to a file The try block should work well enough but it’s a point of
3.Append text to a file possible improvement depending on your own system.
4.Delete a file

www.pclpublications.com 81
Python Code and Ideas

Number Guessing Game


This is a simple little piece of code NUMBERGUESS.PY
but it makes good use of the Random Copy the code and see if you can beat the computer within five
module, print and input, and a guesses. It’s an interesting bit of code that can be quite handy
while loop. The number of guesses when your implementing a combination of the Random module
alongside a while loop.
can be increased from 5 and the
random number range can easily be import random 1
altered too. guessesUsed = 0
Name=input(‘Hello! What is your name? ‘)
number = random.randint(1, 30)
print(‘Greetings, ‘ + Name + ‘, I\’m thinking of a
number between 1 and 30.’)
while guessesUsed < 5:
guess=int(input(‘Guess the number within 5 guesses...’))
guessesUsed = guessesUsed + 1
if guess < number:
print(‘Too low, try again.’)
if guess > number: 2
print(‘Too high, try again.’)
if guess == number:
break
if guess == number:
guessesUsed = str(guessesUsed)
print(‘Well done, ‘ + Name + ‘! You guessed
correctly in ‘ + guessesUsed + ‘ guesses.’)
3
if guess != number:
number = str(number)
print(‘Sorry, out of guesses. The number I was
thinking of is ‘ + number)

Although this is a reasonably easy to follow program, there are


1 some elements to the code that are worth pointing out. To begin
with, you need to import the Random module, as you’re using
random numbers within the code.
This section of the code creates the variables for the number
2 of guesses used, along with the name of the player, and also
sets up the random number between 1 and 30. If you want a
wider range of random number selection, then increase the
number=random.randint(1, 30) end value of 30; don’t make
it too high though or the player will never be able to guess it.
If the player guesses too low or too high, they are given the
appropriate output and asked to try again, while the number
of guesses is less than five. You can also increase the number of
guesses from 5 by altering the while guessesUsed < 5: value.
If the player guessed the correct number then they are given a
3 ‘well done’ output, along with how many guesses they used up.
If the player runs out of guesses, then the game over output is
displayed instead, along with revealing the number the computer
was thinking of. Remember, if you do alter the values of the
random number chosen by the computer, or the number of
guesses the player can take, then along with the variable values,
you also need to amend the instructions given in the print
statements at the start of the code.

82 Raspberry Pi Coding & Projects


Number Guessing Game

Code Improvements
Since this is such as simple script to apply to a situation, there’s can be reduced or increased depending on the circumstances
plenty of room to mess around with it and make it more the player’s character ends up in.
interesting. Perhaps you can include an option to take score, For example, as per the screenshot provided, you could use
the best out of three rounds. Maybe an elaborate way to something along the lines of:
congratulate the player for getting a ‘hole in one’ correct guess
on their first try. Endurance=0
CR=0
Moreover, the number guessing game code does offer some Luck=0
room for implementing into your code in a different manner. Endurance = random.randint(1, 15)
CR = random.randint(1, 20)
What we mean by this is, the code can be used to retrieve a
Luck = random.randint(1, 10)
random number between a range, which in turn can give you Print(“Your character’s stats are as follows:\n”)
the start of a character creation defined function within an Print(“Endurance:”, Endurance)
adventure game. Print(“Combat Rating:”, CR)
Print(“Luck:”, Luck)
Imagine the start of a text adventure written in Python, where
the player names their character. The next step is to roll the
The player can then decide to either stick with their roll or
virtual random dice to decide what that character’s combat
try again for the hope of better values being picked. There’s
rating, strength, endurance and luck values are. These can then
ample ways in which to implement this code into a basic
be carried forward into the game under a set of variables that
adventure game.

www.pclpublications.com 83
Python Code and Ideas

Text Adventure Script


Text adventures are an excellent way ADVENTURE.PY
to build your Python coding skills and The Adventure game uses just the Time module to begin with,
have some fun at the same time. This creating pauses between print functions. There’s a help system in
example that we created will start you place to expand upon, as well as the story itself.

on the path to making a classic text


adventure; where it will end is up to you. import time

print(“\n” * 200)
print(“>>>>>>>>>>Awesome Adventure<<<<<<<<<<\n”)
print(“\n” * 3)
time.sleep(3)
print(“\nA long time ago, a warrior strode forth from
the frozen north.”)
time.sleep(1)
print(“Does this warrior have a name?”)
name=input(“> “)
print(name, “the barbarian, sword in hand and looking
for adventure!”)
time.sleep(1)
print(“However, evil is lurking nearby....”)
time.sleep(1)
print(“A pair of bulbous eyes regards the hero...”)
time.sleep(1)
print(“Will”, name, “prevail, and win great fortune...”)
time.sleep(1)
print(“Or die by the hands of great evil...?”)
time.sleep(1)
print(“\n” *3)
print(“Only time will tell...”)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(1)
print(‘...’)
time.sleep(5)
print(“\n” *200)

print(‘’’ You find yourself at a small inn. There’s


little gold in your purse but your sword is sharp,
and you’re ready for adventure.
With you are three other customers.
A ragged looking man, and a pair of dangerous
looking guards.’’’)

def start():
print(“\n ----------”)
print(“Do you approach the...”)
print(“\n”)
print(“1. Ragged looking man”)
print(“2. Dangerous looking guards”)

cmdlist=[“1”, “2”]
cmd=getcmd(cmdlist)

84 Raspberry Pi Coding & Projects


Text Adventure Script

if cmd == “1”:
ragged() def getcmd(cmdlist):
elif cmd == “2”: cmd = input(name+”>”)
guards() if cmd in cmdlist:
return cmd
def ragged(): elif cmd == “help”:
print(“\n” * 200) print(“\nEnter your choices as detailed in
print(‘’’You walk up to the ragged looking man and the game.”)
greet him. print(“or enter ‘quit’ to leave the game”)
He smiles a toothless grin and, with a strange return getcmd(cmdlist)
accent, says. elif cmd == “quit”:
“Buy me a cup of wine, and I’ll tell you of print(“\n-----------”)
great treasure...’’’) time.sleep(1)
time.sleep(2) print(“Sadly you return to your homeland without
fame or fortune...”)
def guards(): time.sleep(5)
print(“\n” *200) exit()
print(‘’’You walk up to the dangerous looking guards
and greet them.
The guards look up from their drinks and if _ _ name _ _ =
=” _ _ main _ _ ”:
snarl at you. start()
“What do you want, barbarian?” One guard reaches
for the hilt of his sword...’’’)
time.sleep(2)

Adventure Time
This, as you can see, is just the beginning of the adventure and
takes up a fair few lines of code. When you expand it, and weave
the story along, you’ll find that you can repeat certain instances
such as a chance meeting with an enemy or the like.

We’ve created each of the two encounters as a defined set


of functions, along with a list of possible choices under the
cmdlist list, and cmd variable, of which is also a defined function.
Expanding on this is quite easy, just map out each encounter and
choice and create a defined function around it. Providing the
user doesn’t enter quit into the adventure, they can keep playing.

There’s also room in the adventure for a set of variables designed


for combat, luck, health, endurance and even an inventory or
amount of gold earned. Each successful combat situation can
reduce the main character’s health but increase their combat
skills or endurance. Plus, they could loot the body and gain gold,
or earn gold through quests.

Finally, how about introducing the Random module. This will


enable you to include an element of chance in the game. For
example, in combat, when you strike an enemy you will do a
random amount of damage as will they. You could even work out
the maths behind improving the chance of a better hit based on
your or your opponent’s combat skills, current health, strength
and endurance. You could create a game of dice in the inn, to see
if you win or lose gold (again, improve the chances of winning by
working out your luck factor into the equation).

Needless to say, your text adventure can grow exponentially


and prove to be a work of wonder. Good luck, and have fun with
your adventure.

www.pclpublications.com 85
Python Code and Ideas

Python Digital Clock


There is already a clock displayed on DIGCLOCK.PY
the desktop of most operating systems This is a surprisingly handy little script and one that we’ve used
but it’s always handy to have one on top in the past instead of relying on a watch or even the clock in the
of the currently open window. To that system tray of the operating system.

end, why not create a Python digital import time


import tkinter as tk
clock that can be a companion desktop
def tick(time1=’’):
widget for you. # get the current time from the PC
time2 = time.strftime(‘%H:%M:%S’)
if time2 != time1:
time1 = time2
clock.config(text= time2)

clock.after(200, tick)

root = tk.Tk()
clock = tk.Label(root, font=(‘arial’, 20, ‘bold’),
bg=’green’)
clock.pack(fill= ’both’, expand= 1)
tick()
root.mainloop()

86 Raspberry Pi Coding & Projects


Python Digital Clock

Tick Tock
This is a piece of code we’ve used many times in the past to keep
track of time while working on multiple monitors and with just a root.title(‘Stop Watch’)
quick glance to where we’ve placed it on the screen. root.resizable(True, False)
root.grid _ columnconfigure(0, weight=1)
The Tkinter box can be moved around without affecting the padding = dict(padx=5, pady=5)
widget = StopWatch(root, **padding)
time, maximised or closed by the user at will. We haven’t given
widget.grid(sticky=tkinter.NSEW, **padding)
the Tkinter clock window a title, so you can add to that easily
root.mainloop()
enough by snipping the code from other examples in this book.
def _ _ init _ _ (self, master=None, cnf={}, **kw):
Another area of improvement is to include this code when padding = dict(padx=kw.pop(‘padx’, 5), pady=kw.
Windows or Linux starts, so it automatically pops up on the pop(‘pady’, 5))
desktop. See also, if you’re able to improve its functionality by super(). _ _ init _ _ (master, cnf, **kw)
including different time zones: Rome, Paris, London, New York, self.grid _ columnconfigure(1, weight=1)
Moscow and so on. self.grid _ rowconfigure(1, weight=1)
self. _ _ total = 0
self. _ _ label = tkinter.Label(self,
text=’Total Time:’)
self. _ _ time = tkinter.StringVar(self,
‘0.000000’)
self. _ _ display = tkinter.Label(self,
textvariable=self. _ _ time)
self. _ _ button = tkinter.Button(self,
text= ’Start’, command=self. _ _ click)
self. _ _ label.grid(row=0, column=0,
sticky=tkinter.E, **padding)
self. _ _ display.grid(row=0, column=1,
sticky=tkinter.EW, **padding)
self. _ _ button.grid(row=1, column=0,
columnspan=2,sticky=tkinter.NSEW, **padding)

def _ _ click(self):
if self. _ _ button[‘text’] == ‘Start’:
self. _ _ button[‘text’] = ‘Stop’
self. _ _ start = time.clock()
self. _ _ counter = self.after _ idle(self. _ _ update)
else:
self. _ _ button[‘text’] = ‘Start’
self.after _ cancel(self. _ _ counter)

def _ _ update(self):
now = time.clock()
Another example, expanding on the original code, could be a diff = now - self. _ _ start
digital stopwatch. For that you could use the following: self. _ _ start = now
self. _ _ total += diff
import tkinter self. _ _ time.set(‘{:.6f}’.format(self. _ _ total))
import time self. _ _ counter = self.after _ idle(self. _ _ update)

class StopWatch(tkinter.Frame): if _ _ name _ _ == ‘ _ _ main _ _ ’:


StopWatch.main()
@classmethod
def main(cls):
tkinter.NoDefaultRoot()
root = tkinter.Tk()

www.pclpublications.com 87
Python Code and Ideas

Vertically Scrolling Text


What’s not to like about vertically EPICSCROLL.PY
scrolling text? Its uses are many: the We’ve used the poem Cimmeria by Robert E. Howard for the
beginning of a game or introduction to code’s scrolling text, along with a dramatic black background and
something epic, like the beginning of red text. We think you’ll agree, it’s quite epic.

every Star Wars movie; a list of credits at


the end of something, such as a Python
presentation. The list goes on. import pygame as pg
from pygame.locals import *

pg.init()

text _ list = ‘’’

I remember
The dark woods, masking slopes of sombre hills;
The grey clouds’ leaden everlasting arch;
The dusky streams that flowed without a sound,
And the lone winds that whispered down the passes.

Vista on vista marching, hills on hills,


Slope beyond slope, each dark with sullen trees,
Our gaunt land lay. So when a man climbed up
A rugged peak and gazed, his shaded eye
Saw but the endless vista – hill on hill,
Slope beyond slope, each hooded like its brothers.

It was a gloomy land that seemed to hold


All winds and clouds and dreams that shun the sun,
With bare boughs rattling in the lonesome winds,
And the dark woodlands brooding over all,
Not even lightened by the rare dim sun
Which made squat shadows out of men; they called it
Cimmeria, land of Darkness and deep Night.

It was so long ago and far away


I have forgot the very name men called me.
The axe and flint-tipped spear are like a dream,
And hunts and wars are shadows. I recall
Only the stillness of that sombre land;
The clouds that piled forever on the hills,
The dimness of the everlasting woods.
Cimmeria, land of Darkness and the Night.

Oh, soul of mine, born out of shadowed hills,


To clouds and winds and ghosts that shun the sun,
How many deaths shall serve to break at last
This heritage which wraps me in the grey
Apparel of ghosts? I search my heart and find
Cimmeria, land of Darkness and the Night!

‘’’.split(‘\n’)

88 Raspberry Pi Coding & Projects


Vertically Scrolling Text

class Credits:
def _ _ init _ _ (self, screen _ rect, lst): A Long Time Ago…
self.srect = screen _ rect The obvious main point of enhancement is the actual text
self.lst = lst itself. Replace it with a list of credits, or an equally epic
self.size = 16
opening storyline to your Python game, and it will certainly
self.color = (255,0,0)
self.buff _ centery = self.srect.height/2 + 5 hit the mark with whoever plays it. Don’t forget to change
self.buff _ lines = 50 the screen resolution if needed; we’re currently running it at
self.timer = 0.0 800 x 600.
self.delay = 0
self.make _ surfaces()

def make _ text(self,message):


font = pg.font.SysFont(‘Arial’, self.size)
text = font.render(message,True,self.color)
rect = text.get _ rect(center = (self.srect.
centerx, self.srect.centery + self.buff _ centery) )
return text,rect

def make _ surfaces(self):


self.text = []
for i, line in enumerate(self.lst):
l = self.make _ text(line)
l[1].y += i*self.buff _ lines
self.text.append(l)

def update(self):
if pg.time.get _ ticks()-self.timer > self.delay:
self.timer = pg.time.get _ ticks()
for text, rect in self.text:
rect.y -= 1

def render(self, surf):


for text, rect in self.text:
surf.blit(text, rect)

screen = pg.display.set _ mode((800,600))


screen _ rect = screen.get _ rect()
clock = pg.time.Clock()
running=True
cred = Credits(screen _ rect, text _ list)

while running:
for event in pg.event.get():
if event.type == QUIT:
running = False
screen.fill((0,0,0))
cred.update()
cred.render(screen)
pg.display.update()
clock.tick(60)

www.pclpublications.com 89
Python Code and Ideas

Text to Binary Convertor


While it may not seem too exciting, this TXT2BIN.PY
text to binary convertor is actually quite Naturally we’re using the format function to convert the
good fun. It also only uses two lines of user’s entered text string into its binary equivalent. If you
code, so it’s extremely easy to insert into want to check its accuracy, you can plug the binary into an
online convertor.
your own script.
text=input(“Enter text to convert to Binary: “)

print(‘ ‘.join(format(ord(x), ‘b’) for x in text))

90 Raspberry Pi Coding & Projects


Text to Binary Convertor

1000010 1101001 1101110 1100001


1110010 1111001
The text to binary convertor does offer some room for
pygame.display.set _ caption(“Binary Conversion”)
improvement and enhancement. There are many uses: it could
be utilised in a password or secret word script, as part of an done = False
adventure game or just a novel way to display someone’s name. clock = pygame.time.Clock()

With regards to improvements, you could display the binary text _ rotate _ degrees = 0
conversion in a Pygame window, using the animated text options
from page 100. You could also ask the user if they wanted to Binary=(‘ ‘.join(format(ord(x), ‘b’) for x
have another go, or even ask if they wanted the binary output to in conversion))
be saved to a file.
while not done:

With regards to rendering the outputted binary conversion to a for event in pygame.event.get():
Pygame window, complete with rotating text, you can use: if event.type == pygame.QUIT:
done = True
import pygame
pygame.init() screen.fill(WHITE)
font = pygame.font.SysFont(‘Calibri’, 25, True, False)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255) text = font.render(Binary, True, BLACK)
BLUE = (0, 0, 255) text = pygame.transform.rotate(text, text _
GREEN = (0, 255, 0) rotate _ degrees)
RED = (255, 0, 0) text _ rotate _ degrees += 1
screen.blit(text, [100, 50])
print(“>>>>>>>>>>Text to Binary Convertor<<<<<<<<<<\n”) pygame.display.flip()

conversion=input(“Enter text to convert to Binary: “) clock.tick(60)

size = (600, 400) pygame.quit()


screen = pygame.display.set _ mode(size)
print(‘ ‘.join(format(ord(x), ‘b’) for x in conversion))

www.pclpublications.com 91
Python Code and Ideas

Hangman Game Script


Hangman is a great game to program HANGMAN.PY
into Python. It can be extremely We’ve made a Hangman game board (the gallows) out of
complex, displaying graphics, the characters that can be displayed in the IDLE Shell, along with a
number of guesses left in the secret huge bank of words to randomly choose from.

word, a huge bank of available words


picked at random and countless other import random

elements. It can also be quite simple. board = [‘’’


Here we have a mix between the two. >>>>>>>>>>Hangman<<<<<<<<<<

+---+
| |
|
|
|
|
= = = = = = = = = ’’’, ‘’’

+---+
| |
O |
|
|
|
= = = = = = = = = ’’’, ‘’’

+---+
| |
O |
| |
|
|
= = = = = = = = = ’’’, ‘’’

+---+
| |
O |
/| |
|
|
= = = = = = = = = ’’’, ‘’’

+---+
| |
O |
/|\ |
|
|
= = = = = = = = = ’’’, ‘’’

+---+
| |
O |
/|\ |
/ |

92 Raspberry Pi Coding & Projects


Hangman Game Script

| luggage responsible ambassador circumstance


= = = = = = = = = ’’’, ‘’’ congratulate frequent’.split()
return bank[random.randint(0,len(bank))]
+---+
| | def main():
O | game = Hangman(rand _ word())
/|\ | while not game.hangman _ over():
/ \ | game.print _ game _ status()
| user _ input = input(‘\nEnter a letter: ‘)
= = = = = = = = = ’’’] game.guess(user _ input)

game.print _ game _ status()


class Hangman: if game.hangman _ won():
def _ _ init _ _ (self,word): print (‘\nCongratulations! You have won!!’)
self.word = word else:
self.missed _ letters = [] print (‘\nSorry, you have lost.’)
self.guessed _ letters = [] print (‘The word was ‘ + game.word)

def guess(self,letter): print (‘\nGoodbye!\n’)


if letter in self.word and letter not in self.
guessed _ letters: if _ _ name _ _ == “ _ _ main _ _ ”:
self.guessed _ letters.append(letter) main()
elif letter not in self.word and letter not in
self.missed _ letters:
self.missed _ letters.append(letter)
else:
return False
QUIT()
return True Since this is the last example in our Python code repository,
we thought we’d go out with a bang and feature the hangman
def hangman _ over(self): gallows being drawn with each incorrect guess of the word.
return self.hangman _ won() or (len(self.missed _ Don’t worry if it looks misaligned in the text here, this is
letters) == 6)
merely due to the differences between using the Python IDLE
def hangman _ won(self): editor and pasting the code into a word processor (which
if ‘ _ ’ not in self.hide _ word(): formats things differently).
return True
return False There’s plenty you can do to improve, enhance and expand on
what we’ve presented here. You can include a routine that
def hide _ word(self): returns an error if the user enters a number or character. You
rtn = ‘’ can include extra points for someone who guesses the entire
for letter in self.word: word in one go rather than one letter at a time and you could
if letter not in self.guessed _ letters:
perhaps add Chopin’s Funeral March should you lose the
rtn += ‘ _ ’
game; or something celebratory if you win.
else:
rtn += letter
return rtn

def print _ game _ status(self):


print (board[len(self.missed _ letters)])
print (‘Word: ‘ + self.hide _ word())
print (‘Letters Missed: ‘,)
for letter in self.missed _ letters:
print (letter,)
print ()
print (‘Letters Guessed: ‘,)
for letter in self.guessed _ letters:
print (letter,) Consider replacing the bank of words too. They’re found
print () under the bank list, and could easily be swapped out for
something more difficult. If you download www.github.com/
def rand _ word(): dwyl/english-words you can find a text document with over
bank = ‘ability about above absolute accessible 466,000 words. Perhaps you could swap the words in the bank
accommodation accounting beautiful bookstore to instead read the contents of the text file:
calculator clever engaged engineer enough
handsome refrigerator opposite socks interested def rand _ word():
strawberry backgammon anniversary confused with open(“/home/pi/Downloads/words.txt”, “rt”) as f:
dangerous entertainment exhausted impossible bank=f.readlines()
overweight temperature vacation scissors return bank[random.randint(0,len(bank))]
accommodation appointment decrease development
earthquake environment brand environment necessary

www.pclpublications.com 93
Mastering Linux

114 Raspberry Pi Coding & Projects


Mastering Linux INDEX

Mastering
Linux
The Raspberry Pi OS is Linux based, which is an incredibly powerful operating
system that drives many supercomputers, web servers and even top-end
military hardware. Get to grips with Linux, and you will not just master the Pi
but also the power behind the Internet.
In this section, you will discover how the OS works, how the filesystem is
built and how you can list, move, create and delete files and folders. To truly be
able to hack the Raspberry Pi, you will need to be familiar with the OS and its
inner-workings.
The more adept you become at Linux, the better your projects will be, and
the more power you’ll have over them and how they interact with the digital
world to which they’re connected.

116 What is Linux? 136 Useful System and Disk Commands


118 Using the Filesystem 138 Managing Programs and Processes
120 Listing and Moving Files 140 Input, Output and Pipes
122 Creating and Deleting Files 142 Fun Things to Do in the Terminal
124 Create and Remove Directories 144 More Fun Things to Do in the
126 Copying, Moving and Renaming Files Terminal
128 Using the Man Pages 146 Linux Tips and Tricks
130 Editing Text Files 148 Command Line Quick Reference
132 Getting to Know Users 150 A-Z of Linux Commands
134 Ownership and Permissions

www.pclpublications.com 115
Mastering Linux

What is Linux?
The Raspberry Pi operating system is Raspbian, which is a Linux operating system; but what
exactly is Linux? Where did it come from and what does it do? In a world where Windows
and macOS have supremacy of the desktop, it’s easy to overlook it, but there’s more to Linux
than you might imagine.

Linux is a surprisingly powerful, fast, secure and capable that it soon became the system of choice for companies
operating system. It’s used as the OS of choice for the and universities where high-end computing tasks
Raspberry Pi, in the form of Raspbian OS, as well as in some were needed.
of the most unlikely places.
Torvalds needed a system that could mirror Unix’s
Despite only enjoying a 1.96% share (according to performance and features, without the licensing cost. Thus
netmarketshare.com) of the total desktop operating system was born Linux, the Unix-like operating system which used
market, Linux has a dedicated following of enthusiasts, freely available code from the GNU project. This enabled
users and contributors. It was created in 1991 by University users around the world to utilise the power of the Unix-like
of Helsinki student, Linus Torvalds, who had become system, completely free of charge, an ethos that still holds
frustrated with the limitations and licensing of the popular today: Linux is free to download, install and use.
educational system Minix, a miniature version of the Unix
Linux is much like any other operating system, such as
operating system, in use at the time.
Windows or macOS in that it manages the computer
Unix itself was released in the early ‘70s, as a multi-tasking, hardware, provides an interface for the user to access
modular-designed operating system originally developed that hardware and comes with programs for productivity,
for programmers who needed a stable platform to code communications, gaming, science, education and more. Linux
on. However, its performance, power and portability meant can be broken up into a number of significant elements:

BOOTLOADER SHELL
The bootloader is the software that initialises and boots The Linux shell is a command line interface environment,
up your computer. It loads up the various modules the OS which a Linux user can use to enter commands to the OS
uses to begin to access the hardware in the system. that directly affect it. Within the shell you can add new
users, reboot the system, create and delete files and
folders plus much more. BASH (Bourne-Again Shell) is
the most popular shell used in Linux, although others are
available. The shell is also known as the Terminal and it’s
where we’re going to work from through this section of
KERNEL the book.
The kernel is the core of the system and the single
element that is actually called Linux. The Linux kernel
manages the computer processor, memory, storage and
any peripherals you have attached to your computer.

DESKTOP ENVIRONMENT
The Desktop Environment, or DE, is the main Graphical
User Interface (GUI) that users interact with. It’s the
DAEMONS desktop and includes Internet browsers, productivity,
Daemons are background services that start as the games and whatever program or app you’re using. There
operating system is booting. These can enable printing, are countless DEs available, however Raspbian uses PIXEL.
sound, networking and so on.

PROGRAMS/APPLICATIONS
GRAPHICAL SERVER As Linux is a free, open source operating system, it
This is a module within Linux that provides a graphical also makes good use of the tens of thousands of freely
output to your monitor. It’s referred to as the X server or available applications. The likes of LibreOffice, GIMP and
simply X. Python are just the tip of the iceberg.

116 Raspberry Pi Coding & Projects


What is Linux?

Linus Torvalds, the creator


of the Linux kernel.

Linux is used throughout the world, in a number of basic and


quite unique uses. While it may look radically different from one
environment to the next, the actual Linux kernel, can be found
in modern smart TVs, in-car entertainment systems and GPS,
supercomputers, IoT devices and the Raspberry Pi. It’s used by
NASA, both in the command centre and on-board the ISS. Linux
servers power the backbone of the Internet, along with most
of the websites you visit daily. Android utilises components
of the Linux kernel, as do set top boxes, games consoles and
even your fridge, freezer, oven and washing machine.
Linux isn’t just a free to use operating system. It’s stable, powerful and
Tux, the Linux mascot fast, easily customised and requires very little maintenance. However, it’s
(Linus likes penguins).
more than just performance stats; Linux means freedom from the walled
garden approach of other operating systems. It’s a lively community of
like-minded individuals who want more from their computers without the
shackles of price or conformity. Linux means choice.

Raspbian on the
Raspberry Pi, is the
Linux distribution
of choice.

A Desktop Environment can be as


complex or as simple as the user desires.

www.pclpublications.com 117
Mastering Linux

Using the Filesystem


To master Linux, it’s important to understand how the filesystem works. What’s more,
it’s also important to become familiar with the Terminal, or shell. This command line
environment may appear daunting at first, but with practise, it soon becomes easy to use.

GETTING AROUND
To drop into the Terminal, click on the fourth icon from the left along the top of the Raspberry Pi desktop, the one with a right-facing arrow
and an underscore. This is the shell, or Terminal.

First, you’re going to look at directories and the Enter: ls to view the contents of the current
STEP 1 STEP 3
directory path. A directory is the same thing as a directory. You should see Desktop, Documents, and
folder, however in Linux it’s always called a directory. These are Downloads and Scratch in Blue. You may also see other items
placed inside each other using a “/” character. So when you see / depending on how much you have used your Raspberry Pi. The colour
home/pi it means the pi directory is inside the home directory. code is worth knowing: directories are blue while most files are white.
Enter: clear and press return to clean the screen. Now enter: pwd. As you go on you’ll see other colours: executable files (programs) are
This stands for Print Working Directory and displays /home/pi. bright green, archived files are red and so on. Blue and white are the
two you need to know to get started.

When you log in to your Raspberry Pi, you don’t Now you’re going to move from the pi directory into
STEP 2 STEP 4
start at the base of the hard drive, known as the the Documents directory. Enter: cd Documents.
‘root’ (also known as the topmost directory). Instead you begin Note the capital “D”. Linux is case sensitive, which means you have to
inside your user directory, which is named ‘pi’ by default and is enter the exact name including correct capitalisation. The cd
itself in a directory called ‘home’. Directories are indicated by the ‘/’ command stands for change directory. Now enter: pwd again to view
symbol. So, “‘/home/pi’” tells you that in the root is a directory the directory path. It will display /home/pi/ Documents. Enter: ls to
called home, and the next “‘/’” says that inside “home” is a directory view the files inside the Documents directory.
called “pi”. That’s where you start.

118 Raspberry Pi Coding & Projects


Using the Filesystem

How do you get back up to the pi directory? By using The “ls” and “cd” commands can also be used with
STEP 5 STEP 6
a command “cd ..”. In Linux two dots means the more complex paths. Enter: ls Documents/
directory above, also known as the parent directory. Incidentally, a Pictures to view the contents of a Pictures directory inside your
single dot “.” is used for the same directory. You never use “cd .” to Documents directory. You can switch to this directory using cd
switch to the same directory but it’s worth knowing because some Documents/Pictures; use cd ../.. to move back up two
commands need you to specify the current directory. parent directories.

ABSOLUTE VS RELATIVE PATHS


It is important to know the difference between the working directory, root directory and home. There are also two types of path: Absolute
and Relative. These are easier to understand than they sound. Let’s take a look…

By default, commands like “ls” use the working The second command (“ls /Documents/Pictures”)
STEP 1 STEP 3
directory. This is the current directory that you’re attempts to list the content of Pictures in a directory
looking at and is set to your home directory by default (/users/pi). called Documents inside the root directory (because the path started
Using “pwd” (Print Working Directory) lets you know what the working with ‘/’, which is root). There is typically no Documents directory in
directory is, and using “cd” changes the working directory. root, so you will get a “No such file or directory” error. Starting a path
with ‘/’ is known as an “absolute path”, while starting without the ‘/’ is
known as a “relative path” because it is relative to your
working directory.

The root directory is always ‘/’. Entering: ls / lists the There is also an absolute path shortcut to your user
STEP 2 STEP 4
contents of root, and entering: cd / switches to the directory, and that is the tilde “~” character. Entering:
root directory. This is important because there is a difference between ls ~ always lists the contents of your home directory, while “cd ~”
“ls Documents/Pictures” and “ls /Documents/Pictures”. The first moves straight to your home directory, no matter what your working
command lists the contents of the Pictures directory in Documents directory is. You can also use this shortcut wherever you are: enter: ls
inside the working directory (which, if you are in the home directory, ~/Documents/Pictures to display the contents of the Pictures.
will work).

www.pclpublications.com 119
Mastering Linux

Listing and Moving Files


Admittedly, using the desktop GUI to list and move files is much easier than using the
Terminal and keyboard. However, it’s an important skill that you will appreciate as you
advance with the Raspberry Pi and Linux.

LOOKING AT FILES
Operating systems are built on files and folders, or directories if you prefer. While you’re used to viewing your own files, most operating
systems keep other files out of sight. In Raspbian, you have access to every file in the system.

We’ve already looked at “ls”, which lists the files in After the permission letters come a single number.
STEP 1 STEP 3
the working directory, but you are more likely to use This is the number of files in the item. If it’s a file then
a command like “ls –l”. The bit after the command (the ‘-lah’) is it’ll be 1, but if it’s a directory it’ll be at least 2. This is because each
known as the argument. This is an option that modifies the directory contains two hidden files; one with a single dot (.) and one
behaviour of the command. with two dots (..). Directories containing files or other directories will
have a higher number.

The “-l” argument lists files and directories in long Next you’ll see the word “pi” listed twice on each
STEP 2 STEP 4
format. Each file and directory is now on a single line, line. This refers to the user rather than the name of
and before each file is a lot of text. First you’ll see lots of letters and your computer (your default username is “pi”). The first is the owner
dashes, like ‘drwxr-xr-x’. Don’t worry about these for now; they are of the file, and the second is the group. Typically these will both be
known as ‘permissions’ and we’ll come to those later. the same and you’ll see either ‘pi’ or ‘root’. You can enter: ls -l /
to view the files and directories in the root directory that belong to
the root account.

120 Raspberry Pi Coding & Projects


Listing and Moving Files

The next number relates to the size of the file, in bytes. Finally, you should be aware that there are many
STEP 5 STEP 6
In Linux each text file is made up of letters and each hidden files in Linux. These are listed using the “-a”
letter takes up a byte, so our names.txt file has 37 bytes and 37 argument. Hidden files and directories begin with a dot (.), so you
characters in the document. Files and directories can be extremely should never start a file or directory with a dot, unless you want to
large and hard to determine, so use “ls – lh”. The “h” argument hide it. Typically, you can combine all three arguments together into
humanises the number, making it easier to read. the command ‘”s –lah”.

SOME COMMON DIRECTORIES


Now that you know how to view the contents of your hard drive you’ll start to notice a lot of directories with names like bin, sbin, var and
dev. These are the files and directories that you are kept away from on a Mac, and won’t encounter on a Windows PC.

Enter: ls -lah / to view all of the files and Entering: ls /home displays the contents of your
STEP 1 STEP 3
directories, including the hidden items, in the root home directory, which contains pi; the directory
directory of your hard drive. Here you will see all the items that make that you start in. So, entering: ls/home/pi is the same as just “ls”
up your Raspbian OS (which is a version of Linux). It’s worth taking the from the default home directory. This is where you are expected
time to know some of them. to place most of the documents you create. Don’t confuse home
with “usr”; the /usr directory is where find you find program tools
and libraries.

Bin is a directory that stores binaries. This is the Linux Lib is a directory that contains libraries of code that
STEP 2 STEP 4
way of saying programs or applications. Sbin is for are referred to by other programs (different programs
system binaries, which are the programs that make up your system. share files in Lib). “Var” is short for various, which is mostly files used
Dev contains references to your devices: hard drive, keyboard, mouse by the system, but you may need to work with items here. Finally there
and so on. Etc contains your system configuration files. is a directory called “tmp”, which is for temporary files; files placed
here are on your system for the short term and can be deleted from
the system.

www.pclpublications.com 121
Mastering Linux

Creating and Deleting Files


Being able to create and delete a file is an everyday computing skill. However, when using
the Linux Terminal, there’s an element of care required, chiefly because any deleted files
aren’t placed in the system recycle bin.

CREATING FILES
Once you learn to recognise the files and directories that make up Raspbian OS, it’s time to discover how to make your own. Knowing how to
make, edit and delete files and directories is essential if you want to make your own projects.

We’re going to create a file using a command called If you try to touch a file that doesn’t exist, you create a
STEP 1 STEP 3
Touch. Touch is an interesting command that reaches blank file with that name. Try it now. Type touch
out to a file, or directory, and updates it (this changes the system time testfile and ls –l to view the files. You’ll now have a new file in
as if you’d just opened the file). You can see Touch in access using “ls your home directory called “testfile”. Notice that the size of the file is
–l” and checking the time next to a directory (such as Scratch). 0, because it has nothing in it.

Now enter: touch Scratch and ls –l again and A quick word about file names: remember that Linux is
STEP 2 STEP 4
notice that the time has changed. It now matches the case sensitive, so if you now enter: touch Testfile
current time. You might be wondering what this has to do with (with a capital T), it doesn’t update ‘testfile’; instead, it creates a
creating files or directories. Touch has a second, more popular, use, second file called ‘Testfile’. Enter: ls –l to see both files. This is
which is to create files. confusing, so most people stick with using lowercase letters at
all times.

122 Raspberry Pi Coding & Projects


Creating and Deleting Files

Another important thing to know is never to use a Here are some other files names to avoid:
STEP 5 STEP 6
space in your file names. If you try to enter: touch #%&{}\<>*?/$!’”:@+`|=. The full stop (.) is used to
test file, you create a document called “test” and another called create an extension to a file; usually used to indicate a file type, such
“file”. Technically there are ways to create files containing a space but as textfile.txt or compressedfile.zip, and starting a file with a full stop
you should always use an underscore character (“_”) instead of a makes it invisible. Don’t use a full stop in place of a space though; stick
space, such as “touch test_file”. to underscores.

REMOVING FILES
We’ve created some files that we don’t want, so how do we go about removing them? It turns out that deleting files in your Raspberry Pi is
really easy, which may be a problem, so be careful.

Enter: ls –l to view the files in your home directory. We’re going to use a wildcard (*) to delete our next
STEP 1 STEP 3
If you’ve followed the steps before then you should two files, but again this is something you really need
have three files: “test”, “testfile”, and “Testfile”. We’re going to get rid to do with care. First use “ls” to list the files and make sure it’s the one
of these items because they were created as an example. you want to delete. Enter: ls test* to view files that match the
word “test” and any other characters. The “*” character is called a
“wildcard” and it means any characters here.

To get rid of files you use the “rm” command. Enter: We see that “ls test*” matches two files: “test” and
STEP 2 STEP 4
rm Testfile to delete the file called “Testfile” (with “testfile”, but not the file called “file”. That’s because
the uppercase “t”). Enter: ls –l and you’ll find it’s gone. Where is it didn’t match the “test” part of “test*”. Check carefully over groups
it? It’s not in the Trash or Recycle Bin, like on a Mac or Windows PC. of files you want to remove (remember you can’t recover them) and
It’s deleted completely and cannot be recovered. Bear this in mind replace the “ls” with “rm”. Enter: rm test* to remove both files.
and always think before deleting files. Finally enter: rm file to get rid of the confusing file.

www.pclpublications.com 123
Mastering Linux

Create and Remove


Directories
Creating, moving and deleting directories isn’t as easy in the Terminal as it is within a
desktop interface. You need to tell Linux to move the directories inside other directories, a
process known as recursion. Sounds complex but you should quickly get the hang of it.

MANAGING FILES AND DIRECTORIES


Now that you know how to create files, you’ll want to learn how to make directories, which are the same thing as folders, as well as move
items around. If you are more used to working with a desktop interface, this can take a bit of getting used to.

Enter: ls to quickly view all the directories currently in Like touch, you can create multiple directories at once
STEP 1 STEP 3
in the home location. Directories are created using the with the mkdir command. Enter: mkdir testdir2
“mkdir” command (make directory). Enter: mkdir testdir to create testdir3 and enter: ls. You’ll now find several directories called
a new directory in your home directory. Enter: ls again to see it. testdir. Also, like files, you should know this means you can’t (and
really shouldn’t) create directories with spaces. As with files, use an
underscore (“_”) character instead of a space.

The “mkdir” command is different to touch, in that it You can create directories inside of each other using
STEP 2 STEP 4
doesn’t update the timestamp if you use it with a the directory path. Enter: mkdir Documents/
directory that already exists. Enter: mkdir testdir again and you’ll photos to create a new directory called “photos” inside your
get the error “mkdir: cannot create directory ‘testdir: File exists”. documents directory. The directory has to already exist, though, try to
enter: mkdir articles/reports and you’ll get an error because
there is no articles directory.

124 Raspberry Pi Coding & Projects


Create and Remove Directories

To create a directory path you need to pass in the “p” Now you’re starting to get a bit more advanced, we’re
STEP 5 STEP 6
option to mkdir (which stands for “parents”). Options, going to just reiterate something. In Linux the
if you remember, come after the command and start with a ‘-’. So command structure is always: command, option and argument, in that
enter: mkdir -p articles/reports. Enter: ls to view the articles order. The command is the function, next are the options (typically
directory, or “ls articles” to view the reports directory sitting inside. single letters starting with “-”) and finally the argument (often a file, or
directory structure). It’s always command, option then argument.

GETTING RID OF DIRECTORIES


Deleting directories is pretty easy in Linux, along with files, and this can be a problem. It’s too easy to delete entire directories containing
files and these are instantly removed, not sent to a trash directory. Tread carefully.

We’re going to remove one of the directories we To delete a directory containing files or other
STEP 1 STEP 3
created earlier using the “rmdir” command. Enter: ls directories, you return to the “rm” command used to
to view the files and directories in the current directory. We’ll start by remove files, only now we need to use the “-R” option (which stands
getting rid of one of the test directories. Enter: rmdir testdir3 and for “recursive”.) Using “rm –R” removes all the files and directories to
ls again to confirm the directory has been removed. whatever you point it at. Enter: rm -R articles to remove the
articles directory.

Now we’ll try to get rid of the articles directory As with multiple files, you can delete multiple
STEP 2 STEP 4
(containing the reports directory). Enter: rmdir directories inside the same directory using the “rm”
articles and press return. You’ll get an error saying “rmdir: failed to command with the wildcard character (*). This should be done with
remove ‘articles’: Directory not empty”. This is a puzzler; the rmdir care though so use the -I option (which stands for “interactive”). This
command only removes directories that having nothing in them (no will prompt you before each deletion. Enter: rm -Ri test* and
files or other directories). press Y and return to each prompt. It’s a good idea to use the -i
option whenever using the rm command.

www.pclpublications.com 125
Mastering Linux

Copying, Moving and


Renaming Files
Taking command of the Terminal is essential when learning how your Raspberry Pi’s
operating system works. The copying, moving and renaming of files is equally important, as
you’ll be doing a lot of this throughout your Pi projects.

USING THE MOVE COMMAND


In Linux, renaming a file is simply moving it from one name to another and copying a file is moving it without deleting the original. Don’t
panic, it’s quite easy to master.

Before we can move anything around, we need to Enter: mv testfile testdir and press return to
STEP 1 STEP 3
have a few test items in our home directory. Enter: move the testfile document into the testdir directory.
touch testfile and mkdir testdir to create a test file and test Enter: ls to see that it’s no longer in the home directory, and ls
directory in your home directory. Enter: ls to check that they are testdir to see the testfile now sitting in the testdir directory. Now
both present. enter: mkdir newparent to create a new directory.

Files and directories are moved using the mv Directories with files are moved in the same way.
STEP 2 STEP 4
command. This is different to the commands we’ve Enter: mv testdir newparent to move the testdir
looked at so far because it has two arguments (remember Linux directory inside the newparent directory. Let’s move into the directory
command line is command, option, argument). The first argument is to find the file. Enter: cd /newparent/testdir and enter: ls to
the source (the file or directory to be moved) and the second is view the testfile sitting inside the directory.
the destination.

126 Raspberry Pi Coding & Projects


Copying, Moving and Renaming Files

Files and directories can be moved up using the You can also move files using longer paths. Enter:
STEP 5 STEP 6
double dot (“..”) as an argument. Enter: ls –la to cd ~ to return to the home directory and
view your testfile and the single and double dot files. The single dot is mv newparent/testfile newparent/testdir/testfile to
the current directory and the double dot is the parent directory. Enter: move the testfile from its current location back inside the testdir
mv testfile .. to move the testfile up into the newparent directory. Enter: ls newparent/testdir to view the file back in its
directory. Enter: cd .. to move up to the parent directory. current directory.

RENAMING FILES AND DIRECTORIES


The mv command isn’t used just to move files; it also serves the purpose of renaming files (effectively it moves it from its old name to a new
name). Let’s see how to use mv to rename items.

Let’s start by making a new test file called “names”. You can rename directories inside other directories
STEP 1 STEP 3
Enter: touch testfile and then ls to make sure the using paths. Let’s rename the testdir directory, which
testfile is present. We’re going to turn this into a file that contains the is now inside the people directory. Enter: mv names/testdir
names of some people. So let’s call it something more appropriate, names/friends. Now enter: mv names people/friends to move
like “names”. the names file inside the friends directory.

Enter: mv testfile names and ls. Now we can see It is easy to overwrite files using the mv command,
STEP 2 STEP 4
the new “names” file in our directory. The mv so if you have files with the same name use the
command can also be used to rename directories. We should still have “-n” option, which stands for “no overwrite”. Enter: touch
our newparent directory in our home directory. Enter: mv newparent testfile to create a new file and mv -n testfile people/
people to rename the newparent directory. Enter: ls to view it. friends. There’s no error report though, enter: ls and you’ll find
testfile still there.

www.pclpublications.com 127
Mastering Linux

Using the Man Pages


Linux comes with man (manual) pages that explain each command and show you all the
options you can use. Once you get the hang of reading the man pages, you’ll be able to find
and do just about anything in Linux.

HEY, MAN!
The man pages are one of the best features of Linux, and as a built-in tool it’s invaluable for both beginner and senior level Linux
administrators. Let’s see how it works

Linux has a built-in manual, known as man for short. Most commands are pretty easy to figure out how to
STEP 1 STEP 3
Using the man command you can obtain information use, so what you spend most of the time in the man
on all the Linux commands we’ve talked about. Simply enter: man and pages is looking under the Description. Here you will see all the
the name of the command you want to learn more about. Start by options and the letters used to activate them. Most man pages are
entering: man ls in the command line. longer than a single page, so press any key, such as the space bar, to
move to the next page of content.

The man pages are a bit more detailed than you might
STEP 2
be used to. First you have a name, which tells you
what the command is called; in this case “list directory contents” and
then the synopsis shows you how it works. In this case: “ls [OPTION]..
[FILE..]”. So you enter: ls followed by options (such as -la) and the
file or directory to list.

Press the H key while looking at a man page to view


STEP 4
the commands you can use to control the view. This is
called the Summary of Less Commands (the less command is
something we’ll come to when we look at editing text). For now
realise that you can move back and forward with Z and W. Press Q to
quit this help screen and return to the man page.

128 Raspberry Pi Coding & Projects


Using the Man Pages

Scroll to the bottom of the man page to discover more The man command can be used for just about every
STEP 5 STEP 6
information. Typically you will find the author’s name command you use in Linux. You can even enter: man
and information on reporting bugs, including web links that can be man to get information on using the man tool. From now on,
useful for more information. Press Q to exit the man page and return whenever you come across a new command in this book, such as
to the command line. “nano” or “chmod”, take time to enter: man nano or man chmod and
read the instructions.

USING MAN OPTIONS


Because man doesn’t change anything, like mv or mkdir, it is tempting not to see it as a command. But it is, and like all other commands it has
options. These can be very handy to learn.

Entering: man man enables you to view some of the One of the most powerful man options is the -k option,
STEP 1 STEP 3
options, but sometimes you’ll just want a quick which is for “apropos”. This enables you to search a
overview. Fortunately man has a built-in help option that quickly lists wider range of man pages than the exact command. Enter: man -k
the options. Press Q if you’re in a man page and enter: man –h at the directory to view all of the man pages relating to directories “(man
command line. -k directory | less” to view one page at a time). Here you’ll find
commands like “ls”, “mkdir” and “cd” along with their description.

If you’re fast you may have noticed the start of the Entering the man page for all the commands you
STEP 2 STEP 4
text flew up off the page. This is because the “man –h” come across can be a little long-winded, although
option doesn’t use the less command by default (less is what enables ultimately productive. If you simply want to know what a command
you to move down text one screen at a time). We’ll look into pipes (“|”) does you can read just the description using the “whatis” command.
later on, but for now just use “man -h | less” to read long text one page Enter: whatis pwd to read the description of the “pwd” command
at a time. (“print name of current/working directory”).

www.pclpublications.com 129
Mastering Linux

Editing Text Files


A text file in Linux can be anything from a simple set of instructions on how to use an app, to
some complex Python, C++ or other programming language code. Text files can be used for
scripting, automated executable files, as well as configuration files too.

THE JOY OF TEXT


You will come across a lot of text files in Linux and to be able to edit or create a text file, you need a good text editor. Linux has many but
here are some in action on the Raspberry Pi.

The first text editor for the Raspberry Pi is the default Vi is the original Unix command but in this case it
STEP 1 STEP 3
desktop environment app: Leafpad. To use, you can launches VIM, the new Linux version of Vi. Although
either double-click an existing text file or click the Raspberry Pi menu simple looking, Vi is considered, even by today’s standards, to be one
icon (in the top left of the desktop) and from the Accessories menu, of the most widely used text editors, There’s a lot you can do with it,
choose Text Editor. so check out the man pages for more Vi information.

From the Terminal there are even more options, Nano is another favourite, and simple, text editor
STEP 2 STEP 4
although using the correct command, you can launch available for Linux. Enter: nano into the Terminal to
any of the desktop apps via the Terminal. One of the simplest, and a launch it. You can use Nano for editing code, creating scripts or writing
classic text editor that’s carried over from the Unix days, is vi. In the your own help files. To exit Nano, press Ctrl + X, followed by Y to save
Terminal, enter: vi. the file or N to exit without saving.

130 Raspberry Pi Coding & Projects


Editing Text Files

Emacs, or GNU Emacs, is an extensible and Emacs can offer an uncomplicated view of your text
STEP 5 STEP 8
customisable, self-documenting, real-time display file or one with a plethora of information regarding
editor. It’s a fantastic text editor and one that’s worth getting used to the structure of the file in question; it’s up to you to work out your
as soon as you can. Sadly, it’s not installed on the Pi by default, so own preference. There’s also a hidden text adventure in Emacs, which
you’ll need to install it. In the Terminal, enter: we cover later in this book, why not see if you can find it without
sudo apt-get install emacs our help.

The previous command contacts the Debian (Raspbian Gedit is another excellent text editor for Linux. Again,
STEP 6 STEP 9
is based on a Debian Linux distribution) repositories it’s not installed by default on the Raspberry Pi;
and pulls down the information needed to install Emacs. When the Pi however, by entering: sudo apt-get install gedit and
asks to continue with the installation, press Y. This installs the latest accepting the installation, the program can be on the Pi in a matter of
version and when it’s done, you’ll be back to the command prompt. seconds. Once it’s installed, use gedit in the Terminal to launch it.
Gedit is a great text editor for coding.

Once the installation is complete, enter: emacs into Finally, Jed is an Emacs-like, cross-platform text editor
STEP 7 STEP 10
the Terminal. The Emacs splash screen opens in a new that’s lightweight and comes with a wealth of
window, offering a tutorial (which we recommend you run through) features. To install it, enter: sudo apt-get install jed. Accept
and a guided tour amongst other information. the installation and when it’s complete, use: jed to launch.

www.pclpublications.com 131
Mastering Linux

Getting to Know Users


You might think you’re the only person using your Raspberry Pi but there are several different
users and even groups of users. Your main account is normally called Pi and there is an
account above it called root, which is more powerful. You can also create users and groups.

WHAT IS A USER?
An important part of using Linux is the concept of users and understanding which user you are and which group you belong to. Like all
modern computers, you can have multiple user accounts with each having different levels of access.

The first thing you need to do is get a concept of To allow this, you need to use the sudo command.
STEP 1 STEP 3
which user you are. Enter: whoami into the command Sudo loosely stands for Substitute User Do; essentially
line and press return. It should say “pi” (unless you set up your account it’s the highest level of access to the system and you’ve already
name differently during setup). The “whoami” command might seem a installed text editors using sudo. You’ll come across sudo frequently in
bit simplistic, but it comes in very handy sometimes. Linux, so let’s create a second account to get the hang of it. Enter:
sudo useradd -m lucy (or pick your name).

When you are working in Linux, from time to time a Now add a password for the new account. Enter: sudo
STEP 2 STEP 4
‘Permission denied’ error will occur, typically when you passwd lucy and enter: a short password. Retype
try to create, edit or execute (run) a file or directory outside of your the same password and you’ll now have two accounts on your
area of privilege. If you want to see this, enter: mkdir /testdir. Raspberry Pi. Now enter: ls -l /home to view the home directories
Attempting to create a new directory in your root directory for both users. Notice that the lucy directory lists lucy as the owner
isn’t allowed. and group; and pi directory is belongs to pi.

132 Raspberry Pi Coding & Projects


Getting to Know Users

Let’s try switching to our new account. Enter: su We’ll look at permissions in the next tutorial, but for
STEP 5 STEP 6
lucy and enter the password you just created for that now try to create a file as before. Enter: touch
account. Notice that the command line now says “lucy@raspberrypi” testfile to create a file. It will say “touch: cannot touch ‘testfile’:
but the working directory is “still /home/pi” (check this using “pwd”). Permission denied”. This is because your new user account doesn’t
Enter: whoami to confirm that you are now the new user. have the right to create files in the /home/pi directory. Enter: su pi
to switch back to your pi account.

GETTING SUDO
We now have two accounts on our Raspberry Pi: lucy and pi. The lucy account can edit files in /home/lucy and the pi account can edit files in /
home/pi. But there’s also a third account, called “root”, that sits above both lucy and pi. It can edit files anywhere.

The root account is all-powerful. It is possible, but not It’s rare that you use sudo to substitute another user. If
STEP 1 STEP 3
recommended, to switch to the root account, although you don’t specify a user using the “-“u option with a
you’ll need to give it a password first (using “sudo passwd root”). Then username it defaults to the root account, as if you’d typed “sudo -u
just type “su” to switch to root. Please don’t do this though: root”. Enter: sudo touch /home/lucy/anothertestfile to
knowledge is a good thing but it’s safer and wiser to use sudo instead. create a file in the lucy directory while still using the pi account.

This step is optional. Only the pi user can use sudo. If


STEP 4
we want to give the lucy account sudo privileges, it
needs to be added to the sudoers file. Enter: sudo visudo to view
the sudoers file. Add lucy ALL=(ALL) NOPASSWD: ALL to the last
line and use Control+O to output the file. Remove the “.tmp” that is
Most people think sudo stands for “super user”, but it added to the file name as a security measure. Note that most accounts
STEP 2 are not added to the sudoers file as a matter of course.
stands for “substitute user do”. It enables you to
perform a command as another user. Enter: sudo -u lucy touch /
home/lucy/test to create a file inside the lucy home directory. You
won’t get an error because the lucy user has permission to edit
that directory.

www.pclpublications.com 133
Mastering Linux

Ownership and
Permissions
Once you’ve got the hang of users, you need to learn about ownership and permissions.
Different users have different areas of ownership and can do different things with each file.
Permissions in Linux can be quite complex but with careful thought it’s not too difficult.

OWNER AND PRIVILEGE


Each user account in Linux is an owner of a section of the filesystem: their Home area. Within this area, they do what they like (within
reason), as they have owner privileges. Elsewhere though, they usually just have read-only privileges.

If you followed the previous tutorial you should now The first letter in the permissions also indicates a
STEP 1 STEP 3
have two accounts on your Raspberry Pi. One called directory or file. Notice that all the other files start
“pi” and the other with a name (Lucy in our case). An essential aspect with a ‘d’ and our textfile.txt file starts with a ‘-’. That’s what the first
of Linux is the idea of file and directory ownership; who owns, and has letter means. It’s either a ‘d’, in which case it’s a directory, or a ‘-’, in
access, to what. You need a test file so enter: touch testfile. which case it’s not; it’s a file. Enter: ls -l testfile.txt to view the
permissions for just this file.

Now enter: ls –l and let’s have a good look at the


STEP 2
default permissions file. Our testfile.txt files starts
with the text “-rw-r--r—“. Start with the first letter, which is a dash ‘-’.
All the other items in our home directory are directories. You can tell
because they are blue, and our testfile.txt file is white.

The next nine letters of the permissions are known as


STEP 4
“alpha notation” because they let you know the
permissions using letters. Each permission is either on, in which case
you see a letter, or it is off, in which case you see a dash. The letter
doesn’t change for each place. So the first permission - the second
letter after the directory one - is either an ‘r’ or a ‘-’. It’s never any
other letter.

134 Raspberry Pi Coding & Projects


Ownership and Permissions

The ‘r’ means that particular permission is read and it’s The presence of r, w, or x means that this aspect is
STEP 5 STEP 6
set to On. The nine letters here are divided into three possible, a dash means it isn’t. Our testfile.txt has no x
groups of three letters: r, w, x. They stand for read, write and execute letter; so if it were a script it wouldn’t run. So why are there so many
(run). Read means the file can be viewed (using cat or nano); w means letters? Why not just three; read, write and execute? The three blocks
the file can be edited or moved, and x means the file - typically a script of three letters are for different sets of people: user, group and other.
or program - can be run.

CHANGING PERMISSIONS
Now that you know how groups of permissions work, it’s time to look at how to change them.

The first block of three is the most important. This is Turning everything on is probably overkill, so you need
STEP 1 STEP 3
the user who owns the file (typically pi); the second is to target each group. Do this by putting commas
for other people in the same group as the user, and the third is for between each mode option. Enter: chmod u=rwx,g=rw,o=r
other people on the system. Permissions are changed using the testfile.txt to give users read, write and execute privileges, user
chmod (change file mode bit) command. Enter: man chmod to look at read and write and other just read. Enter:
the manual. ls –l to see your handiwork.

Alpha notation is fine, but many Linux admins use


STEP 4
octal notation instead. This is a three-digit number
The chmod command is one of the trickier ones to that represents permissions. This is the formula: read=4, write=2 and
STEP 2 execute=1 and you add them up for each group, therefore if a group is
understand. There are two ways you can adjust
permissions; the first is using chmod with an option to target one of read, write and execute it’s 7, if it’s read and write it’s 6 or if it’s just
the three groups: owner, group, other. For these you use u, g or o execute it’s 1. A popular option is 755. Enter: chmod 755 testfile.
followed by = and the letters or dashes you want. So enter: chmod txt to change the file using octal notation.
ugo=rx testfile.txt to make all three groups read, write
and execute.

www.pclpublications.com 135
Mastering Linux

Useful System and


Disk Commands
Understanding these core Linux commands will enable you to not only master the inner
workings of your Raspberry Pi but also to transfer those skills to other Linux distros, such as
Ubuntu or Linux Mint.

LOTS OF LINUX
Linux is a huge and versatile command line language and there are hundreds of commands you can learn and use. Here are a few that can
help you get more from your Raspberry Pi.

The Raspberry Pi is a great little computer, so let’s Enter: uname to view the name of the operating
STEP 1 STEP 3
start by getting some information. Enter: cat / system’s kernel, this is the element that sits between
proc/cpuinfo to view some details on your Raspberry Pi processors. the interface and hardware. Just as you would suspect, the response
If you have a Raspberry Pi 3 you will see four processors, along with from the command is Linux, as Raspbian is a Linux distro, which in
the model name and other info. itself is based on another Linux distro called Debian. While it may
sound complicated, it actually demonstrates how versatile Linux is.

Enter: uname –a to view some more detailed


STEP 2 STEP 4
information. Here you’ll see the kernel name,
Remember that cat is hostname and kernel version (3.18.7-v7 on ours). If you have a
used to list the Raspberry Pi 2 you’ll see SMP (symmetric multiprocessing),
contents of a text file, followed by the system date, CPU architecture and operating
which is what cpuinfo system (GNU/Linux).
is. There are other text
files with system info
available. Try “cat /
proc/meminfo” to get
information about your
memory, “cat /proc/
partitions” for
information about your
SD card, and “cat /proc/
version” shows which
version of Raspberry Pi
you are using.

136 Raspberry Pi Coding & Projects


Useful System and Disk Commands

Enter: vcgencmd measure_temp to view the current One command you might be wondering about is how
STEP 5 STEP 6
operating system temperature of your Raspberry Pi. to switch off or restart your Raspberry Pi from the
Enter: vcgencmd get_mem arm to view the RAM available, and command line. Don’t just hit the power switch. Enter: sudo
vcgencmd get_mem gpu to view the memory available to the showdown –h now to shut down the Raspberry Pi (the “-h” option
graphics chip. Finally try ls usb to view a list of attached USB devices. stands for “halt”), or enter: sudo shutdown –r now to restart your
Raspberry Pi.

DISK COMMANDS
Learn the two commands that enable you to view your disk space and the files on it: df (disk free space) and du (disk usage). With these two
commands you can view the file usage on your SD card.

Start by entering: df in the command line. It returns a Now enter: du. You should see lots of text fly up the
STEP 1 STEP 3
list of the volumes contained on your SD card. You screen. This is the disk usage for the files contained in
might be wondering what a volume is. It’s best to think of your SD card your home directory and their sub-directories. As with df, it is better to
as the drive. This contains partitions, which is where you split one drive use du with the “-h” option to humanise the output. If you want to
to act like two or more drives. And each partition can contain volumes, slow down the output, you’ll also need to pipe it through less. Enter:
which are storage spaces. df -h | less to view the files and their respective usage one page
at a time.

Enter: df –h to get the list in human readable form. You don’t typically enter: du on its own; most of the
STEP 2 STEP 4
The first two lines should read “rootfs” and “/dev/ time you want to view the disk usage of a specific
root” and have matching Size, Used, Avail and Use% listings. This is the directory. Enter: du -h python_games to view how much space the
main drive, and is an indication of how much space you have used, and python_games directory (installed alongside Raspbian) takes up. It
have free, on your Raspbian OS. The other volumes are for booting should be 1.8M. If you want a more comprehensive breakdown of the
and initialising devices (you can ignore these for now). files contained, use the “-a” option (all). Enter: du -ha python_
games to view all the files contained and their disk usage.

www.pclpublications.com 137
Mastering Linux

Managing Programs
and Processes
Being able to effectively manage the active programs and processes on your Raspberry
Pi allows you to change the way the systems work. If you have a project requiring more
memory, you can kill a process to free up the available system resources.

PROGRAMS AND PROCESSES


Linux has a trick up its sleeve when it comes to being able to manage programs and processes. When Windows closes a program, the
allocated memory often isn’t freed up again. However, Linux is far more streamlined.

As you get If you type in “ps” on its own you don’t see much. You
STEP 1 STEP 3
into Linux should see two items: bash and ps. Bash (Bourne
you’ll start to hear more Again Shell) is the command line environment you are typing in, and ps
about processes and is the command you just entered. If that seems a little light, that’s
another thing called the because it is. These are just the processes owned by the user and are
“kernel”. The kernel sits running in the foreground.
beneath the software and
hardware. It passes
instructions to the
hardware running
processes, which takes up
memory, and when the
process is finished it
closes it and reclaims
the memory.

If you want
STEP 4
to see
processes used by other
users (including those
started by root) enter: ps
You’re probably used to thinking in terms of programs –a. The option stands for
STEP 2
and most OS’s tend to keep processes out of sight. In all users. This still isn’t
Linux on the other hand, you’re right in at the deep end. A process is everything though
like a program, only it’s a single task running on your computer. because it doesn’t include
Programs as you know them, may be a single process, or multiple background processes. For
processes working together. In Linux, you should learn to manage this you can enter either
processes. This is done using the “ps” (process status) command. “ps –A” or “ps –e”. This will
show you every process on
the system including the
background processes. You
may need to pipe it
through less using
“ps -e | less”.

138 Raspberry Pi Coding & Projects


Managing Programs and Processes

The ps The “ps aux” command displays the processes in


STEP 5 STEP 6
command is columns. The first is the User followed by the Process
one of the oldest known, and ID (PID), then we see the percentage of CPU and memory.
it has a lot of legacy. Because
of this, it also has alternative
options that can be used
without the dash at the start.
The most common way to
use ps is to enter: ps aux.
Piping this command
through less is the best way
to go about using ps. Enter:
ps aux | less to view
your processes.

VIEWING AND QUITTING PROCESSES


Now that you’ve got a handle on processes, you need to know what to do with them. You can view processes running in real-time, and quit
ones that you no longer need, or those that are problematic.

While ps is a great tool for checking all the processes Now that you’ve got an idea of what processes are,
STEP 1 STEP 3
on your Raspberry Pi, sometimes you need to view how do you go about stopping them? Some processes
them in real-time. In particular you may want to check the CPU and run in the foreground until you quit them. Enter: ping www.google.
memory usage of processes and see if any process is hogging all your com and you’ll start a ping process continuously contacting Google.
computer’s resources. Use “top” to do this. This sort of process runs until you press Control+C.

Top fills the display with processes and it fits as many Processes are stopped using the kill command. Enter:
STEP 2 STEP 4
as it can on one screen. These run in real-time so as sleep 100 & to create a dummy process. Enter:
you watch, the display items will move up and down according to their pgrep sleep to find its PID number (on ours it is 2192). Now enter:
usage. You can interact with top as it is running: use < and > to change kill 2192 and the sleep process will be stopped. You can also use
the sort column. Press H to view a help page with all the commands pkill sleep if you’re sure you know the process name.
you can use.

www.pclpublications.com 139
Mastering Linux

Input, Output and Pipes


Most operating systems allow you to direct the output of something on the screen to, for
example, a file. Linux, with its ancestral history of Unix-like command-based arguments,
goes a step further and offers much more control.

IN, OUT, LINUX ALL ABOUT


Everything on a computer is about input and output. You input things into the computer (press keys, move the mouse) and it makes
calculations and outputs content (changes the display, makes a noise, for example).

When you enter commands into Linux (in the You can change the standard output to something
STEP 1 STEP 3
command line), you are using standard input and else using the “>” character after your command. If we
output. This is so obvious that most people don’t even think about it. wanted to see all the items in the python_games directory we could
You enter commands using the keyboard (that’s input) and it responds use “ls -l python_games”. Using “ls -l python_games > games.txt”
to the screen (output). This is the regular way of doing it, which is why outputs the list of items to a new text file called “games.txt”.
it’s “standard input and output” (often called “stdin” and “stdout”
for short).

The games.txt file now contains the output from the ls


STEP 4
command. You can check it using “nano games.txt”.
It’s an editable text file containing all the permissions, user and file
size information and the names of the files. The output from the ls -l
command, normally displayed on the screen, was instead sent to this
file. Press Control+X to quit nano.

As far as the computer is concerned, input and output


STEP 2
can be to and from a whole range of different sources
that you might never even think about. A program can get input from
other programs, from files stored on the hard drive and a whole host
of other areas. It outputs back to the display line, but also to files,
other programs and even other commands.

140 Raspberry Pi Coding & Projects


Input, Output and Pipes

So > enables you to output to files, but you can also We’re going to use this text file as input to the sort
STEP 5 STEP 6
get input from a file. Make a new directory called command. Enter: sort < bands.txt and the
music (“mkdir music”) and switch to it (“cd music”). Enter: nano content from the text file is used as input to sort. Because the output
bands.txt to create a new text file. Enter some band names and isn’t specified, it uses the standard output (the screen) but you use
press Control+O to output the file. Press Control+X to quit nano. input and output together. Enter: sort < bands.txt > bands_
sorted.txt to create a new file with the band names in order to
switch back to your pi account.

USING PIPES
As well as directing input and output to and from files, you can send the output from one command directly into another. This is known as
piping, and uses the pipe character “|”.

As you start to get more advanced in Linux, you You can pipe commands multiple times. Enter: cat
STEP 1 STEP 3
begin to create more powerful commands, and bands.txt | sort | grep The* to get the bands
one way you do this is by using the pipe character (“|”). Take starting with “The” in alphabetical order. The output of the text from
some time to find this character if you haven’t already: it usually the bands.txt document is passed into sort, and the output from sort is
sits above or to the left of the Return key on most keyboards. passed into grep which filters out the bands starting with “The”. These
bands form the output.

We’ve used the pipe a few times in the book (“ps aux | You can combine pipes with input and output to create
STEP 2 STEP 4
less”), but you might not have understood what’s complex expressions. You can also use >> to append
actually happening. Enter: cat bands.txt | wc. The output from outputted data to a file that already exists. Enter: cat bands.txt |
the cat command (the text inside the document) isn’t displayed on the wc >> bands.txt. This takes the output from the bands.txt file and
screen, instead it is piped into the wc (word count) function. This then pipes it into the wc (word count) function. The output from wc is
tells us how many lines, words and characters are in the document. appended to the end of the bands.txt file. Enter: cat bands.txt to
view it.

www.pclpublications.com 141
Mastering Linux

Fun Things to Do in
the Terminal
Despite the seriousness of an operating system, the Linux community are certainly no
strangers to a bit of fun. Over the years, the developers have created and inserted all manner
of quirky and entertaining elements into the Terminal.

TERMINAL FUN
All these commands are Linux-based, so not only can you use them on the Raspberry Pi but also on any of the Debian-based
Linux distributions.

The first command we’re going to use is sl, it’s not If you’ve ever fancied having the computer read a
STEP 1 STEP 3
installed by default so enter: sudo apt-get random fortune out to you then you’re in luck.
install sl. The command can be run with sl and when executed Raspbian requires you to install the Terminal app, Fortune, first. Enter:
displays a Steam Locomotive travelling across the screen (hence ‘sl’). sudo apt-get install fortune, then simply enter: fortune,
Entering: LS (note the upper case) also works. into the Terminal to see what comes up.

Fans of Star Wars even get a fix when it comes to the The rev command is certainly interesting, and at first
STEP 2 STEP 4
Terminal. By linking to a remote server via the telnet what seems a quite useless addition to the OS can,
command, you can watch Episode IV: A New Hope being played out, however, be used to create some seemingly unbreakable passwords.
albeit in ASCII. To view this spectacle, enter: sudo apt-get Enter: rev and then type some text. Then press Enter and everything
install telnet, followed by: you typed in is reversed. Press Ctrl+C to exit.
telnet towel.blinkenlights.nl

142 Raspberry Pi Coding & Projects


Fun Things to Do in the Terminal

If you’re stuck trying to work out all the possible If you really want to expand the whole cow thing, for
STEP 5 STEP 8
factors for any particular number, simply enter: whatever reason, then pipe the fortune command
factor followed by the number. For example, factor 7 doesn’t offer through it, with: fortune | cowsay; and for the graphical cow
much output, whereas factor 60 displays more. equivalent: fortune | xcowsay. Plus, there’s always cowthink. Try:
cowthink ...This book is awesome.

There’s a fine line between the rather cool and the Admittedly, the command ‘toilet’ doesn’t inspire much
STEP 6 STEP 9
really quite weird. Having an ASCII cow repeat text to confidence. However, it’s not as bad as it first sounds.
you could potentially fall into the latter. Start by installing cowsay: Start by installing it with: sudo apt-get install toilet, then
sudo apt-get install cowsay, then enter: cowsay Raspberry when it’s installed, type something along the lines of: toilet David;
Pi is Ace!. In fact, you can even output the ls command through or perhaps list the contents of the current folder through it, with: ls
the cow, by entering: ls | cowsay. | toilet.

To further the cow element, there’s even a graphical, Expanding the toilet command, you can actually
STEP 7 STEP 10
i.e. non-Terminal, cow available. Install it with: sudo generate some decent looking graphics through it. For
apt-get install xcowsay, then when it’s installed enter example, try this: toilet -f mono12 -F metal David. You can
something similar to cowsay, such as: xcowsay BDM Publications enter: toilet --help, for a list of the command line arguments to
are ace!. expand further.

www.pclpublications.com 143
Mastering Linux

More Fun Things to Do in


the Terminal
If the previous list of bizarre, and fun things to do in the Terminal has you wanting more,
you’re in luck. We’ve put together another batch of both useful, and not so useful, commands
for you to try out.

MORE FUN, YAY


Since the Terminal session is already open, and your keyboard digits are nicely warmed up, here are another two pages of
Terminal nonsense.

Remember the old ZX Spectrum days of computing, Having a little white cat chase your mouse pointer
STEP 1 STEP 3
when you could type in 10 print “Hello”, 20 goto 10 around the desktop may sound like a terrible waste of
and Hello would list down the screen? Well, in Raspbian you can do the time. Oddly though, it isn’t. Enter: sudo apt-get install oneko,
same. Simply enter: yes followed by some text, i.e. yes Raspberry then type: oneko to have the cat appear. Move your ‘mouse’ cursor
Pi is ace. It keeps going until you press Ctrl+C. around the screen and the cat chases it. Use Ctrl+C to exit the action.

The Matrix was one of the most visually copied films This entry is a little more serious than the previous.
STEP 2 STEP 4
ever released and there’s even a version of the Matrix Fork Bomb is a command that continually replicates
code available for Linux. Install it with: sudo apt-get install itself until it has used up all the available system resources, eventually
cmatrix. When it’s done enter: cmatrix and follow the white rabbit, causing your computer to crash. You don’t have to try it, but it’s
Neo. Unlike the real Matrix though, you can press Ctrl+C to exit. interesting nonetheless. Simply enter: :(){ :|:& }: and be
prepared to reboot.

144 Raspberry Pi Coding & Projects


More Fun Things to Do in the Terminal

Stringing several commands and piping them through Used as a music demo from the old Amiga and DOS
STEP 5 STEP 8
other commands is what makes scripting such a days, the bb command evokes memories of three and
powerful element to an OS. For example, using the while command, a half inch floppies crammed with all manner of demo scene goodies.
together with toilet, can yield some impressive results. Enter: while You’ve already installed bb from the previous step, so just enter: bb.
true; do echo “$(date ‘+%D %T’ | toilet -f term -F Follow the onscreen instructions and turn up your volume.
border --metal)”; sleep 1; done.

This entry is in two parts. First you need to get hold of


STEP 9
the necessary packages: sudo apt-get install libcurses-
perl. When that’s done enter: cd Downloads/ && wget http://
search.cpan.org/CPAN/authors/id/K/KB/KBAUCOM/
Talking computers were the craze of the ‘80s. To
STEP 6 Term-Animation-2.4.tar.gz && tar -xf Term-Animation-
re-live the fun enter: sudo apt-get install 2.4.tar.gz && cd Term-Animation-2.4/. Followed by: perl
espeak, then: espeak “This is a Raspberry Pi” to have the Makefile.PL && make && make test && sudo make install.
computer repeat the text inside the quotes to you. Make sure your
volume is turned up and try the following: ls > folders.txt &&
espeak -f folders.txt. This gets Raspbian to read back the
contents of the ls command.

A roaring ASCII fire isn’t the most useful command to With that little lot completed, onto the next part.
STEP 7 STEP 10
have at your disposal but it’s fun. Install it with: sudo Enter: cd .. && wget http://www.robobunny.
apt-get install libaa-bin, then use: aafire. It’s not exactly com/projects/asciiquarium/asciiquarium.tar.gz && tar
warming but you get the idea. To expand the above, enter: sudo -xf asciiquarium.tar.gz && cd asciiquarium_1.1/ &&
apt-get install bb caca-utils, then: cacafire. chmod +x asciiquarium. Providing all went well, enter: ./
asciiquarium and enjoy your very own ASCII-based aquarium.

www.pclpublications.com 145
Mastering Linux

Linux Tips and Tricks


The Linux Terminal, you’ll no doubt agree, is an exceptional environment and with a few
extra apps installed along with a smidgen of command knowledge, incredible and often
quite strange things can be accomplished.

TAKING COMMAND
There are countless Linux tips, secrets, hacks and tricks out there. Some are very old, originating from Linux’s Unix heritage, while
others are recent additions to Linux lore. Here are our ten favourite tips and tricks.

Emacs text editor, is a great piece of software Ever fancied being able to browse
EASTER EGGS TERMINAL BROWSING
but did you know it also contains a hidden the Internet from the Terminal?
Easter Egg? With Emacs installed (sudo apt-get install emacs24), drop While not particularly useful, it is a fascinating thing to behold. To do
to a Terminal session and enter: so, enter:
emacs -batch -l dunnet sudo apt-get install elinks
Dunnet is a text adventure written by Ron Schnell in 1982, and hidden Then:
in Emacs since 1994. elinks
Enter the website you want to visit.

Based on the classic 1982 arcade game, Moon Snowing in the Terminal console isn’t something
MOON BUGGY LET IT SNOW
Patrol, Moon Buggy appeared on home you come across every day. If you’re interested,
computers in 1985 amid much praise. It’s a cracking Atari game however, enter:
available in the Linux Terminal by entering: wget
sudo apt-get install moon-buggy
https://gist.githubusercontent.com/sontek/1505483/ra
Then:
w/7d024716ea57e69fb52632fee09f42753361c4a2/snowjob.
moon-buggy
sh
Enjoy.
chmod +x snowjob.sh
./snowjob.sh

146 Raspberry Pi Coding & Projects


Linux Tips and Tricks

If you need to see which apps are consuming Back in the days of dial-up connections, the online world was
MEMORY HOGS BBS
the most memory on your Raspberry Pi, made up of Bulletin Board Systems. These remote servers
simply enter: provided hangouts for users to chat, swap code, play games and more.
ps aux | sort -rnk 4 Using telnet in Linux, we can still connect to some active BBSes. First,
This sorts the output by system memory use. install Telnet with:
sudo apt-get install telnet
Then:
telnet amigacity.xyz
You will be connected to a BBS dedicated to the Commodore Amiga.
There’s plenty more, which you can find at www.telnetbbsguide.com.

When you delete a file, there’s still a chance of


SHREDDER
someone with the right software being able to
retrieve it. However, files can be securely and permanently deleted
using Shred:
shred -zvu NAMEOFFILE.txt
Replace NAMEOFFILE with the name of the file to delete.
If you want to create an entire directory
DIRECTORY TREES
(or folder) tree with a single command,
you can use:
mkdir -p New-Dir/{subfolder1,subfolder2,subfolder3,s
ubfolder4}
This creates a New-Dir with four sub folders within.

ASCII art can be quite striking when applied to some


ASCII ART
images. However, it’s often difficult to get just right.
You can create some great ASCII art from the images you already have
on the Raspberry Pi by using img2txt:
img2txt NAMEOFIMAGEFILE.png
Replace NAMEOFIMAGEFILE with the actual name of the image file on
your system.
It’s not easy trying to
FORGOTTEN COMMANDS
remember all the available
Linux commands. Thankfully, you can use apropos to help. Simply use
it with a description of the command:
apropos “copy files”
apropos “rename files”

www.pclpublications.com 147
Mastering Linux

Command Line
Quick Reference
When you start using Linux full time, you will quickly realise that the graphical interfaces of
Ubuntu, Mint, etc. are great for many tasks but not great for all tasks. Understanding how to
use the command line not only builds your understanding of Linux but also improves your
knowledge of coding and programming in general. Our command line quick reference guide
is designed to help you master Linux quicker.

TOP 10 COMMANDS
These may not be the most common commands used by everyone but they will certainly feature frequently for many users of Linux
and the command line.

The ‘cd’ command is one of the commands you will The ‘mv’ command moves a file to a different
use the most at the command line in Linux. It allows location or renames a file. For example mv file
cd mv
you to change your working directory. You use it sub renames the original file to sub. mv sub ~/
to move around within the hierarchy of your file Desktop moves the file ‘sub’ to your desktop
system. You can also use chdir. directory but does not rename it. You must specify a
new filename to rename a file.

The ‘ls’ command shows you the files in The ‘chown’ command changes the user and/or
your current directory. Used with certain options, it group ownership of each given file. If only an owner
ls chown
lets you see file sizes, when files where created and (a user name or numeric user ID) is given, that user
file permissions. For example, ls ~ shows you the is made the owner of each given file, and the files’
files that are in your home directory. group is not changed.

The ‘cp’ command is used to make copies of files and The ‘chmod’ command changes the permissions
directories. For example, cp file sub makes an on the files listed. Permissions are based on a fairly
cp chmod
exact copy of the file whose name you entered and simple model. You can set permissions for user,
names the copy sub but the first file will still exist group and world and you can set whether each can
with its original name. read, write and or execute the file.

The ‘pwd’ command prints the full pathname of The ‘rm’ command removes (deletes) files or
the current working directory (pwd stands for directories. The removal process unlinks a filename
pwd rm
“print working directory”). Note that the GNOME in a filesystem from data on the storage device
terminal also displays this information in the title and marks that space as usable by future writes. In
bar of its window. other words, removing files increases the amount of
available space on your disk.

The ‘clear’ command clears your screen if this Short for “make directory”, ‘mkdir’ is used to create
is possible. It looks in the environment for the directories on a file system, if the specified directory
clear mkdir
terminal type and then in the terminfo database does not already exist. For example, mkdir work
to figure out how to clear the screen. This is creates a work directory. More than one directory
equivalent to typing Control-L when using the may be specified when calling mkdir.
bash shell.

148 Raspberry Pi Coding & Projects


Command Line Quick Reference

~ $ .\Commonly_Used_Commands\

USEFUL HELP/INFO COMMANDS


The following commands are useful for when
you are trying to learn more about the system or
program you are working with in Linux. You might
not need them every day, but when you do, they
will be invaluable.

The ‘free’ command displays the total amount The ‘sed’ command opens a stream editor.
of free and used physical and swap memory in A stream editor is used to perform text
free sed
the system. For example, free -m gives the transformations on an input stream: a file or input
information using megabytes. from a pipeline.

The ‘df’ command displays filesystem disk The ‘adduser ‘command adds a new user to the
space usage for all partitions. The command system. Similarly, the addgroup command adds a
df adduser
df-h is probably the most useful (the -h new group to the system.
means human-readable).

The ‘top’ program provides a dynamic real- The ‘deluser’ command removes a user
time view of a running system. It can display from the system. To remove the user’s files
top deluser
system summary information, as well as a list and home directory, you need to add the
of processes. -remove-home option.

The ‘uname’ command with the -a option prints The ‘delgroup’ command removes a group from
all system information, including machine name, the system. You cannot remove a group that is the
uname delgroup
kernel name, version and a few other details. primary group of any users.

The ‘ps’ command allows you to view all the The ‘man man’ command brings up the manual
processes running on the machine. Every operating man entry for the man command, which is a great place
ps
system’s version of ps is slightly different but all do man to start when using it.
the same thing.

The ‘grep’ command allows you to search inside a The ‘man intro’ command is especially useful. It
number of files for a particular search pattern and man displays the Introduction to User Commands,
grep
then print matching lines. An example would be: intro which is a well written, fairly brief introduction to
grep blah file. the Linux command line.

www.pclpublications.com 149
Mastering Linux

A-Z of Linux Commands


There are literally thousands of Linux commands, so while this is not a complete A-Z, it does
contain many of the commands you will most likely need. You will probably find that you end
up using a smaller set of commands over and over again but having an overall knowledge is
still very useful.

Search file(s) for lines that

A
adduser Add a new user
dd

diff
Data Dump, convert and
copy a file
Display the differences
between two files
grep

groups
match a given pattern
Print group names a user
is in
arch Print machine dirname Convert a full path name gzip Compress or decompress
architecture to just a path named file(s)
awk Find and replace text du Estimate file space usage
within file(s)

E H
B
bc An arbitrary precision
echo Display message on
screen
head

hostname
Output the first part of
file(s)
Print or set system name
calculator language ed A line oriented text editor

C egrep
(edlin)
Search file(s) for lines
that match an extended
I
id Print user and group ids
cat Concatenate files and expression
print on the standard info Help info
env Display, set or remove
output environment variables install Copy files and set
chdir Change working attributes
expand Convert tabs to spaces
directory
chgrp

chroot
Change the group
ownership of files
Change root directory
expr

F
Evaluate expressions
J
join Join lines on a common
field
cksum Print CRC checksum and factor Print prime factors

cmp
comm
byte counts
Compare two files
Compare two sorted files
line by line
fdisk

fgrep
Partition table
manipulator for Linux
Search file(s) for lines
K
kill Stop a process from
that match a fixed string running
cp Copy one or more files to find Search for files that meet

crontab
another location
Schedule a command to
run at a later time
fmt
a desired criteria
Reformat paragraph
text
L
less Display output one
csplit Split a file into context- fold Wrap text to fit a screen at a time
determined pieces specified width
ln Make links between files
cut Divide a file into several format Format disks or tapes
locate Find files
parts
fsck Filesystem consistency
logname Print current login name

D
date Display or change the G
check and repair
lpc

lpr
Line printer control
program
Off line print
date & time gawk Find and Replace text lprm Remove jobs from the
dc Desk calculator within file(s) print queue

150 Raspberry Pi Coding & Projects


A-Z of Linux Commands

M
man See Help manual
S
screen Terminal window manager
V
vdir Verbosely list directory
contents (`ls -l -b’)
mkdir Create new folder(s) sdiff Merge two files interactively
mkfifo

mknod
Make FIFOs (named
pipes)
Make block or character
special files
select
seq
shutdown
Accept keyboard input
Print numeric sequences
Shutdown or restart
W
watch Execute or display a
Linux program periodically
more Display output one
sleep Delay for a specified time wc Print byte, word, and
screen at a time line counts
sort Sort text files
mount Mount a file system whereis Report all known
split Split a file into fixed-size
instances of a

N
nice Set the priority of a
su
sum
pieces
Substitute user identity
Print a checksum for a file
which
command
Locate a program file
in the user’s path
command or job symlink Make a new name for a file who Print all usernames
nl Number lines and write currently logged in
sync Synchronise data on disk
files with memory whoami Print the current user
nohup Run a command immune id and name
to hangups
T X
P
passwd Modify a user password
tac

tail
Concatenate and write
files in reverse
Output the last part of
xargs Execute utility, passing
constructed argument
list(s)
paste Merge lines of files files
pathchk

pr
Check file name
portability
Convert text files for
tar
tee
Tape Archiver
Redirect output to
multiple files
Y
yes Print a string until
printing interrupted
test Evaluate a conditional
printcap Printer capability expression
database
time Measure Program
printenv Print environment Resource Use
variables
touch Change file timestamps
printf Format and print data
top List processes running on

Q
quota Display disk usage and
traceroute
tr
the system
Trace Route to Host
Translate, squeeze and or
delete characters
limits
tsort Topological sort
quotacheck Scan a file system for disk

quotactl
usage
Set disk quotas
U
R
ram Ram disk device
umount
unexpand
uniq
Unmount a device
Convert spaces to tabs
Uniquify files
rcp Copy files between two units Convert units from one
machines scale to another
rm Remove files unshar Unpack shell archive
scripts
rmdir Remove folder(s)
useradd Create new user account
rpm Remote Package
Manager usermod Modify user account
rsync Remote file copy users List users currently
(synchronise file trees) logged in

www.pclpublications.com 151
Pi Projects

152 Raspberry Pi Coding & Projects


Pi Projects INDEX

Pi Projects
The Raspberry Pi is all about projects. We’ve seen the Pi attached to a
satellite taking high-resolution images of the Earth, as well as by scientists
monitoring habitats in some of the most extreme places on the planet. And
enthusiasts the world over have used a Raspberry Pi as the driving force of
their unique projects.
Want to use the Pi to see where the International Space Station is? How
about creating a retro gaming system, or a media centre, or even connecting
to a Bulletin Board System? You’ll find these projects and more in this section.
Where next is up to you. Let your imagination fly with the Raspberry Pi.

154 Creating a Loading Screen 168 Stream Digital TV with a HAT - Part 2
156 Tracking the ISS 170 Pi Projects: Desktop Pi
with Python 172 Pi Projects: Retro Gaming
160 Text Animations 174 Pi Projects: Media Centre
162 Retro Coding 176 Pi Projects: BBS Client
164 Using Text Files for Animation 178 Pi Projects: Weather Station
166 Stream Digital TV with a HAT - Part 1 180 Common Raspberry Pi Problems

156 Tracking
ISS with
the
172 Pi Projects:
Retro
Python Gaming
NASA, among other The Raspberry Pi
agencies, uses a makes for an amazing
wealth of Python code retro gaming computer.
onboard the ISS.

www.pclpublications.com 153
Pi Projects

Creating a Loading Screen


If you’re looking to add a little something extra to your Python code, then consider including a
loading screen. The loading screen is a short introduction, or piece of art, that appears before the
main part of your code.

LOAD”” THE CODE


Back in the 80s, in the 8-bit Launch Python and enter the following code to a New File:
home computing era, import os
loading screens were
import time
often used to display the
cover of a game as it
loaded from tape. The def loading_screen(seconds):
image would load itself screens=open(“screens.txt”, ‘r’)
in, usually one-line-at-
for lines in screens:
a-time, then proceed
to colour itself in print(lines, end=’’)
while the loading time.sleep(seconds)
raster bars danced screens.close()
around in the borders of the screen.
Loading screens were a part of
#Main Code Start
the package and often the buy-in
for the whole game as an experience. Some loading screens os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
featured animations, or a countdown for time remaining as the loading_screen(.5)
game loads, while others even went so far as to include some
kind of playable game. The point being: a loading screen is not
print (“\nYour code begins here...”)
just an artistic part of computing history, but an introduction to
the program that’s about to be run.
While these days loading screens may no longer be with us, in
terms of modern gaming we can still include them in our own
Python content. Either just for fun, or to add a little retro-
themed spice to the mix.

SCREEN$
Creating a loading screen in Python is remarkably easy. You have
several options to hand: you can create a tkinter window and
display an image, followed by a brief pause, before starting your
main code, or you could opt for a console-based ASCII art version
that loads one-line-at-a-time. Let’s look at the latter and see how
it works. The code is quite simple: import the OS and Time modules and then
create a Python function called loading_screen with a (seconds)
First you’ll need some ASCII art, you can look up plenty of
option. Within the function, open the text file with the ASCII art as
examples online, or use an image to ASCII Art converter to
read-only and create a For loop that’ll read the text file one-line-
transform any images you have to ASCII. When you have your ASCII
at-a-time. Next, print the lines – incidentally, the lines, end=’’
art, drop it into a newly created folder inside a normal text file.
element will strip the newline from the text document, without it
you’ll end up with a double-line spaced display. Include the timing
in seconds and close the text file buffer.
The final part of the code, #Main Code Start, is where you’ll
clear the screen (CLS for Windows, Clear for Linux (Raspberry
Pi) and macOS) and call the function, together with the output
number of seconds to wait for each line to be written to the
Save the file, call it screens.txt for now. screen – in this case, .5 of a second.

154 Raspberry Pi Coding & Projects


Creating a Loading Screen

COMBINING THE TWO


How about combining the two elements we’ve looked at? Let’s
begin with a Loading… progress bar, followed by the loading
screen. After that, you can include your own code and continue
Save the code as screens.py, drop into a Command Prompt or your program. Here’s the code:
Terminal and execute it. The screen will clear and your ASCII art import os
inside the text file will load in line-by-line, creating a loading
import time
screen effect.

def loading_bar(seconds):
LOADING…
for loading in range(0,seconds+1):
Another favourite introduction screen is that of a simple loading
animation, where the word loading is displayed, followed by percent = (loading * 100) // seconds
some characters, and a percentage of the program loaded. While print(“\n”)
it may not take long for your Python code to load, the effect can print(“Loading...”)
be interesting.
print(“<” + (“-” * loading) + (“ “ *
Create a New File in Python and enter the following code: (seconds-loading)) + “> “ + str(percent) + “%”)
import os print(“\n”)
import time time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else
def loading_bar(seconds): ‘clear’)
for loading in range(0,seconds+1):
percent = (loading * 100) // seconds def loading_screen(seconds):
print(“\n”) screens=open(“screens.txt”, ‘r’)
print(“Loading...”) for lines in screens:
print(“<” + (“-” * loading) + (“ “ * print(lines, end=’’)
(seconds-loading)) + “> “ + str(percent) + “%”) time.sleep(seconds)
print(“\n”) screens.close()
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else #Main Code Start
‘clear’)
loading_bar(10)
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
#Main Code Start
loading_screen(.5)
loading_bar(10)

print (“\nYour code begins here...”)


print (“\nYour code begins here...”)
You can, of course, pull those functions up wherever and
The code works in much the same way as the previous, except, whenever you want in your code and they’ll display, as they
instead of reading from a text file, it’s running through a For loop should, at the beginning. Remember to have the ASCII
that prints Loading… followed by an animation of sorts, along with a text file in the same folder as the Python code, or, at the
percentage counter; clearing the screen every second and displaying screens=open(“screens.txt”, ‘r’) part of the code, point
the new results. It’s simple, yes, but quite effective in its design. to where the text file is located.

ADVENTURE TIME
A good example of using loading screen, ASCII art text images is when coding
a text adventure. Once you’ve established your story, created the characters,
events and so on, you could easily incorporate some excellently designed
ASCII art to your game.
Imagine coming across a dragon, in game, and displaying its representation
as ASCII. You can then load up the image lines, one-by-one, and continue with
the rest of the adventure code. It’s certainly worth having a play around with
and it’ll definitely add a little something else extra.

www.pclpublications.com 155
Pi Projects

Tracking the ISS with Python


Of the many, amazing human achievements over the past decade or so, the International Space
Station tops the bill. This incredible collaboration between nations sees vital experiments carried
out in space, as well as observations of our own planet.

TO BOLDLY GO…
Indeed, the ISS is something most of us consider as a worthy
example of what can happen when we work together. NASA,
among other agencies, uses a wealth of Python code onboard the
ISS to help automate routines, alongside its function as an
in-between link to translate code from one language
to another, and then into a human-readable
format. If you’re considering a career in
space, then learning Python is a must-
have skill.
While we’re not able to fill
you in on all the details
regarding the code the
ISS utilises, we can
look at a fun Python
script that will track
the ISS, display the
number of astronauts
on board, and update
the station’s current
latitude and longitude
every five seconds, while
also displaying your current
latitude and longitude.
Displaying all that information
in a single screen can become a
little cluttered, so in this instance
we’re going to look at spreading
all those details over three
screens: a text document window
-displaying the astronauts and your
current latitude and longitude,
a command line (or Terminal
window) - displaying the continually
updating latitude and longitude of
the ISS as it orbits Earth, and a final,
large window displaying a map of
the world, together with an icon
representing the ISS, that’s updated
as it orbits. Interested? Read on.

156 Raspberry Pi Coding & Projects


Tracking the ISS with Python

THE GRAPHICS
Firstly, we need to get hold of a map of the world and an image of the As we’re going to be using Turtle, a component of tkinter, the
ISS, to use as an icon that will be updated according to the position downloaded images will need to be converted to GIF, since this is the
of the space station as it travels over the surface. A quick Google of default and recommended image format. You can easily look up a
World Map will help you out here. Look for one that’s reasonably converter online, but using GIMP, which is cross-platform and therefore
large, the one we used for this example was 1280 x 700, and one works on both the Raspberry Pi and a Windows PC, will suffice. Simply
that has the names of the countries – if you’re using this with young load the image up in your image editor app and choose Save As, call
people, to help with putting shapes of countries to names. them map and iss respectively, and click GIF as the image format.
Remember to also resize the ISS image before saving it as a GIF.

Next, look for an ISS icon. As this is going to be a graphical


representation of the location of the ISS, we need the image to
be reasonably small so it doesn’t drown out the locations on the
map, but also prominent enough to see when the map is loaded.
We opted for an image that’s 32 x 22 pixels in size. Don’t worry
too much if you’re not able to find one that small, you can always
resize it in an image-editing app such as GIMP.

THE CODE
The code we’re using here utilises an open source API In order for Python to interact with the
(Application Programming Interface) to retrieve real-time data JSON provided data, it needs to use the
online regarding the status of the ISS. An API enables applications urllib.request and json modules. We’re
to communicate with one another by providing the raw data that also going to be using a new module called
a programmer can pull out and interact with in their own code. In geocoder, which will pull up a users’ current
this case, the API in question is a web-based collection of raw data latitude and longitude based on their IP
that’s stored in a JSON (JavaScript Object Notation) format – an address. The two JSON APIs can be located
accessible and easy to use data-interchange interface. at: http://api.open-notify.org/astros.
json, and, http://api.open-notify.org/iss-
now.json. One of which contains the data
regarding the astronauts onboard the ISS,
and the other contains the data regarding
the current location of the ISS in longitude
and latitude.

www.pclpublications.com 157
Pi Projects

Let’s begin by breaking the code into bite-sized chunks: screen.setworldcoordinates(-180, -90, 180, 90)
import json, turtle, urllib.request, time, #Load the world map image
webbrowser screen.bgpic(“map.gif”)
import geocoder # need to pip install geocoder
for your lat/long to work.
screen.register_shape(“iss.gif”)
First, we need to import the modules used in the code: json,
turtle, urlib.request, time, and webbrowser. The json and urlib. iss = turtle.Turtle()
request modules deal with the data being pulled from the APIs, iss.shape(“iss.gif”)
turtle will display the graphics, and time you already know. The
iss.setheading(45)
Webbrowser module will open text files in the default browser
or default text reader application. The geocoder module is a iss.penup()
new element and you will need to install it with: pip install This section of the code sets up the graphical window containing
geocoder (or try pip3 install geocoder, if the pip install the world map and the ISS icon. To begin, we set up the turtle
command still won’t load the module). Geocoder can retrieve a screen, using the resolution of the world map image we
users’ location based on their IP address, as each ISP will have a
downloaded at the start of this tutorial (1280 x 720). The screen.
geo-specific IP.
setworldcoordinates syntax will mark the boundaries of the
#Retrieve the names of all the astronauts screen, creating the x and y coordinates of the four corners of
currently on board the ISS, and own lat/long -
the canvas, so that the ISS icon can freely travel across the map
write to a file and display
of the world and wrap itself back to the opposite side when it
url = “http://api.open-notify.org/astros.json”
reaches an edge. The ISS icon is set as the turtle pen shape, giving
response = urllib.request.urlopen(url) it an angle of 45 degrees when moving.
result = json.loads(response.read()) while True:
a=open(“iss.txt”,”w”)
#Load the current status of the ISS in real-
a.write(“There are currently “ + time
str(result[“number”]) + “ astronauts on the
url = “http://api.open-notify.org/iss-now.json”
ISS:\n\n”)
response = urllib.request.urlopen(url)

people = result[“people”] result = json.loads(response.read())

for p in people: #Extract the ISS location


a.write(p[“name”] + “ - on board” + “\n”) location = result[“iss_position”]
lat = location[“latitude”]
g=geocoder.ip(‘me’) # need to pip install lon = location[“longitude”]
geocoder, and import as in the headers above
a.write(“\nYour current Lat/Long is: “ + str(g.
#Output Latitude and Longitude to the console
latlng)) # prints your current lat/long in the
text file. lat = float(lat)
a.close() lon = float(lon)
webbrowser.open(“iss.txt”) print(“\nLatitude: “ + str(lat))
This section will use the json and urllib.request modules to pull print(“Longitude: “ + str(lon))
the data from the API that contains the names of the astronauts
onboard the ISS. It then creates a new text file called iss.txt,
where it’ll write ‘There are currently X astronauts on the ISS…’ #Update the ISS location on the map
and list them by name. The second part of this section will then iss.goto(lon, lat)
use the geocoder module to retrieve your current latitude
#refresh every 5 seconds
and longitudes, based on your IP address, and also write that
information to the end of the text file that contains the names time.sleep(5)
of the astronauts. The last line, webbrowser.open(“iss.txt”) will Now for the final part of the code: Here we collect the location
use the webbroser module to open and display the newly written data from the ISS status API, pulling out the latitude and
text file in either the system’s default text file reading app or the longitude elements of the JSON file. The code then prints the
default web browser; either will work just fine.
latitude and longitude data to the console/Terminal, transferring
#Setup world map in Turtle the data from a float to a string in order to print it correctly. The
screen = turtle.Screen() last section will use the latitude and longitude as variables lat
screen.setup(1280, 720) and lon, to update the ISS icon on the map every five seconds.

158 Raspberry Pi Coding & Projects


Tracking the ISS with Python

Here’s the code in its entirety:


import json, turtle, urllib.request, time, webbrowser
import geocoder # need to pip install geocoder for
your lat/long to work.

#Retrieve the names of all the astronauts currently on


board the ISS, and own lat/long - write to a file and
display
url = “http://api.open-notify.org/astros.json”
response = urllib.request.urlopen(url)
result = json.loads(response.read())
a=open(“iss.txt”,”w”)
a.write(“There are currently “ + str(result[“number”])
+ “ astronauts on the ISS:\n\n”)

people = result[“people”]

for p in people:
a.write(p[“name”] + “ - on board” + “\n”)

g=geocoder.ip(‘me’) # need to pip install geocoder,


and import as in the headers above
a.write(“\nYour current Lat/Long is: “ + str(g.
latlng)) # prints your current lat/long in the text
file.
a.close()
webbrowser.open(“iss.txt”)

#Setup world map in Turtle


screen = turtle.Screen()
screen.setup(1280, 720)
screen.setworldcoordinates(-180, -90, 180, 90)
#Load the world map image
screen.bgpic(“map.gif”)
RUNNING THE CODE
The code is best executed from the command line, or Terminal.
screen.register_shape(“iss.gif”) Clear your desktop, enter your command line, and navigate
iss = turtle.Turtle() to where you’ve saved the code plus the two graphics.
iss.shape(“iss.gif”) Launch the code with either: python3 ISSTrack.py, or,
iss.setheading(45) python ISSTrack.py (depending on whether you’re using a
iss.penup() Raspberry Pi/Linux, or a Windows PC, and what you’ve called
the Python code).
while True:
#Load the current status of the ISS in real-time
url = “http://api.open-notify.org/iss-now.json”
response = urllib.request.urlopen(url)
result = json.loads(response.read())

#Extract the ISS location


location = result[“iss_position”]
lat = location[“latitude”]
lon = location[“longitude”]

#Output Latitude and Longitude to the console


lat = float(lat)
lon = float(lon)
print(“\nLatitude: “ + str(lat))
print(“Longitude: “ + str(lon))

#Update the ISS location on the map The code will launch two extra windows together with the
iss.goto(lon, lat) command line window you already have open. One will be the
#refresh every 5 seconds text file, containing the named astronauts, along with your
time.sleep(5) current latitude and longitude and the other will be the world
map with the ISS icon located wherever the ISS is currently
Create a new folder in your system, called ISSTrack (for example), and orbiting. The command line window will start scrolling through
place the two graphics as well as the Python code itself. the changing latitude and longitude of the ISS.

www.pclpublications.com 159
Pi Projects

Text Animations
There’s a remarkable amount you can do with some simple text and a little Python know-how.
Combining what you’ve already learned, we can create some interesting animation effects from
the command line.
#Display the message
THE FINAL COUNTDOWN print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
Let’s begin with some example code that will display a large
print(“< >”)
countdown from ten, then clear the screen and display a message.
The code itself is quite simple, but lengthy. You will need to start by print(message)
importing the OS and Time modules, then start creating functions print(“< >”)
that display the numbers (see image below) and so on to 10. It’ll print(“v^v^v^v^v^v^v^v^v^v^v^v^v^v^v”)
take some time, but it’s worth it in the end. Of course, you can print(“\n\n\n”)
always take a different approach and design the numbers yourself.
The code in its entirety can be viewed from within our Code Repository:
The next step of the process is to initialise the code settings and
https://bdmpublications.com/code-portal,
start the countdown:
where you’re free to copy it to your own
#Initialise settings Python IDLE and use it as you see fit. The end
start = 10 effect is quite good and it’ll be worth adding to
message = “> BLAST OFF!! <” your own games, or presentations, in Python.
To extend the code, or make it easier to use,
you can always create the number functions
#Start the countdown
in their own Python code, call it Count.py for
for counter in range(start, 0, -1): example, then import Count at the beginning
if counter == 10: of a new Python file called Countdown.py,
ten() along with the OS and Time modules:

elif counter == 9: import os

nine() import time

elif counter == 8: import count


From there, you will need to specify the imported code in the
eight()
Countdown section:
elif counter == 7:
#Start the countdown
seven()
for counter in range(start, 0, -1):
elif counter == 6:
if counter == 10:
six()
count.ten()
elif counter == 5:
elif counter == 9:
five()
count.nine()
elif counter == 4:
elif counter == 8:
four()
count.eight()
elif counter == 3:
elif counter == 7:
three()
count.seven() elif counter == 3:
elif counter == 2:
elif counter == 6: count.three()
two()
count.six() elif counter == 2:
elif counter == 1:
elif counter == 5: count.two()
one()
count.five() elif counter == 1:
time.sleep(1)
elif counter == 4: count.one()
os.system(‘cls’ if os.name ==
count.four()
‘nt’ else ‘clear’) This will pull the functions from the imported Count.py and print
And finally, we can add a display for the message: them to the screen.

160 Raspberry Pi Coding & Projects


Text Animations

ROCKET LAUNCH ROLLING DIE


Building on the previous Aside from the rocket animation, together with its countdown,
countdown example, we can another fun bit of text-based animation is that of a rolling dice.
create an animated rocket that’ll A rolling dice can be a great animation to include in an adventure
launch after the Blast Off!! game, where the player rolls to see what their score is compared
message has been printed. The to that of an enemy. The highest roller wins the round and the
code would look something like: losers’ health drops as a result. It’s an age-old combat sequence,
def Rocket(): used mainly in the Dungeon and Dragons board games and
distanceFromTop = 20 Fighting Fantasy novels, but it works well.

while True: The code you’ll need to animate a dice roll is:

os.system(‘cls’ if os.name == ‘nt’ else ‘clear’) import os

print(“\n” * distanceFromTop) import time

print(“ /\ “) from random import randint

print(“ || “)
die = [“ \n O \n “] #1
print(“ || “)
die.append(“ O\n \nO “) #2
print(“ /||\ “)
die.append(“O \n O \n O”) #3
time.sleep(0.2)
die.append(“O O\n \nO O”) #4
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
die.append(“O O\n O \nO O”) #5
distanceFromTop -= 1
die.append(“O O\nO O\nO O”) #6
if distanceFromTop <0:
distanceFromTop = 20 def dice():
for roll in range(0,15):
os.system(‘cls’ if os.name == ‘nt’ else
#Launch Rocket
‘clear’)
Rocket()
print(“\n”)
Here, we’ve created a new function called Rocket, which produces
number = randint(0,5)
the effect of an ASCII-like rocket taking off and scrolling upwards;
using the distanceFromTop variable. print(die[number])
To use this, add it to the end of the previous countdown code and, time.sleep(0.2)
at the end of the Blast Off!! message, add the following lines:
print(“\n\n\n\n”) #Main Code Begins

input(“Press Enter to launch rocket...” dice()

This will allow your message to be displayed and then, when the You may need to tweak the O entries, to line up the dots on the
user has hit the Enter button, the rocket will launch. virtual dice. Once it’s done, though, you’ll be able to add this
function to your adventure game code and call it up whenever
Again, the code in its entirety can be found in the Code
your character, or the situation, requires some element of luck,
Repository at: https://bdmpublications.com/ code-portal. combat, or chance roll of the dice.

DISCOVER ANIMATIONS
The great thing about Python code is that it’s so accessible. These what it is you’re after, you’re bound to come across something very
few examples will help you add some fun, or something different, like the desired effect; all you need to do is modify it slightly to
to your programs, but they’re just the tip of the proverbial iceberg. accomplish your own goals.
If there’s something you want to include in your code, and you’re at You’ll find that many professionals will often take to the Internet to
a sticking point, then consider heading over to Stack Overflow and find content they’re after. True, they’re able to code it themselves,
search for Python 3 content. but even experts get stuck sometimes, so don’t worry about hunting
Stack Overflow is a great online help and resource portal, where you code snippets down; you’re in good company.
can ask questions and experts will try and help you. It doesn’t always
work out, but most of the time, you’ll find what you’re looking for
within this great resource.
Also, if you’re after a simple animation then take to Google and
spend some time searching for it. While you may not find exactly

www.pclpublications.com 161
Pi Projects

Retro Coding
There’s a school of thought, that to master the foundations of good coding skills you need to
have some experience of how code was written in the past. In the past is a bit of a loose term, but
mostly, it means coding from the 80s.
BBC BASIC was used on the Acorn BBC Micro range of computers,
utilising the MOS 6502-based processor technologies. It was one of
the quickest examples of BASIC and, thanks to an inline assembler,
it was also capable of allowing the developers of the time to write
code for different processor types, such as the Zilog Z80 – a CPU
present in the ZX Spectrum, as well as many arcade machines.
The BBC Micro was designed and built by Acorn Computers – a
THE GOLDEN ERA OF CODE company that is historically responsible for the creation of the ARM
While it may seem a little counterproductive to learn how to code CPU - the processor that’s used in virtually every Android phone and
in a language that’s virtually obsolete, there are some surprising tablet, smart TV, set top box and so on, as well as the Raspberry Pi –
benefits to getting your hands dirty with a bit of retro coding. so essentially, the BBC Micro is the grandfather of the Raspberry Pi.
Firstly, learning old code will help you build the structure of code The BBC Micro was born in a time when the UK government
as, regardless of whether it is a language that was developed was looking for a countrywide computer platform to be used
yesterday, or forty years ago, code still demands strict discipline to throughout education. Different companies bid, but it was the
work correctly. Secondly, everyday coding elements, such as loops, BBC’s Computer Literacy Project (the BBC Micro) that was chosen,
sub routines and so on, are a great visual aid to learn in older code, due to its ruggedness, upgradability, and potential for education.
especially BASIC. Lastly, it’s simply good fun. As a result, the BBC Micro, or the Beeb as it’s affectionately known,
became the dominant educational computer throughout the 80s.

BEEBEM
Naturally, you could scour eBay and look for a working BBC Micro to
play around on, and it’ll be a lot of fun. However, for the sake of just
getting hands-on with some retro code, we’ll use one of the best BBC
Micro emulators available: BeebEm.
GOING BASIC BeebEm was originally developed for UNIX in 1994 by Dave Gilbert and
The easiest retro language to play around with is, without doubt, later ported to Windows. It is now developed by Mike Wyatt and Jon
BASIC. Developed back in the mid-sixties, BASIC (Beginner’s All- Welch, who maintain the Mac port of the emulator, and is therefore
Purpose Symbolic Instruction Code) is a high-level programming available for Windows 10, Linux and macOS, as well as other platforms.
language whose design was geared toward ease of use. In a time If you’re using Windows 10, simply navigate to http://www.mkw.
when computers were beginning to become more accessible, me.uk/beebem/index.html, and download the BeebEM414.exe that’s
designers John Kemeny and Thomas Kurtz needed a language that displayed in the main screen.
students could get to grips with, quickly and easily. Think of BASIC
as a distant relation to Python.

THE BEEB
The problem with BASIC is that there were so many different
versions available, across multiple 8-bit platforms, with each having
its own unique elements on top of the core BASIC functions. The
BASIC that was packaged with the Commodore
64 was different to that on the ZX
Spectrum, or the Atari home
computers, due to the differing Once downloaded, launch the executable and follow the on-screen
hardware of each system. instructions to install it. MacOS users can get everything they need
However, it’s widely recognised from: http://www.g7jjf.com/. However, Raspberry Pi and Linux users
that one of the ‘best’, and possibly will have to do a little nifty keyboard work before they can enjoy the
most utilised, form of BASIC from the benefits of the Beeb on their screens. Here’s how to get it working
80s was that of BBC BASIC. under Linux:

162 Raspberry Pi Coding & Projects


Retro Coding

First, drop to a Terminal and enter:


sudo apt-get update && upgrade
wget http://beebem-unix.bbcmicro.com/download/
beebem-0.0.13.tar.gz
Then, extract the compressed files with:
tar zxvf beebem-0.0.13.tar.gz, then enter the newly
created Beebem folder with: cd beebem-0.0.13/.
50 print
Now enter the following lines, hitting Enter and answering Y to
accept any changes: BBC BASIC also has some interesting built-in features, such as the
value of PI:
sudo apt-get install libgtk2.0-dev libsdl1.2-dev
1 REM Area of a circle
./configure
2 CLS
make
20 Input “Enter the radius: “ r
sudo make install
30 let area = PI*r*r
This may take some time, but when it’s all done, simply enter:
beebem, to start the BBC Micro emulator. 40 print “The area of your circle is: “; area
50 print ‘’’

BBC BASIC
Once installed and powered up, BeebEm will display the default BBC
system start-up, along with a couple of beeps. Those of you old enough
to have been in a UK school in the 80s will certainly recall this setup.
In BASIC, we use line numbers to determine which lines of code run
in sequence. For example, to print something to screen we’d enter: As you’ll notice, variables with a dollar
($) represent strings, nothing after the
10 print “hello”
variable, or a hash (#) represent floating
Once you’ve typed the above in, press Enter and then type: point decimals; a whole integer has a %
run character, and a byte has an ampersand
We can of course expand the code (&). The single quotes after the Print on
to include variables, multi-line print line 50 indicate a blank line, one for each
statements, and so on: tick, while REM on line 1 is a comment,
and thus ignored by the BASIC compiler.
1 CLS
Needless to say, there’s a lot you can learn, as well as having fun, with
10 Input “Hello, what’s your name? “ n$
BBC BASIC. It’s a rainy day project and something that’s interesting
20 print to show the kids – this is how we rolled back in the 80s, kids!
30 print “Hi, “ n$ “ I hope There are a number of sites you can visit to learn BBC BASIC, such as
you’re well today.” http://archive.retro-kit.co.uk/bbc.nvg.org/docs.php3.html. See what
Type RUN to execute the code, you can you can come up with using BBC BASIC, or other BASIC types for
also type LIST to view the code you’ve different systems, and let us know what you’ve created.
entered.
OTHER SYSTEMS
Naturally, you don’t have to look
to the BBC Micro to play around
with some retro code. If you
grew up with a Commodore 64,
then you can always try VICE,
the C64 emulator. Likewise, the
ZX Spectrum has a slew of great
As you can see, variables are handled in much the same way as
emulators available for every
Python, a print statement on its own displays a blank line, and CLS
modern system to play around
clears the screen; although the Pi uses Clear instead of CLS. We’re
on. In fact, you can probably
also able to do some maths work, and play around with variables too:
find an emulator for virtually
1 CLS every 8-bit or 16-bit machine
10 input “how old are you? “ a that was produced over the
years. Each has their own
20 print
unique perspective and coding
30 if a > 40 print “You’re over 40 years old.” nuances, so find a few and see
40 if a < 40 print “You’re under 40 years old.” what you can create.

www.pclpublications.com 163
Pi Projects

Using Text Files


for Animation
Animation in Python can be handled with the likes of the Tkinter and Pygame modules, however,
there’s more than one way to achieve a decent end result. Using some clever, text file reading
code, we can create command-line animations.

ASCII ANIMATION
Let’s assume you wanted to create an animated ASCII Happy Birthday Python script, with the words Happy and Birthday alternating in
appearance. Here’s how it’s done.

First we need to create some ASCII-like text, head over Save the text file as 1.txt (you can call it anything, but
STEP 1 STEP 3
to http://patorjk.com/software/taag. This is an online now for ease of use 1.txt will suffice) and save the file
Text to ASCII generator, created by Patrick Gillespie. Start by entering in the newly created Test folder. When it’s saved, do exactly the same
Happy into the text box, the result will be displayed in the main for the word Birthday. You can select a new font from the ASCII
window. You can change the font with the drop-down menu to the Generator, or add extra characters, and when you’re ready save the
side of the text box; we’ve opted for Big. file as 2.txt.

Now, on your computer create a folder in your Python


STEP 2
code directory (call it Test, for now) and open either
Leafpad for the Raspberry Pi or, if you’re using Windows 10, then
Notepad. Click on the Select & Copy button, at the bottom of the
ASCII Generator webpage, and paste the contents into the text editor.
Open up Python and create a New File. We’re going
STEP 4
to need to import the OS and Time modules for this
example, followed by a line to clear the screen of any content. If
you’re using Windows, then you’ll use the CLS command, whereas it’s
Clear for the Raspberry Pi’s Linux OS. We can create a simple if/else
statement to handle the command.

164 Raspberry Pi Coding & Projects


Using Text Files for Animation

Next we need to create a list with the names of the Here’s the code in full:
STEP 5 STEP 8
text files we want to open, and then we need to open
them for display in the Terminal. import os, time
filenames = [“1.txt”, “2.txt”]
frames = [] os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)

for name in filenames:


with open(name, “r”, encoding=”utf8”) as f: filenames = [“1.txt”, “2.txt”]
frames.append(f.readlines()) frames = []

for name in filenames:


with open(name, “r”, encoding=”utf8”) as f:
frames.append(f.readlines())

for i in range(10):
for frame in frames:
print(“”.join(frame))
time.sleep(1)
os.system(‘cls’ if os.name == ‘nt’ else
‘clear’)

We’ve used the UTF8 standard when opening the text Note, from the loop, within the code, we’ve used the
STEP 6 STEP 9
files, as ASCII art as text, within a text file, often same CLS and Clear if/else statement as before. Again,
requires you to save the file as UTF compliant – due to the characters if you’re running on Windows then the OS module will use the CLS
used. Now we can add a loop to display the files as 1.txt, then 2.txt, command, ‘ELSE’ if you’re using Linux or a Mac, the Clear command
creating the illusion of animation while clearing the screen after each will work correctly. If you want, you could use a Try/Except
file is displayed. statement instead.

Save the Python code in the same folder as the text You can spice things up a little by adding system/
STEP 7 STEP 10
files and drop into a Terminal or Command Prompt. Terminal colours. You’ll need to Google the system
Navigate to the folder in question, and enter the command: codes for the colours you want. The code in our example turns the
python3 NAME.py Raspberry Pi Terminal to green text on a black background, then
Where NAME is whatever you called your saved Python code. changes it back to white on black at the end of the code. Either way, it’s
a fun addition to your Python code.

www.pclpublications.com 165
Pi Projects

Stream Digital TV with a


HAT - Part 1
A HAT, in case you’re wondering, is a Hardware Attached on Top add-on board that connects to
a Raspberry Pi’s 40-pin GPIO. They can extend the capabilities of a Pi by adding motors, LCDs,
sensors, controllers and more. In addition, they can be programmed via the Pi and Python.

TV HAT
In this tutorial, we’re using the Raspberry Pi TV HAT as sold by The Pi Hut (https://thepihut.com/products/raspberry-pi-tv-
hat?variant=13539182673982). It’s a Sony CXD2880 TV Tuner supporting DVB-T and 2nd-gen DVB-T2 standards.

The Raspberry Pi TV HAT is compatible with the Pi With the spacers attached to the Raspberry Pi, line up
STEP 1 STEP 3
Zero, Pi 3 A+ and B+ models. The kit comes with the TV HAT with the 40-pin header, ensuring that the
everything you need to connect the HAT to your RPi, including spacers, side of the HAT with the Pi logo is facing up and the HAT’s gold
screws and the 40-pin header. Begin by opening the box and spreading coloured coaxial attachment is on the side of the SD card. When in
the contents out on a clear area. place, screw the HAT to its spacers.

Start by connecting the 40-pin header to the 40-pin


STEP 2
GPIO on top of your Raspberry Pi. Now take the
spacers and screws and fit them to the corresponding holes in the Now attach the coaxial adapter to the gold-coloured
STEP 4
corners of the main Raspberry Pi and the TV HAT; use three spacers pin at the side of the TV HAT. It may need a firm push
and screws for the Pi Zero and two for the Pi 3 Models A+/B+. to lock into place, it will ‘click’ when fully inserted and in position. Now
you will need to connect the TV HAT to your TV aerial and provide
power to the Raspberry Pi.

166 Raspberry Pi Coding & Projects


Stream Digital TV with a HAT - Part 1

You can use the HDMI port to connect your Pi and its If you haven’t used your Raspberry Pi since, at least,
STEP 5 STEP 8
TV HAT to the TV/monitor, or you can just power the November 2018, then you may need to upgrade the
Pi (the TV HAT gets its power from the Pi) and connect remotely. The core OS and synchronise the version of Raspbian with what’s currently
most important element is to ensure that the TV HAT is connected to available from the Pi Foundation’s downloads page. It’s not totally
an aerial that you know can receive a TV signal. necessary, but if you choose to, enter:
sudo apt-get dist-upgrade
Press Enter and follow the on-screen instructions.

Power up your Raspberry Pi and when you get to the When the updates are complete, there’s a good
STEP 6 STEP 9
Raspbian desktop, open up the Terminal app. When at chance you’ve got some leftover, older setup files and
the Terminal, enter the following to ensure the Pi is up to date and packages in the system. To save space, use the following commands:
running the latest versions of its software and system: sudo apt-get autoclean
sudo apt-get update && sudo apt-get upgrade and:
sudo apt-get autoremove
Answer ‘Y’ to clear the system of the unnecessary packages and files.

Press Enter and allow the Pi to run through the update


STEP 7
process. If you have any significant updates, you may At this point, it’s worth noting that in the UK it’s
STEP 10
need to answer ‘Y’ to any questions the Pi asks regarding these. necessary to have a valid TV License in order to watch
Answering yes will replace the older software with the newer versions or record programmes as they are being shown on TV or live via an
and is necessary for a smoothly running Pi. online service. It is an offence under Section 363 of the Communications
Act 2003 to use a TV receiving device without a valid TV License.

www.pclpublications.com 167
Pi Projects

Stream Digital TV with a


HAT - Part 2
In part 1 of this tutorial, we set up the Raspberry Pi and the TV HAT. The core Pi software and
system should now be up to date and the TV Hat connected to an aerial. You should also ensure
you have a valid UK TV Licence.

TURN ON, TUNE IN


With the hardware ready, it’s now time to begin the TV tuning software installation and setup. If you haven’t already, reboot the Raspberry
Pi and enter the Terminal for this next part.

To use the TV tuner, we need to install the TVheadend The remainder of the setup will now continue. It’ll take
STEP 1 STEP 3
software. Open a Terminal session and enter around three minutes to complete, depending on
the following: which model Raspberry Pi you’re using. When the setup has finished,
sudo apt-get install tvheadend you can exit the Terminal session.
Press Enter and ‘Y’ if necessary to confirm the installation.

As the installation continues, you will be presented You can now either open the web browser on the Pi, if
STEP 2 STEP 4
with a configuration screen. Enter a username and you’re connected to the TV through the Pi, or, if
password to enable access to the TVheadend server. Once entered, you’re connecting remotely, open any web browser on your computer
make a note of the web address access for the server. When accessing with the address from Step 2. If you don’t know the Pi’s IP address
on the TV Pi, it’ll be http://localhost:9981/. If accessing from another enter:
computer on the network, use the Pi’s IP address. For example: ifconfig
http://192.168.1.223:9981/. in the Terminal on the Pi. The inet entry is the Pi’s IP address. Here,
the example is: 192.168.1.238.

168 Raspberry Pi Coding & Projects


Stream Digital TV with a HAT - Part 2

For this example, we will assume you’re connecting For this next step you need to select the transmitter
STEP 5 STEP 8
remotely (from another computer on the home closest to your location. You can find the closest
network). Enter the Pi’s IP address with the port 9981, e.g.: transmitter by entering your details at: http://www.digitaluk.co.uk/
http://192.168.1.238:9981/. To start the Configuration Wizard: enter coveragechecker/. Simply choose the transmitter from the pull-down
the username and password you set up from Step 2 and log in to the list. When ready, click on the Save & Next button. The TV HAT will now
TVheadend Server, then set the Language and Language 1 options to scan for all available TV signals from the chosen transmitter.
your preference.

Click the Save & Next button to continue. You will On the next screen, tick all three of the available
STEP 6 STEP 9
need to enable network access to the server. Leave boxes. Click the Save & Next box followed by the
the Allowed Network field blank, but add an asterisk (*) in each of the Finish button on the next screen; It’s recommended that you now
other fields. Click Save & Next for the next step in the setup process. reboot the Pi and when it’s fully rebooted, navigate back to the
TVheadend server webpage.

For the Network Settings page, leave the first three The TVheadend server webpage will now display the list
STEP 7 STEP 10
fields blank, but use the pull-down menu to select of available channels. After picking one, either click the
DVB-T Network. The TVheadend server will already have pre-selected title of the programme showing to expand the details, then click the
the Sony CXD2880 tuner (the TV HAT) from its available choices. Click Play Programme button to view its content, or click the small TV icon in
the Save & Next button when ready. the details column of the channel. You can now watch live TV across
your home network.

www.pclpublications.com 169
Pi Projects

Pi Projects: Desktop Pi
As you are now no doubt aware, the Raspberry Pi is certainly a versatile little piece of technology.
Let’s look at some of the popular projects you can apply to your Pi, starting with one that’s not
only the easiest, but also one of the best.

COMPUTER PI
First and foremost, the Raspberry Pi is a computer. It has an
operating system, built-in productivity apps, the ability to
connect to both a home network and the Internet (either
wirelessly or through Ethernet), and you can connect a mouse,
keyboard, and monitor. It stands to reason, then, that it makes for
a remarkably cheap desktop computer.
The obvious advantage of using the Raspberry Pi as a desktop
computer though, is the fact that it’s so cheap. For around £100
you could easily purchase the Pi, monitor, keyboard and mouse,
providing you with a fully-functional computer capable of doing
most, if not all, of the things you would do on a computer that
costs ten times that amount. However, there are ways in which
you can further enhance the desktop Pi project.

CASES
To begin with, you will need the Raspbian
Stretch with desktop and recommended
software OS version from the Raspberry
Pi Foundation page, www.raspberrypi.org/
downloads/raspbian. Once you’ve installed
that to your Pi, booted it, and logged in with a
personal user account, you can then start looking
at one of the many colourful, and functional, cases
available for the Pi.
The Pi Hut offers a superb selection of cases for the
various versions of the Raspberry Pi, for this project, we’d
recommend the Raspberry Pi 3 Model B+, as it’s the fastest and
most capable of the current models. For just £6, you can have a
colourful – white and red – official Raspberry Pi case, with pre-
formed holes that line up perfectly with the ports on the Pi. For
around ten pound more, there’s also the FLIRC case, an impressive
design that’s finished in brushed aluminium. On the
other hand, if you want something a little different
from the norm, then how about a case that’s designed
to look like a Nintendo Entertainment System, a SNES,
or even a SEGA Megadrive?

170 Raspberry Pi Coding & Projects


Pi Projects: Desktop Pi

COOLING
Another thing to consider, if you’re going to be using your Pi as a
desktop computer, is cooling. While the Pi’s low use of resources
means that its internals don’t get too hot, prolonged and intense
use may see your Pi getting a little warm, especially if it’s inside
a case and the ambient temperature of the environment is also
warm. There are options available to help cool your Pi down, chiefly
the Raspberry Pi Heatsink. This is a high-quality aluminium
heat dispersing element that fits on top of the Pi’s
processor, leeching heat away from the vital circuit
board and out into the surrounding air. However,
bigger and more effective heatsinks are available, as
well as fans, and even a water-cooling kit. These are a
little extreme though, and only necessary if your Pi is doing
some serious number crunching for an extended period of time.

STORAGE
While the Raspberry Pi desktop project is a great idea, the sad
fact of the matter is that the Pi doesn’t exactly offer the user a
wealth of storage; compared to a Windows or Mac desktop, that is.
Naturally, you can use a larger capacity SD card on which to install
Raspbian, and utilise the remaining space as your Home folder,
but again you’re limited. Thankfully, it’s not too much expense to
include an external hard drive. A portable, USB connected, slimline
2TB hard drive can cost in the region of £60 and give you as much
storage capacity as one of the more traditional desktop computers.
One thing worth noting with regards to using an external hard
drive, make sure you always have a backup of what’s on there.
There are many options available to you if you decide to go
down the Raspberry Pi desktop computer project route; there’s
even a Pi laptop kit available called Pi-Top. Needless to say, with
this amount of choice you’re able to customise your desktop and its
setup in a more personal way than on a Windows PC, or a Mac.

DON’T THROW AWAY YOUR PC YET


PERIPHERALS While the Raspberry Pi is a great little desktop computer, it does
To cut down on the have its limitations. If you’re accustomed to using a reasonably
amount of cable powerful Windows PC, or Mac, then you may find that, while being
clutter on your efficient, cheap and offering more space on your desk, the Pi does
desktop, you could tend to struggle from time to time.
consider opting for This is purely down to the fact that the Raspberry Pi isn’t the
a Bluetooth keyboard most powerful computing device available today. It won’t be able
and mouse. The Pi 3 Model B+ to handle the latest, triple-A games, intense graphics, Virtual
offers Bluetooth connectivity alongside its Reality, or even some of the higher definition media content. You
Wi-Fi capabilities, so effectively you’re able to use any may find it stuttering when trying to playback fast moving 1080HD
recently purchased Bluetooth keyboard and mouse kit available. scenes, and true 4K playback isn’t an option.
The major advantage here is that the Pi can be mounted to the However, if you’re looking to substitute your day-to-day
rear of your monitor and, together with connecting to your home workstation with something cheaper and smaller, and you’re not
network via Wi-Fi, the only cables involved would be the power going to push the Pi’s processor too much, then you’ll find the Pi to
and the HDMI cable to the monitor, both of which could be neatly be a wonderful desktop computer. If you want more, though, hang
tucked away. on to that more powerful PC for the moment.

www.pclpublications.com 171
Pi Projects

Pi Projects: Retro Gaming


Those of you old enough to recall the golden era of the home computer, the 80s, will have fond
memories of playing on a Commodore 64, ZX Spectrum, Amiga, Atari ST, and the countless
wonderful arcade machines that consumed more than their fair share of our pocket money. Hold
on, because you’re in luck.

GOING RETRO
The Raspberry Pi makes for an amazing retro gaming
computer. With it you’re able to emulate and play the classic
home computers, consoles and arcade machines that brought
us so much joy back in the day.
Thankfully, the processing power of most of the systems of
the past is well within the capabilities of the Raspberry Pi’s
processor. There are a few examples that don’t run too well,
such as a PS2, or those systems that utilised a specialised
3D component, but on the whole, there’s likely to be a fully
working emulator, available for the Pi, that covers the home
computer, console, or arcade that you remember playing.

RetroPie is the foremost retro gaming project available for the If you don’t want to go down the RetroPie route and instead
Raspberry Pi. It’s a set of modules that are built upon Raspbian, you only want one or two systems emulated, then Raspbian has a
an older project called EmulationStation, and Linus distribution wealth of individual emulators available for you to install. You can
called RetroArch. It contains built-in emulation that covers dozens search for the system via Google,
of systems, from an Amiga through to an Atari 2600, Amstrad or if you already know the name
CPC to SEGA Dreamcast, ZX Spectrum to an Apple II; and the of it, simply install it to Raspbian
list is continually growing thanks to the contributions from through the Terminal. It’s worth
the community. mentioning that there will often be
RetroPie can work as an installation on top of an existing multiple emulators designed for the
operating system, such as Raspbian, or you can install RetroPie to same system. While one may work
an SD card and boot the Pi directly into it, choosing to add further perfectly with the vast majority
software later if you want. Once installed, you’re able to connect of games, it may struggle with
USB controllers, or even a PS4 controller via Bluetooth, and if you’re some of the better games
feeling up to it, there’s also support for original controllers when available for that particular
connected to the Raspberry Pi’s GPIO pins. system. On the other

172 Raspberry Pi Coding & Projects


Pi Projects: Retro Gaming

hand, another emulator may play all the games for a system almost desktop arcade machine.
perfectly, with perhaps a loss of sound in some parts, or a slow Picade is a great project, featuring authentic sticks and buttons,
down in others. It’s therefore up to you what you want. You can and an external speaker. There’s artwork available for the arcade
have multiple emulators installed for a single system and use them cabinet setup, along with full instructions on how to set up the
depending on which game you want to play, based on how well the Pi and connect everything to the GPIO pins. The 8-inch display is
emulator supports them, or you can find the single emulator that perfect for old-school gaming, and you can improve on the visuals by
works reasonably well with everything. It’s trial and error, finding the adding extra stickers, a different acrylic marquee, and posters. This,
perfect setup. combined with a RetroPie installation, is an
There are further options you can pursue when building a excellent project idea that’ll
Raspberry Pi retro gaming system. You can encase your Pi inside keep you entertained
one of the many retro-themed cases, such as the Mega-Pi SEGA for hours.
Megadrive case, or you can build your Raspberry Pi into the Picade

ABOUT ROMs
A ROM is the actual contents of a game, or the BIOS of an old
system, be that a home computer or a console. These ROMs are
often ripped from the original tape, cartridge, or chip, and are
available to download from the Internet.
However, the use of ROMs is a continual legal headache. Most
ROMs are illegal, meaning that they are available to download
without the permission of the developer who
created the game, the publishing house that
released the game, and the company that owns
the rights to the system on which the game is
intended to be played.
There’s a school of thought that if you
own the original tape, cartridge and so on,
of the game then you’re legally allowed to
obtain a ROM of the same game and play it on
an emulator, but that’s not always correct. In
the example of music, it is technically illegal
to copy music from a CD you own to playback
on a media device; and in some ways the same
applies to a ROM.
There are however, some examples of a
situation when a title, or a system, has fallen
out of copyright, or has been abandoned.
In these instances, it is perfectly legal for
someone to generate a ROM from the game
and distribute it on the Internet. Sometimes,
another developer improves the original game, adding extra levels,
effects, and so on. Some original developers of older games have
allowed the use of their game to be distributed as a ROM, and
therefore it is legal for you to download and play it.
In short, if you download a ROM from the Internet, and it
doesn’t specify that it’s abandonware or allowed by the developer, LEGAL EMULATION
publishing house, or company, then you’re doing so illegally. It’s Interestingly, while it’s illegal to download most ROMs, it is not
highly unlikely that the police will drop in through your bedroom illegal to install and use an emulator. In fact there are emulators
window and arrest you on the spot – unless you actively host available for the PS4 that allow you play old SEGA Megadrive
illegal content on a website you own – so it’s purely down to your games, so while Sony, or whoever released the emulator for
own conscious. the PS4, have paid for the rights to use the ROMs in their
Remember, even if the game is over thirty years old, emulator, it isn’t illegal for them to develop and use the SEGA
somewhere out there is a developer who spent the time creating Megadrive emulator.
it, so by playing a pirated version of it - an illegal ROM, you’re taking In the same respect, it’s not illegal for you to download an
something away from the individual or team that programmed the emulator for any of the systems, you will just need to find legal
game in the first place. ROMs to play on it.

www.pclpublications.com 173
Pi Projects

Pi Projects: Media Centre


Of all the Raspberry Pi projects out there, turning the tiny computer into a powerful media
centre is probably top of the list. And thanks to the Pi’s diminutive dimensions, and reasonable
processing performance, it is wholly achievable.

FILM NIGHT
First off, what is a media centre? Basically, a
media centre, with regards to what we’re talking
about here, is a computer that’s capable of
playing, possibly recording, and even sorting a
media collection made up of videos, music and
images. It’s a home cinema system, connected to
a TV that will stream media from online, or from
a network attached storage device, or storage
connected directly to the computer itself.
A media centre is often capable of sorting your
collection of videos, music, and photos into
a logical order, either by album, genre, year,
alphabetically, or some custom setup. It can
connect to the Internet and display information
regarding the media, such as album cover, movie
poster, location an image was taken, or even
connect to an online database such as IMDB and
provide further information. In short, it’s a one-
stop location for all your content.

KODI
Since the Pi’s first appearance, there has been some form
of media centre software available for it. Back then, when it
launched in 2012, the major player was XBMC, Xbox Media
Centre, and was considered one of the best cross-platform
media centre applications ever developed. By 2014, though, the
team behind XBMC decided to change its name to Kodi.
Kodi itself is an entertainment hub that collates and
organises all your digital media into a single, user-friendly, and
beautifully designed user interface. Thanks to its design, Kodi is
capable of playing all types of music media and video media, as
well as streaming TV shows (via online, or through a compatible
TV tuner) and photos, plus you can record live TV through a
PVR. It’s extraordinarily customisable, allowing you to install
further add-ons that can connect to other online services like
SoundCloud, YouTube and so on.

174 Raspberry Pi Coding & Projects


Pi Projects: Media Centre

AUTO-START KODI LIBREELEC VS. OSMC VS. RASPBIAN


If you want to start Kodi as soon as your Raspberry Pi powers up, Which OS to install? We could argue all day over the benefits,
then you will need to alter one of the configuration files. While in advantages, and disadvantages of each available operating system
the Terminal, after installing Kodi, enter: and you will probably still be as undecided as when we began.
In truth, there is no perfect operating system, as each offers its
sudo nano /etc/default/kodi own unique way of doing things. In the end, it simply comes down
to which one do you prefer. Raspbian has everything, yet will be
Look for the entry ENABLED, and change it to 1: slower, LibreELEC and OSMC
are faster, but aren’t as fully
ENABLED=1 featured as Raspbian. What you
need to do is experiment with
Press Ctrl+Z to save and exit Nano, then reboot your Pi with: all three, have a look around to
see what else is available, and
sudo reboot then decide on which works
best for you and your particular
Your Pi will now reboot and Kodi will start up once the main boot goals with the Raspberry Pi.
sequence has completed.

OTHER OPTIONS
Of course, you don’t necessarily need to go down the full media centre
road to utilise the Pi as an excellent media playback device. As you have
already noticed, the Raspberry Pi comes pre-installed with its own
specialised version of VLC, a very capable media player. VLC on the Pi
has been designed to make use of the Pi’s processing power, and has
some hardware acceleration benefits coded directly into it, making it
one of the best media players available.
All you need, therefore, is to have a software updated Pi with VLC,
and access to wherever you’ve stored your media collection. While it
may not be as graphically impressive as Kodi, you can still playback
most, if not all, forms of digital media.

INSTALLING KODI – OPTION 2


The second option for installing Kodi on the Pi is to use one of the
Kodi-optimised operating systems suitable for the Raspberry Pi. If
you recall, from when you first installed Raspbian via NOOBS, there
INSTALLING KODI – OPTION 1 are several OS options available to you of which two are LibreELEC
Should you want to install Kodi on your Raspberry Pi and use it as an and OSMC. Both of these operating systems are especially
all-powerful media centre, there are two options available to you. designed to work better with Kodi than the fully installed version
The first is to simply boot up Raspbian, drop into a Terminal session, of Raspbian, due to being a more lightweight OS and less system
perform an update and upgrade, then enter: resource heavy.
This option is often regarded as the preferred method of
sudo apt-get install kodi turning the Pi into a media centre, as both LibreELEC and OSMC are
much faster operating systems, giving more of the Pi’s resources
Once the setup is complete, you can start Kodi by entering: kodi, over to Kodi and allowing it to playback content without causing
into the Terminal. too many problems.

www.pclpublications.com 175
Pi Projects

Pi Projects: BBS Client


In a digital world, before the Internet was a common household name, there existed a connected
community of surfers. These individuals didn’t surf the WWW, instead they dialled up Bulletin
Board Systems (BBS) and opened a whole new world of content.

WARGAMES
If you’re old enough to recall, or have since watched, the
excellent movie Wargames, then you’ll be roughly familiar
with the way in which a Bulletin Board System works; and if
you haven’t watched Wargames, then we recommend you get
hold of it.
In the movie, the young protagonist spends his days at the
keyboard of his early 80s computer, using his modem to dial into
remote systems. Once inside these remote systems, he then
goes about traversing the remote host’s file system looking for
anything interesting.
The movie plot aside, this, essentially, is how a BBS works. It’s a
remote computer that runs specialist BBS server software with a
mix of content either pre-installed, or added by the system admin
(sysadmin or sysop). A user of the BBS can then dial, in the old
modem sense, the BBS server’s phone number and gain access to
the system with a valid username and password; or if they’re new,
they have the option to create a new user.
These days, of course, the dial-up aspect has pretty much gone the
way of the Dodo (although there are still some retro stalwarts who
relish in the chronic noise of a dial-up connection), however, we
can still enjoy the retro feeling of a traditional BBS using the legacy
protocol, Telnet.

WHY?
In a world of Internet snooping, a BBS is probably one of the last bastions of
digital privacy; to some degree. A private BBS is somewhere you can connect with
likeminded individuals, to chat, swap code, reminisce, play a text-based adventure,
or simply just hang out. True, you can get hold of copyrighted or explicit content,
but that’s only if you connect to those BBSes that serve such content, just as with
the Internet.
Most BBSes follow a theme, whether that’s old DOS-based adventures, ZX
Spectrum fans, Commodore 64 gamers, or even something non-techie related, such
as a Ford Cortina owners club; no doubt swapping owner manuals, old photos of the
Cortina E and such.
In truth, a modern BBS is a bit of fun. Connecting to a system someone has
installed and built, set around a particular theme, and designed with fantastic looking
ANSI graphics, is a great pastime. It’s a form of respect, in some ways, to acknowledge
the work that’s gone into creating the BBS by connecting to it and you also get to
learn a little more about how protocols work, and how everything is connected.

176 Raspberry Pi Coding & Projects


Pi Projects: BBS Client

HOW?
Connecting to a BBS via the Raspberry Pi is quite easy, but to get the
most from it you will need to get your hands dirty in the Terminal.
As mentioned, we’re going to be using a form of the protocol
Telnet, in this instance specifically the program SyncTERM, to
emulate the old-style Terminals that support ANSI art and IBM fonts,
while connecting to the remote BBS with the Telnet protocol. You
can simply use telnet under the Terminal (once you’ve installed it),
but you’ll miss some of the glorious artwork displayed within the
majority of the BBSes.
To begin with, drop into a Terminal session on your Pi. When Once in the syncterm directory, you can begin to build from
the Terminal is fired up, enter sudo apt-get update && sudo apt- source. However, before you do that, it’s worth installing a couple
get upgrade to ensure your system is up to date. If everything of extras to ensure the BBS session works to perfection. Start by
is okay, enter: sudo apt-get install telnet. While this stage isn’t installing the following:
strictly necessary, it’s always a good idea to have the base protocol
client installed. sudo apt-get install libncurses5-dev
When telnet is installed, you can then start the procedure of sudo apt-get install libsdl1.2-dev
installing SyncTERM. In order to get SyncTERM working, you’ll need
to build it from source. By now, you should be a dab hand at this, but Once these two are installed, start the build process by entering:
here’s the process in case you’ve forgotten (along with some added
elements to help everything go to plan). sudo make

Followed by:

sudo make install

Begin by changing directory to the Downloads folder and


downloading the source code: The process may take a few minutes, so be patient. When
everything is installed, you can enter the command: syncterm,
cd Downloads\ to start the program and change the screen settings, if you wish.
wget http://syncterm.bbsdev.net/syncterm-src.tgz However, to get straight into connecting to a BBS, try one of
ls these commands:

With ls entered, you should see the newly downloaded tgz file. syncterm dura-bbs.net: 6359
To unpack the downloaded file, enter: syncterm bbs.kernelerror.com: 10023
syncterm particlebbs.dyndns.org: 6400
tar -xf syncterm-src.tgz syncterm heatwave.ddns.net: 9640
syncterm sysgod.org:23000
This will create a new syncterm-(DATE) folder, where DATE is the
current date when you’ve unpacked the contents of the tgz file. Naturally, some, or even all, of these BBSes may be offline
You will now need to change directories to: when you come to test them; they are, after all, being operated by
individuals like you and I. If they are offline, you can always get hold
cd syncterm-(DATE) of a comprehensive list of active servers by visiting https://www.
cd src telnetbbsguide.com/bbs/list/brief/.
cd syncterm
GET CONNECTED
You can mesh these directories together, but, for the sake It’s worth spending some time finding the sort of BBS that suits your
of keeping things simple, we’ll stick to one folder at a time. tastes. As you’ll see by visiting the aforementioned website, there’s
Also, remember you can hit the Tab key to auto-complete a over 500 BBSes currently listed, so somewhere in there a BBS could
directory name. be your new online haunt.

www.pclpublications.com 177
Pi Projects

Pi Projects: Weather Station


The Raspberry Pi has offered its userbase a superb platform to science. There are Raspberry Pi
projects that involve the International Space Station, alongside NASA and ESA-led applications.
However, it’s an Earth-based project that’s taken the community by storm.

IT’S RAINING PI, HALLELUJAH!


Weather stations have been available to the project-
minded public since long before the Raspberry Pi entered
the scene, but thanks to the Pi’s unique specifications,
a new generation of weather station has emerged; and
they’re really quite remarkable.
As with a lot of Raspberry Pi projects, the market has
become flooded with various hardware, kits, and HATs
that will enable you to set up a simple, or complex,
weather station. The more experienced weather station
and Raspberry Pi user will probably lean toward buying in
the components individually, as opposed to an entire kit,
but for the rest of us the kit-form versions are an excellent
start to a project that can quickly grow over time.

WHY?
With our smart devices connected to that measures ambient temperature, pressure and humidity.
everything around us all the time, having Why indoors? There are a number of reasons. Perhaps you’re in
a multi-limbed weather station, perched charge of a collection of servers, and while the company you work
precariously on the end of the garden for may not be able to stretch to a fully sealed environment machine
shed, measuring the amount of rainfall room, you could fill the gap with a great collection of sensors
and in what direction the wind is blowing, attached to a Raspberry Pi. You may have some from of allergy,
may seem a little unnecessary; since where precise control of your indoor environment is important.
your phone could tell you all that already Maybe you look after some exotic animals, in a room a where
with just a swipe or two. However, that air pressure, humidity and such are vital to the creature’s health.
discounts the pleasure of creating your Needless to say, there are
own project and measuring the results as plenty more examples.
they change from one day to the next. In short, setting up a
Any project, regardless of whether it’s on a Raspberry Pi or not, weather station is simply a
is something from which to learn. In the case of a Raspberry Pi driven fun project. Setting aside
weather station, the user can learn about all manner of electronics, the things you’ll learn from
connectivity, some simple engineering, and coding, even before we getting one up and running,
get onto the varying aspects of meteorology. you’ll eventually have a
The weather station physical piece of hardware
project doesn’t necessarily that can, with moderate
need to be an all-powerful accuracy, measure your
outdoor contraption either. environment and display
Basically, there are two routes that data in a number of
you can opt to take: the graphs and charts. It’s quite
outdoor model, measuring cool, when you stop to think
wind speed/direction, precipitation and so on, and an indoor model about it.

178 Raspberry Pi Coding & Projects


Pi Projects: Weather Station

Pimoroni Enviro Phat – The


SOME OPTIONS? Enviro pHAT is an add-on sensor
To go into all the currently available Raspberry Pi weather station for the Raspberry Pi that includes
options will take more space than we’re currently able to offer four different sensors to monitor
here, but let’s have a quick look at some of the best selling kits temperature, pressure, light
and components. levels, and motion. It’s ideal for
indoor environment monitoring
Weather Meter Kit – For outdoor and, thanks to some nifty Python
weather monitoring, we have the libraries and code, you’re able to display the data via a web page
Weather Meter Kit as sold by CPC for and view the variables remotely.
around £77. The kit comprises of three
main component sensors that measure
wind speed, wind direction, and rainfall. Cyntech WeatherHAT – The
The rain gauge is a self-emptying bucket WeatherHAT from Cyntech can turn
that’s capable of activating for each the Raspberry Pi into a weather
0.011-inch of rainfall collected, while the display station. While not obtaining
anemometer activates a closure switch data directly from an external
every 1.492mph once per second. The source (instead using one of the
wind direction module can display up to many localised, weather monitoring
sixteen different positions, and the kit stations), it does offer seven RGB LEDs to highlight the current
comes complete with full assembly instructions. and upcoming weather. Controlled via Python, the HAT can help
provide a good coding base for future weather station projects.

Velleman WS3080 Weather Station – The


Velleman WS3080 Weather Station is one WeeWX – When you collect the
of the higher-end products that can interact necessary hardware together (the
with the Raspberry Pi. This outdoor mounted various sensors you’ll need and so
station is capable of monitoring rainfall, on), you’ll need a good piece of
wind speed and wind direction, air pressure, software to help collate all that data
wind chill temperatures, air temperature, and display it in a readable fashion;
and UV light levels. It features alarms for this is where WeeWX comes in.
temperature, humidity, wind chill, dew point, WeeWX is a Python-based program
wind speed, air pressure and storms, and that can interact with many different weather stations to produce
comes with a separate LCD transmitter. graphs and reports, and even publish the data to HTML on a web site.

WHERE NEXT?
As you can imagine, it’ll take some time to get everything together, program the components, and collate the data you want to view. Once all
that’s gathered, though, what next?

There are some websites available that display localised weather from independent sources such as a back garden weather station, so when
you’ve got everything up and running, try looking out for such projects and start collaborating. Also, consider creating a Twitter account for
the Raspberry Pi weather station and Tweeting the local weather.

www.pclpublications.com 179
Pi Projects

Common Raspberry Pi
Problems
The Raspberry Pi hardware and software is pretty reliable and problems are more often due
to set up errors rather than anything to do with the hardware. However, there are times when
hardware can seem to be at fault, so here are a few of the more common issues you might
encounter when using your Raspberry Pi.

TROUBLESHOOTING YOUR RPI


The Raspberry Pi is a surprisingly stable bit of kit, but there is always the chance of encountering problems. If you’re really stuck there are
apps available which can help diagnose problems on the RPi.

A blinking red power LED indicates With the current


RED POWER LED IS BLINKING COLOURED SPLASH SCREEN
problems with the power supply. firmware, a
On model A and B, it is hard-wired to the 3.3V power supply rail. If it is blinking, coloured splash screen is displayed after GPU firmware (start.
it means the 5V power supply is dropping out. Use a different power supply. elf) is loaded. This should be replaced by Linux console a
On the model B+ and also the A+, the circuit has been improved to give a much second later. However if the coloured screen remains, it
more reliable warning of poor power quality. The red power LED is wired to an suggests the kernel.img file is failing to boot. Try replacing it
APX803 supervisor which kicks in when the 5V power supply drops below with a known good one.
4.63V. If it does, the LED will blink. Check your connections, cable and
power supply. Immediately after displaying the splash screen, the Pi starts
consuming a little more current. If the Pi resets at that
moment, it is an indication that the power supply isn’t able
to deliver the full current that your Pi requires but dips its
output voltage below a minimum when loaded with the full
current the Pi needs.

GREEN LED BLINKS IN A SPECIFIC PATTERN


1 flash: Possibly you have a RPi from Micron.
Take a good look at the processor if it
says M with an orbit round it. Using the
latest software will solve your problem;
also make sure you have a 4Gb SD card,
as a 2Gb doesn’t work.
2 flashes: The SD Card cannot be read. A solution
could be to forma the card and flash
Raspbian with Pi Installer from Terminal.
3 flashes: Start.elf not found.
4 flashes: Start.elf not launched.
7 flashes: Kernel.img not found.
8 flashes: SDRAM not recognised. You need newer
bootcode.bin/start.elf firmware.

180 Raspberry Pi Coding & Projects


Common Raspberry Pi Problems

NO USB DEVICE WORKS


The most common cause of USB devices working is low power
supply voltage from a bad PSU, cable or USB hub; but it could
also be that no clock signal is present. Return the board for a
replacement if you think this is the case but before coming to this
conclusion, confirm known good peripherals. A significant number
of USB keyboards are not compatible with Raspberry so make sure
you are using one made for Pi.

Connecting a
RASPBERRY PI NOT RESPONDING TO KEY PRESSES KEYBOARD OR MOUSE INTERFERES
keyboard
WITH A USB WI-FI DEVICE and or
This is most often caused by inadequate power. Use a good power
supply and a good power cable. Some cheap cables that work with a mouse while a USB Wi-Fi device is connected, may cause
mobile phone, cannot fully power the Pi. Some USB devices require a one or both devices to malfunction. Tests point to
lot of power; most will have a label showing interferences in the 2.4 GHz frequency band in
the voltage and mA requirements. which both Wi-Fi sticks, as well as USB
Each one should be 5v 100mA max. keyboards transmit data. Changing
Any more than this and they must the channel on the wireless
be used with a powered USB hub. access point should fix the
Try unplugging every USB device problem completely.
except the keyboard. You should
also note that some keyboards
have built in hubs and can try to
draw 150mA; Pi can only handle
100mA per USB slot without a
hub. Use the latest software too.

SD CARD PROBLEMS
If you have problems, check you have the latest firmware version
first. If that is not the problem, try the following.
• Some SD cards do not work on the Pi, so check the list of known
SD cards on the official Pi website.
• If you are having problems setting up your SD card you might
want to start by erasing it completely, especially if it has been
used elsewhere and still contains data or partitions.
• Windows and Mac users can download a formatting tool from
the SD Association: https://www.sdcard.org/downloads/
formatter_3/
• Reformatting cards is also easy to do in a digital camera.
• After writing the image to the SD card, verify that you can see the
boot partition when you insert the SD card into your computer.
The partition should contain a number of files, including start.elf
and kernel.img. If you do not see these files on the SD card, you
have made an error writing the image file.
• If you are manually preparing your SD card on Linux or macOS
using the dd command, this operation will completely erase any
existing data and partitions. Make sure you write to the whole
card (e.g. /dev/sdd) and not to an existing partition (e.g. /dev/
sdd1).
• If you put the SD card into your PC in an attempt to write the Pi
operating system onto it and the PC tells you the card is write-
protected, even with the write-protect tab in the correct forward
position you may have a faulty SD-card rewriter.

www.pclpublications.com 181
Re
o
a
re
d The Complete

M
Manual Series
Tech Guides
Available on

For a full list of titles


available please visit:
www.pclpublications.com
Want to master your PC or Laptop?
Then don’t miss our NEW Windows 10 & 11
magazine on now!

Visit us at: www.pclpublications.com


The Complete Manual Series: device. It remains the purchaser’s sole responsibility to determine Linux Mint, NASA, and Apple. Additional images contained within
the suitability of this book and its content for whatever purpose. this publication are reproduced under licence from Shutterstock.
Raspberry Pi Coding & Projects We advise all potential buyers to check listing prior to purchase Any images reproduced on the front cover are solely for design
ISBN: 978-1-914404-51-1 for confirmation of actual content. All editorial opinion herein is purposes and are not representative of content.
Published by: Papercut Limited that of the reviewer - as an individual - and is not representative of Prices, international availability, ratings, titles and content are
Digital distribution by: Readly, Zinio & Pocketmags the publisher or any of its affiliates. Therefore the publisher holds subject to change.
© 2022 Papercut Limited All rights reserved. No part of this no responsibility in regard to editorial opinion and content. All information was correct at time of publication. Some content
publication may be reproduced in any form, stored in a retrieval This is an independent publication and as such does not may have been previously published in other volumes or titles.
system or integrated into any other publication, database or necessarily reflect the views or opinions of the manufacturers or
commercial programs without the express written permission of hardware and software, applications or products contained within. Papercut Limited
the publisher. Under no circumstances should this publication and This publication is not endorsed or associated in any way with Registered in England & Wales No: 04308513
its contents be resold, loaned out or used in any form by way of The Raspberry Pi Foundation, The Linux Foundation, ARM Holding,
trade without the publisher’s written permission. While we pride Canonical Ltd, Python, Debian Project, Linux Mint, Microsoft, ADVERTISING – For our latest media packs please contact:
ourselves on the quality of the information we provide, Papercut Lenovo, Dell, Hewlett-Packard, Apple and Samsung or any Richard Rowe - [email protected]
Limited reserves the right not to be held responsible for any associate or affiliate company. All copyrights, trademarks and Will Smith - [email protected]
mistakes or inaccuracies found within the text of this publication. registered trademarks for the respective companies are INTERNATIONAL LICENSING – Papercut Limited has many great
Due to the nature of the tech industry, the publisher cannot acknowledged. Relevant graphic imagery reproduced with publications and all are available for licensing worldwide.
guarantee that all apps and software will work on every version of courtesy of Lenovo, Hewlett- Packard, Dell, Microsoft, Samsung, For more information email: [email protected]

You might also like