000 Getstartedrpi Digital
000 Getstartedrpi Digital
000 Getstartedrpi Digital
STARTED
WITH RASPBERRY PI
ESSENTIALS
LEARN | CODE | MAKE
Y
ou are holding, in your hands, a piece of history.
This isn’t just a book about a computer: It’s a book
with a computer.
Not just any computer either. Raspberry Pi 3A+ is an
incredibly well-designed microcomputer. And it’s part of
the most creative computer family on Earth.
With a Raspberry Pi, you can hack, make and build all
kinds of different things. It could be a digital camera, or a
retro games console, or a home media centre. Or a sensor on
board the International Space Station, or a programmable
Minecraft machine.
Almost everything you need to get started with a
Raspberry Pi computer is inside this kit, including a
memory card for the operating system and storage. All you
need to add is a USB keyboard and mouse, HDMI cable, and
5V micro USB power supply (such as a phone charger).
Our tutorials will guide you, step-by-step, from setting
up Raspberry Pi 3A+ hardware to learning how to use the
Raspbian operating system, through to hacking electronics
with the GPIO pins on your Raspberry Pi 3A+.
You’ll also learn how to program a computer with Scratch
and Python, two of the world’s best programming languages.
We’re so glad you’ve got Get Started with Raspberry Pi
with the Official Starter Kit. Now let’s begin…
Lucy Hattersley
Editor
This bookazine is printed on paper sourced from This official product is published by Raspberry Pi (Trading) Ltd., Maurice Wilkes Building, St. John’s Innovation Park, Cowley Road,
sustainable forests and the printer operates an Cambridge, CB4 0DS. The publisher, editor and contributors accept no responsibility in respect of any omissions or errors relating
environmental management system which has to goods, products or services referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is
been assessed as conforming to ISO 14001. licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISBN: 978-1-912047-70-3.
INSTALLING RASPBIAN 24
GETTING
STARTED
WITH RASPBERRY PI 3A+
Packing an incredible amount of power into a small form
factor, Raspberry Pi 3A+ is a superb single-board computer
R
aspberry Pi 3A+ is a low-cost microcomputer keep the size down, it lacks an Ethernet port and
packed onto a single board. While smaller than features a single USB port – so you’ll need a USB hub
a Raspberry Pi 3B+, it packs all of the latter’s to connect more than one device.
processing power into a more compact form factor A full-size HDMI socket enables you to use a
– not as tiny as a Raspberry Pi Zero, but still small standard HDMI cable to connect to a TV or monitor. It
enough to fit in the palm of your hand. uses the same micro USB power input as most other
Despite its diminutive stature, Raspberry Pi 3A+ Raspberry Pi devices, and you can use an official
is no toy: it is a fully-fledged microcomputer with a adapter or salvage a high-quality power supply from a
1.4GHz quad-core ARM CPU and 512MB RAM. It packs mobile phone (2.5 A output is recommended).
enough technology to run the full version of the Other ports include a 3.5 mm AV jack (which you can
Raspbian operating system with ease. use to output audio or connect to a non-HDMI TV) and
Raspberry Pi 3A+ is a versatile device that’s ideal a connector to attach a Raspberry Pi Camera Module
for creating Internet of Things and embedded projects to turn Raspberry Pi 3A+ into a low-cost camera for
requiring more power than a Raspberry Pi Zero. To taking photos and recording videos.
RASPBERRY PI 3A+
Powerful processor Small form factor
Raspberry Pi 3A+ packs It offers a full computer
a powerful 1.4GHz experience, complete
quad-core ARM 54 with the Raspbian
CPU with 512MB RAM, operating system, in a
enabling it to run a smaller form factor than
full desktop operating a full-size Raspberry Pi
system with ease. 3B+ or 4 model.
A full-size
HDMI port means
you can connect a
TV or monitor using a
standard HDMI cable
Devices like
keyboards and
This connector enables mice are connected
you to add a Raspberry Pi to the USB port;
Camera Module to take you may need a
photos and videos USB hub
GPIO to go
The 40-pin GPIO
(general-purpose input/
output) header enables
Raspberry Pi to talk to
other hardware, from
The official case supplied in your Starter Kit
LEDs and buttons to protects Raspberry Pi 3A+ while offering access to all its
ports and pins, thanks to cutouts and a removable lid
special add-on boards.
EQUIPMENT
YOU’LL NEED
All the kit you need to get a Raspberry Pi up
and running for the first time
Y
ou don’t require much To get the most out of your
to get your Raspberry Pi Raspberry Pi in the long term,
started: a smartphone though, you should use high-
charger, a recycled HDMI cable, quality components.
and a keyboard and mouse are all Not all USB power supplies
you need. are born equal. A reliable
Most items can be sourced branded supply (such as the
from spare computer hardware official Raspberry Pi one) will
around the house, or begged and provide a steady stream of
borrowed from friends and family. power, even when you attach
If you’re looking for the ultimate multiple devices to Raspberry Pi.
in low‑cost computing, Raspberry Any equipment you can’t recycle
Pi is it. can be picked up from various
You should be able to source, online retailers, such as The Pi Hut
salvage, and scavenge most and Pimoroni. For official add-ons,
equipment you need to get a visit the Raspberry Pi products page
Raspberry Pi up and running. (rpf.io/products).
Raspberry
Pi 3A+ can be used
without a case, but
it’s better protected
inside one
The official
case features
cutouts to provide
easy access to
all of the ports on
Raspberry Pi 3A+
SET UP YOUR
RASPBERRY PI 3A+
Discover how to set up your Raspberry Pi 3A+ Starter Kit and start using it
S
o, you’ve unpacked your Starter Kit and keyboard and mouse you’ll either have to daisy-chain
You’ll Need are wondering what to do with all the bits? them using the USB port on the keyboard (if it has
Fear not, as here we’ll guide you step by step one) or use a USB hub.
> Your Starter Kit
through the process of setting up the hardware and On another edge of the board, you’ll see a full-size
> USB mouse installing the Raspbian operating system. HDMI port for connecting your Raspberry Pi 3A+ to a
> HDMI cable Raspberry Pi 3A+ may be small, but it’s a fully TV or monitor – all you need is a standard HDMI cable.
> micro USB fledged computer. To keep the size of the board down, Turning your Raspberry Pi 3A+ board over, you’ll
power supply however, it lacks the Ethernet port featured on larger see a small silver slot – this is where you’ll insert your
models (such as Raspberry Pi 3B+ and 4) and there is microSD card from the Starter Kit. Let’s start putting
only a single USB port. Therefore, to connect both a it all together…
micro USB
power port:
plug in your
power supply
here, such as a
mobile phone
charger
>STEP-01 >STEP-04
Put it in the case Connect to a TV
Place your Raspberry Pi 3A+ into the red base of the Insert a standard HDMI cable into the large HDMI
case, making sure that the USB, HDMI, 3.5 mm AV, and port and connect the other end of the cable to an
power ports line up with the cutouts in the case. HDMI socket on your TV or monitor. Turn the latter
on and select the appropriate video input.
>STEP-02 >STEP-05
Insert microSD card Power it up
Turn the case over. That silver slot takes microSD You’re now ready to power up your Raspberry Pi.
cards like the NOOBS one in your Starter Kit. Insert Connect a power supply (such as a phone charger) to
the card into the slot with its metal contacts facing its micro USB port. There is no on/off switch, so turn
down – it’ll only fit one way. on the power at the mains.
>STEP-03 >STEP-06
Plug in a mouse Install Raspbian
Connect a standard mouse to the USB port. If using a A menu will soon appear on screen. Click the checkbox
keyboard with its own USB port/hub, you could daisy- to the left of Raspbian, then click Install – it’ll take a
chain a keyboard and mouse, but only a mouse is while. When prompted, click OK to start up Raspbian
needed for initial setup. and after a few seconds you’ll see its desktop interface.
INSTALLING
RASPBIAN
Discover how to use NOOBS to quickly set up the Raspbian
operating system on your Raspberry Pi
B
efore you start using your Buster, hence the name Raspbian operating systems. Beginners
Raspberry Pi, it needs to (sometimes you’ll hear it called should start with NOOBS (New Out
have an operating system ‘Raspbian Buster’). Of Box Software). More advanced
(OS). This is the software used to You can install a range of users may copy an image file
start the hardware, and open and different OSes on a Raspberry Pi, containing a whole operating
close programs. including LibreELEC, a version of system directly to the SD card.
Most Raspberry Pi owners use the Kodi Entertainment Centre In your Starter Kit is a microSD
an open-source operating system software. To view and install other card (inside the larger SD adapter)
called Raspbian, which is based on OSes, click on the ‘Wifi Networks’ preloaded with NOOBS.
Linux. The current version is based option in the NOOBS menu. If you wish to use a different
on a version of Linux called Debian Raspbian is the official OS and microSD card, you must first
the one most beginners should start wipe it using the Windows FAT32
with, however. It’s the simplest format The easiest way to do this on
to install, easiest to use, and most a Mac or Windows PC is to use SD
projects and tutorials use Raspbian Card Formatter (magpi.cc/sdcard).
as their base. Connect your microSD card to a
Mac or Windows PC, typically using
NOOBS automates the
process of installing
Start with NOOBS a microSD-to-SD card adapter or a
Raspbian. Select the There are two approaches to USB card reader, and use SD Card
Raspbian option and
click on Install to run it installing Raspbian and other Formatter to erase the card.
OPERATING SYSTEMS
Raspbian Windows 10 IoT Core Ubuntu MATE
The official operating system is the Not the full version of Windows, Ubuntu is one of the world’s most
easiest to use, and the one beginners but Windows 10 IoT Core enables popular Linux operating systems, and
should start with. It works a lot like programmers to run Internet of Ubuntu MATE is a lightweight version
other popular operating systems. Things and embedded projects. that runs just fine on the Raspberry Pi.
SETTING UP
and the message ‘OS(es) Installed
NOOBS
Successfully’. Click OK to start
using your Raspberry Pi.
Format SD card
Open SD Card Formatter and you'll see
P I
RRY
R B E
E
RAS P
START
GUIDE
S
o, you’ve followed our guides and now
Get to know
have your Raspberry Pi 3A+ hardware set
up and have installed Raspbian from the
NOOBS microSD card. What next?
We’re here to help with a Starter Guide that
Raspberry Pi
to configure its settings, introduce you to some
awesome applications, and reveal how to install
extra software. We’ll also show how to connect
to and control your Raspberry Pi remotely from
By Sean McManus another computer using SSH and VNC.
05 Volume control. Right- hover the mouse pointer wirelessly control your store your files in the
click to select audio output. over the icon to see your Raspberry Pi device. /home/pi folder.
Raspberry Pi’s IP address.
06 WiFi options. Turn 08 File Manager. Use the 09 With basic, scientific,
WiFi on and off, and switch 07 Manage Bluetooth hierarchical browser on and paper modes, this
networks here. If the icon connections. You can use the left or the Go menu to calculator is handy. Find it
is blue like this, you’re Bluetooth devices such find devices connected to in the Accessories section of
connected. You can also as keyboards and mice to Raspberry Pi. You should the applications menu.
Raspberry Pi Configuration
Need to adjust some settings? The To adjust the amount of memory for
Raspberry Pi Configuration tool is the GPU or to set older Raspberry Pi
in the Preferences section of the models to run faster (overclocking),
applications menu. In its System tab, visit the Performance tab.
you can change your password, adjust You can change the time zone,
display options, and set Raspberry keyboard, and other geographic
Pi to boot to the command-line options in the Localisation tab.
interface (CLI) instead of the desktop. There are separate options in
In the Interfaces tab, you can Preferences for configuring the
enable connections, including appearance, audio, main menu,
remote GPIO access and the camera. mouse and keyboard, and screen.
FEATURE
O ME S
AWES
ICA TION
APPL
Discover some of the software Claws Mail | INTERNET
Send and receive email. The setup wizard
that comes with Raspbian, and helps you add your email account, and the
streamlined interface shows you your mailboxes,
find out how to install more message list, and a preview of the selected message.
R
aspbian comes with a selection of pre-
installed software (which depends on VLC | SOUND & VIDEO
which version you install), so you can start Listen to music while you’re coding using
working, learning, and making things straight VLC, a fully featured media player for
away. Ranging from productivity suites to games, music and video. It can play digital files, streams,
you’ll find a well-curated collection of software is and physical media such as CDs and DVDs.
just a click away, in the applications menu. There
are lots more packages to browse and install, too.
Minecraft Pi | GAMES
We call it a game, but it’s more a way
LibreOffice Writer | OFFICE of life. With Minecraft Pi, you can build
No computer is complete without a word things in Creative mode, and write programs to
processor. LibreOffice Writer has all the change the (game) world.
font and formatting options you would expect, and
has basic compatibility with Microsoft Word.
Python Games | GAMES
These tea-break games are fun, but
LibreOffice Calc | OFFICE they’re also great Python demos. Find the
Work out your budgets with this code in the /usr/share/python_games folder, and
spreadsheet package. If you’re familiar open it in a Python editor to see how it works.
with Microsoft Excel, you’ll feel at home here.
LibreOffice Calc can open and use typical Excel files.
SmartSim | PROGRAMMING
Experiment with designing and testing
LibreOffice Impress | OFFICE digital logic circuits. You can develop
If you’re presenting to a room of people, custom components and then incorporate them
don’t panic: Impress has your back. Use into other circuits. Download examples and read
it to craft and display your slide deck. It’s largely tutorials at smartsim.org.uk.
compatible with Microsoft PowerPoint.
Mathematica
PROGRAMMING
Good for more than just maths,
Mathematica uses the Wolfram language,
which has data and intelligence built
in. Install it from Recommended
Software, in the Preferences section of
the applications menu.
Installing software
The easiest way to manage software is to use the Add / Remove
Software tool in the Preferences part of the applications menu. It
provides a visual front-end for the package manager.
You can click a category on the left to browse applications, or
enter a keyword in the search box in the top-left to look for a
particular application. Choose the applications you want to install
by ticking the box beside them. Some packages require other
packages to work properly, but the tool will take care of that for
you. To remove an application, untick its box. When you’ve made
your choices, click OK to install or remove your software.
FEATURE
NECTED
T CON
GE If your Raspberry Pi is up in a tree photographing nature, you don’t
want to climb up there just to update it. Log in remotely and take control
T
here are two technologies you can use to The software for SSH is pre-installed on
connect to your Raspberry Pi from another Linux, macOS, and Windows 10. Start by opening
device: Secure Shell (SSH) and Virtual the command line. On a Mac, find it by typing
Network Computing (VNC). Before you can use ‘Terminal’ into the Spotlight search. On Windows
them, they need to be switched on in the Raspberry 10, Use +R to open the Run dialog box, then
Pi Configuration settings. To do so, click the type in cmd.
Interfaces tab, then enable SSH and/or VNC. Once you’re in the command line, enter
Both approaches require you to know the IP ssh pi@198.51.100.0, but replace the numbers
address of your Raspberry Pi. The easiest way to find with the IP address of your own Raspberry Pi
it is to hover the mouse pointer over the WiFi icon device. The ‘pi’ bit is your username.
in the taskbar. Alternatively, click the Terminal icon
and enter ifconfig. It will show you all your network
connections. You’re looking for an IP address, which
SH enables you to use
S
will be four numbers with a dot between them,
like 198.51.100.0. You’ll find it beside ‘inet’, in the
the command line on your
details for wlan0 if you’re using WiFi or in the eth0 Raspberry Pi remotely, so
summary if you’re plugged in to the network.
it’s very handy
Using SSH
SSH enables you to use the command line on The first time you connect to a device using SSH,
your Raspberry Pi remotely, so it’s very handy for you’ll see a warning that shows the ECDSA key
installing software and fixing configuration files. for the device you’re trying to connect to. You can
You can’t use SSH to run any applications that need (if you wish) validate that this is correct by using
the graphical desktop, though. ssh‑keygen -l -f /etc/ssh/ssh_host_ecdsa_key.pub
in the Raspberry Pi Terminal. But it’s usually OK to
Using VNC
Virtual Network Computing (VNC) enables you to
remotely access the Raspberry Pi desktop, so you
can manage files and run software using it. Some
people use VNC to share their keyboard, mouse, and
monitor between a PC and Raspberry Pi.
Raspbian includes VNC Server, which runs
automatically in the background if you’ve enabled it
in your settings. You’ll need to download and install
Send files from Raspberry Pi using the File Transfer
VNC Viewer (magpi.cc/FuGnye) on the device you
option in VNC Server in Raspbian. Use the three-bars
want to use to control Raspberry Pi. VNC Viewer is
menu (top-right) to find it.
available for Windows, macOS, and Linux. There are
also Android and iOS apps, so you can use VNC to
control Raspberry Pi from a mobile device, although
it’s rather fiddly without a real mouse and keyboard.
Optionally, by creating a RealVNC account and
registering your Raspberry Pi, you can then access it
from anywhere in the world using VNC Viewer.
When you start VNC Viewer, it’ll ask you to enter
a VNC Server address. This is the IP address you
noted when you ran ifconfig on your Raspberry Pi.
The first time you connect to a device, VNC
Viewer warns you that it has no record of
connecting to this device before, and shows you the
device’s signature and identification catchphrase.
To verify you’re connecting to the correct device,
click the VNC icon on the right of the taskbar in
Raspbian to see your device’s details.
VNC Viewer prompts you to enter the username
and password for the device you’re connecting to.
You’ll then see your Raspbian desktop in the VNC
Viewer window. You can now use your keyboard
and mouse (or touchscreen on a mobile device) Use the toolbar in VNC Viewer to start a chat
to control the Raspbian desktop, including using session with anyone using the server (Raspberry Pi
programs installed on Raspberry Pi. device) and anyone else connected to it remotely.
FEATURE
TO JOY
CODE
Raspberry Pi comes with everything
you need to start programming
I
f you’ve never programmed before, you’re
in for a treat. Raspbian comes with several
integrated development environments (IDEs)
you can use to write your own programs, supporting
languages that are friendly to use, and fun to tinker
with. If you’re a veteran coder, you’ll find powerful
IDEs are included to help you be productive, too.
Scratch 2 Node-RED
LANGUAGE: SCRATCH LANGUAGE: JAVASCRIPT/NODE-RED
With its friendly drag-and-drop commands and Node-RED enables you to use a flowchart to program
a library of sprites and sound effects, Scratch data flows for Internet of Things applications on
makes it simple to get started with coding. By Raspberry Pi. It uses JavaScript, the language of the
minimising typing, and guiding you to sensible web. Run the Node-RED console in Raspbian and
block combinations, it helps you to avoid common then visit http://localhost:1880 in your browser to
mistakes. Don’t be fooled by its accessibility, program it. For help, see nodered.org.
though: it’s a fully-fledged programming
language, with plenty of potential.
Greenfoot
LANGUAGE: JAVA
Thonny Java is one of the
LANGUAGE: PYTHON world’s most popular
Python is one of the most popular languages on programming
Raspberry Pi, and Thonny is our favourite way to languages. Greenfoot
LEARN TO
Sean
AUTHOR
McManus
Author/co-author
of inspiring coding
books including
Mission Python, Cool
Scratch Projects
in Easy Steps, and
Raspberry Pi For
Dummies. Get
free chapters at
Sean’s website.
sean.co.uk
p24 START
CODING WITH
SCRATCH
p27 CODE A
QUIZ GAME
WITH PYTHON
p30 MAKE AN
LED TORCH
L
earning to code can be one of the most profound WITH PYTHON
skills you will ever develop. With code, you can
control a computer. You can get it to do things for you,
and also control gizmos and other computers. Kick back and
let your computer do all the work. p31 BUILD AN
Sure, that’s cool. But coding is about more than that. It’s
ELECTRONIC
about understanding how computers work, and getting a
better understanding of how technology – and the modern GAME
world – works. It’s about breaking down problems into little
bits and solving them. It’s an amazingly helpful life skill.
That’s why it’s profound.
On a more practical level, knowing just a little code can
lead to better job opportunities; a little more can open up
well-paid and fun jobs. It’s an impressive skill to put on
your CV and anybody can do it. Anybody.
Coding is a lot easier than you think. And putting the
power of computing and digital making into the hands of
people is what Raspberry Pi is all about.
Raspberry Pi is ‘the little computer that could’, and
you’re ‘the person who can’. Don’t worry: you’ve got
this. We can help you get started.
Start coding
with Scratch
Beginners, arise! It’s time to take your first steps with
coding, as we introduce you to Scratch and Python, with
a sprinkling of twinkling LEDs! By Sean McManus
B
Start Scratch 2
eing able to write programs is like a superpower:
it means you can get your computer to do
01 Open Scratch by clicking on the Raspberry Pi
whatever you want. Join us as we show you Menu icon and choosing Programming > Scratch 2.
how to make your first programs using Scratch and You will see Scratch interface and a single
Python. You’ll also see how easy it is to build simple character in the top-left, known as ‘Scratch Cat’.
electronics projects. To control the Scratch Cat, we’re going to drag
A program is just a set of instructions. In Scratch, blocks from the Blocks Palette into the Scripts Area
the instructions are written with visual blocks that and join them together.
lock together to make a sequence called a script. Start by clicking on Events and drag the
The blocks are colour-coded to help you find when clicked block to the Scripts Area.
them. To find the brown blocks, for example, Now click on Motion and drag a
click the brown Events button above the point in direction 90 block and connect it the to
Blocks Palette. the bottom of the when clicked block.
Scratch makes coding easier, because you Click on the fields in the blocks to edit the
don’t need to worry about the spelling of numbers. Click on ‘90’ and change it to ‘0’.
commands. And everything is laid out in Now click and drag the blocks below, and edit
front of you. their numbers, to build a script for Scratch Cat.
This script runs when you click the green flag
above the Stage. It sets the cat’s movement
direction to up, puts the cat in the top-left corner
of the Stage, and sets it to always face left or right.
Then, the movement blocks inside the forever
Understanding bracket keep the cat moving all the time.
03
02
01
Send a broadcast
02 The moving objects in Scratch, including
Click the Bananas sprite to add it to the Sprite
List. Notice that its Scripts Area is blank. We’ll Top Tip
the cat, are called sprites. One sprite can send a give Bananas two scripts. The first one sets the
message to all the other sprites using a broadcast. sprite’s size and makes it invisible when you click Get the
You can’t hear it or see it on screen, but sprites the green flag. The second runs when the cat right sprite
can listen for it, and then start a script when they broadcasts its fire message. Click and drag the
Make sure you’re
receive it. We’ll use a broadcast to make the cat blocks below to the Scripts Area.
adding scripts to
throw some bananas. Click the brown Events
the correct sprite.
button, and add the two blocks below to the Scripts You can select a
Area. This new script doesn’t join to the existing sprite by clicking
script (from Step 1) – it sits on its own in the same it in the Sprite List.
Scripts Area.
You need to change ‘message1’ to ‘fire’. Click
the down arrow next to ‘message1’ in the broadcast
block and choose New Message. Enter the message
name ‘fire’ and click OK.
As the program is running, when you tap SPACE,
the broadcast message is sent silently. Crafty!
Top Tip
Blocks inside
Where next?
blocks We’re huge fans of Scratch at The MagPi, so
check out our past issues online for more Scratch
Some blocks can tutorials. Issue 5 includes a memory game, like
go inside other Simple Brian. Issue 34 has a multiple-choice quiz,
blocks. In Step 3, and our 2018 Annual included an introduction
the y position to electronics and Scratch. See issue 76 for
block keeps the a roundup of resources to help you learn
sprite’s y position Scratch, and don’t forget there’s a Scratch book
the same while in The MagPi’s own Essentials series
its x position (magpi.cc/learnscratch) and the Code Club Book
changes. of Scratch (magpi.cc/ccbook1).
Finishing touches
06 Let’s add a simple timer to stop the sprites
moving after 30 seconds, and make the monkey
react when it sees incoming bananas. Add these
two scripts to the monkey sprite. Now the game is
complete, why not try experimenting with it? Can
you make the monkey move erratically instead of
disappearing when it’s hit? Can you change the
sprites’ positions and directions to turn the game
sideways, making it more like Space Invaders?
What about adding more targets to hit? One of the
best ways to learn to code is by experimenting with
existing programs.
M
any people progress from Scratch
to Python, a programming language
that is powerful, easy to get started
with, and much easier to read and write than
other languages.
We’re going to make a simple quiz question
generator that strips the vowels and shuffles the
01
spaces in a phrase. The player has to work out what
that phrase is.
We’ll be using Thonny, which provides a
friendly single-screen environment for running
and testing Python code. Like Scratch, the Thonny
IDE (integrated development environment) comes
pre-installed in the Raspbian with Desktop and 03
Recommended Software operating system.
02
Create a list of questions
01 As well as variables, Python has lists, which
can store multiple pieces of information. Our
program creates a list called questions. Each item
in the list is a piece of text, known as a string. In Python, strings are surrounded by double quotes
01 Type in and edit
to show where they start and end. The whole list is your program
code here
enclosed in square brackets, and there are commas
between the list items. Type in the code below, save 02 Enter direct
commands and
Getting
your program, and then click Run. If it worked, you see program input
should see no error messages in the Shell window. in the Shell here
indentation right 03 Keep track of the
import random data your program
Python uses indentation to show which is processing here
instructions belong to a function, an if statement,
or a repeating section. As you can see in Step 3 questions = ["As You Like It",
(overleaf), you can have multiple levels of "The Tempest", "Measure for Measure",
indentation. The last line belongs to the if "Much Ado About Nothing", You’ll Need
instruction, and that is repeated inside the for "The Comedy of Errors",
loop. The best way to get the indentation right is > Raspbian with
"King Lear", "Cymbeline",
to remember the colon at the end of the previous Desktop and
"Hamlet", "Coriolanus", "Othello",
line. Then, Thonny will add the indentation for you Recommended
automatically. If you forget, use four spaces at the "Love's Labour's Lost", Software
start of the line to insert the indentation. You’ll still "King John", "Julius Caesar",
> Thonny
need to fix that missing colon, though! "Edward III"]
Where next?
You can find Python code to dissect in most issues
of The MagPi. Issue 53 (magpi.cc/53) includes
a more in-depth beginner’s guide to Python,
Pick a random question
Top Tip 02 Python includes modules of prewritten
covering variables, looping with while and for,
branching with if, and functions, which we’ll
code you can use, such as the random module cover shortly in this guide. Issue 54 (magpi.cc/53)
Pesky we imported in Step 1. The first new instruction introduces object‑oriented programming in both
Scratch and Python. Issue 73 (magpi.cc/73)
punctuation! creates a new variable called chosen_phrase and
includes a roundup of Python books and online
puts a randomly chosen question into it. The resources. There is a book in our Essentials
Take care to
second line converts the chosen_phrase to upper series too, called Make Games with Python
add the colons
at the end of
case. Run the program a few times and look at the (magpi.cc/gameswithpython).
the if and else value of chosen_phrase in the Variables pane. You
instructions. The should see different names come up, although
code won’t work names can also repeat.
without them. Add a line of space between the code in Step 1 list. If it is not, the letter is added to the end of
and add the following code: puzzle. The += means ‘add at the end’. Run the
program, then test it’s working by looking at the
chosen_phrase = random.choice(questions) contents of puzzle in the Variables panel. It should
chosen_phrase = chosen_phrase.upper() contain no vowels, spaces, or apostrophes.
Add the following code to the program:
print("Hello"[1:4])
Debugging in Thonny (4) is left out. We’ll create a new list, called
puzzle_with_spaces, by adding chunks of the
You can step through the program slowly to see puzzle string and a space until there’s no puzzle
what it’s doing, which can help you to find errors. string left. The while loop repeats the indented
Click the Debug button in Thonny, then click the
instructions below as long as the length of puzzle
Over button to run through each instruction in turn.
Watch the Variables pane on the right to see how is more than 0. The group_length variable is
the lists and strings change at each stage of the given a random whole number (integer) from
program. Thonny also helps you avoid errors by 1 to 5. Then that many letters are added
highlighting unclosed brackets and double quotes. to puzzle_with_spaces from the front of
puzzle, plus a space. Those characters are
O
ne of the best things about the Raspberry Pi is the yellow wires in the diagram. The first button
that you can easily hook up your own electronics connects to the GPIO 2 pin on one side, and to
projects. Using some electronics components and the ground rail on the other side. We’ll connect
the GPIO Zero library, you can program a puzzle game the latter to a ground pin on the Pi, so anything
where you have to repeat a sequence of lights that plugged in that row of holes connects to ground.
gets longer each turn. You might remember a similar
electronic game from your childhood, but we call ours
Simple Brian. In The MagPi issue 77 (magpi.cc/77)
Connect your first LED
we showed how to use Python code to play the game
on screen. Here, we’ll show you how to make the
02 Always use a resistor when you connect an
electronic game itself, building on your new-found LED to your Pi, to prevent the LED drawing too
Python skills from Missing Vowels. much current and getting damaged. Both the LED
First, we’re going to show you how to build a and the resistor plug straight into your breadboard.
torch by lighting up LEDs. Let’s get going. The current flows from GPIO 18, through the
resistor, through the LED (lighting it up), to the
breadboard’s ground rail. LEDs only work one way
around: the short leg is the negative side, which
Connect your first button
01 The torch circuit diagram (Figure 1)
you connect to ground. The LED won’t light up yet.
Figure 1
The finished game, with all the lights lit up for testing
01
Build an electronic game 03 Using this simple circuit (with an LED and a
06 Now we’re ready to start making the Simple
button), you can make a push-button torch
03
01
Add to the sequence
09 Now we enter the main game loop, under
02 while True (line 27). Everything from here on in is
indented to show it belongs to that loop, repeating
endlessly. The game sequence starts as an empty
list, so the first thing we do is to add an LED. We
pick a random LED using random.choice() and
add it to the end of the sequence list using the
append() list method. A list method is a built-in
Python function that you can apply to a list. Other
01 Just like its famous namesake, our Simple Brian methods are available to insert and remove items,
game features four LED lights that flash up a
and sort the list, among other things.
sequence for you to memorise
DOWNLOAD
brian.py THE FULL CODE:
> Language: Python magpi.cc/github82
works its way through the sequence list, accepts a Check the player’s guess
guess, and checks whether it matches the current
12 We’re still inside the loop going through Top Tip
item in the sequence. There are three loops inside the sequence here, as the indentation of line 51
each other here. The program sets the guess shows. Now we check whether the light the player Underscoring
variable to None, a special value in Python. Then guessed (leds[guess]) matches the current light in repetition
a while loop keeps repeating until the guess the sequence. If so, the light is turned on and then
variable changes. Inside that, a loop goes through off again. If the two lights don’t match, the player The line for _ in
range(3) repeats
the buttons list, checking each one in turn to see made a mistake. We can tell how long a list is using
the indented
whether it’s pressed. If so, the guess variable is len(listname). We use the length of the sequence instructions three
changed, ending the while loop. The program list to tell the player which level they got to. The times. The _
converts the button the player pressed into its correct light is then flashed quickly ten times. The shows we don’t
index number in the list and puts that into the sequence list is emptied to start a new game, and the need to use the
guess variable. That way, we can match the button break instruction breaks out of the for loop that’s loop number.
Often, you’d
to its LED, which will be at the same position in the getting player input. When the player has either
use a variable
leds list. You can find the position of an item in a guessed all the lights, or failed, the game repeats
name instead.
list using listname.index(item). from line 28, adding a new light to the sequence.
BEGINNER’S GUIDE TO
GPIO ZERO
Discover the easy way to control GPIO pins on your Raspberry Pi
T
he 40 metal pins on your Raspberry Pi board
GPIO Zero are known as General Purpose Input/Output
Layout Guide pins, or GPIO pins for short. These pins are your
connection between the virtual world of computer code
GPIO Zero uses the BCM and the real world. With GPIO, you can connect circuit
number system to identify components up to your Raspberry Pi.
pins. These are the numbers It’s easy to attach LED lights, buttons, buzzers, and
referenced on the outside of all kinds of electronic components to your Raspberry
the diagram, such as 18 for Pi. Typically you connect these components to a
GPIO18. The board numbers breadboard, at least when you are starting out. A
(the ones on the inside) are breadboard is a plastic prototyping board used to
just to help you count the link circuit components together without having to
pins. You can use any pin here connect them physically. The legs of the components,
marked GPIO, but the ones along with cables, are pushed into adjoining holes
in blue double up with other on the breadboard (see page 38 for more details).
functions. For this reason, we You then hook the breadboard up to the GPIO pins on
will stick to the ones marked a Raspberry Pi (again, using jumper cables). You’ll need
in green in this tutorial. male-to-male jumper cables to connect breadboard
components together, and male-to-female jumper
cables to connect the breadboard to the GPIO pins on
your Raspberry Pi.
Different GPIO pins have different qualities. Some
provide constant power, either at 5 volts or 3.3 volts.
Others are ground pins, which should be used to
complete a circuit.
Perhaps the most interesting GPIO pins are the ones
that can be programmed. These can be turned on and
off, powering up components (like LED lights) from
code. Alternatively, they can be set to respond to voltage
change inputs, such as a button push. Your code can
then respond to these inputs.
You’ll Need
Typically, you’ll program GPIO pins using Python,
> Rasbperry Pi although Scratch, Java, and a host of other languages can
> Breadboard be used to control GPIO.
Programming GPIO in Python used to be quite a
> LEDs
detailed task. But a Python library called GPIO Zero
> Button
simplifies things massively. With GPIO Zero you can
> Jumper cables quickly connect components and start using them with
just a few simple commands.
Set up a circuit
01
30
25
20
15
10
1
A B C D E
A B C D E
Programming GPIO pins is a relatively
The LED has two legs. The
straightforward process, but remember that there are a few short one is connected to the
steps required to perform the most basic of tasks. resistor (and to the ground pin).
The long leg is connected to
We’re going to start by wiring up a single LED to GPIO25 on the Raspberry Pi
F G H
F G H
GPIO25 as shown in this diagram. If you don’t know how
to use a breadboard, take a look back a couple of pages
I
J
J
in this magazine. This circuit is extremely similar to the
30
25
20
15
10
1
one we used there, except that instead of the long leg of
the LED being connected to a live pin, it is connected to
a programmable GPIO pin. This makes the LED light up
when the GPIO pin is turned on in our program.
Use a female-to-male jumper lead to connect the GND
pin to the ground rail on the breadboard. A resistor is used to
Insert one end of a resistor into a hole on the ground prevent the LED from burning
itself out. The smaller the
rail, and the other end into a hole on the breadboard. resistor, the brighter the light
Connect the short leg of the LED into a hole on the same will be, but don’t burn your LED
out. A 330Ω resistor is a good
line and the longer pin on the line next to it.
start, though you can use other
Finally, take another male-to-female jumper wire. sizes. However, if you pick one
that’s too high, you may not be
Place one end in a hole on the same row as the longer LED
able to see the LED
leg. Connect the other end to GPIO18.
Regular GPIO
02 GPIO Zero
If we were going to light up this LED using regular
code rather than GPIO Zero, this is what we would have to
03 GPIO Zero simplifies things. The same code in GPIO
write (don’t enter this code: it’s just an example): Zero looks like this:
More control
The first line of the program is where we import the
gpiozero library into Python.
05 One neat thing about GPIO Zero commands is that
The second line creates an LED object, with the pin you can enter arguments inside the brackets. Enter led.
number as the argument (inside the brackets). blink( and stop at the open bracket. A yellow box appears
The third line tells the pin to switch on. showing the text ‘on_time=1, off_time=1, n=none,
Now enter led.off(). The light will switch off. background=True)’.
These are the parameters available for the blink
method: the number of seconds for which a light stays on
and then stays off, how many times the light blinks, and
Blink
04 The real joy of GPIO Zero is that it lets you perform
whether you can add more code while the light is blinking.
After each argument is the default value: one second
rather complex tasks with simple instructions. Creating on, one second off, none (which means the light blinks
a blinking LED with more standard code requires you to until you say otherwise), and True (which lets you carry on
import the time module, set an LED to on, pause for a adding code while the light is flashing).
period, then set the LED to off, and repeat in a loop. This To set default values, add a number for each value (from
process makes it difficult to perform other code tasks at left to right):
the same time. In GPIO Zero, however, you simply enter
this line: led.blink(4,2)
led.blink() The light comes on for four seconds, and off for two
seconds. Enter led.off() to stop it. Alternatively, you
The light will start blinking on and off at one-second can add the item and equals sign to pick a value to change
intervals. Enter led.off() to stop it. (and keep the defaults).
led.blink(n=3)
25
20
15
10
1
A B C D E
A B C D E
Traffic lights
06 Let’s take our LEDs and build something a little
F G H
F G H
I
J
25
20
15
10
Connect the new LEDs into the circuit using another two
resistors to connect their shorter legs to the ground rail.
Connect the longer leg of the amber LED to GPIO8 and
the longer leg of the green LED to GPIO 7. These are the two
pins next to GPIO 25, so you have your LEDs all together.
Now we need to create a program to control our traffic
lights. Open Thonny and choose File > New.
Type in the code from traffic_lights.py. Save and run
it (hit the Play icon or press F5). The Python program will
run, and you’ll see your traffic lights in action.
25
20
15
10
1
001. from gpiozero import LED, Button
A B C D E
A B C D E
002. from signal import pause
003.
004. led = LED(17)
005. button = Button(21)
F G H
F G H
006.
007. button.when_pressed = led.on
I
I
008. button.when_released = led.off
J
J
009.
30
25
20
15
10
1
010. pause()
traffic_lights.py
> Language: Python
Button responder
08 Unlike LEDs, you don’t need to use a resistor with Going further
a button. The button’s legs are the same length, and it
typically doesn’t matter which way around you hook it up You can achieve a lot more with GPIO Zero than
to the breadboard. controlling LEDs and buttons.
When the button is pushed, it forms a connection For a more detailed look at how you can detect
between the ground rail and the pin, completing a circuit. motion, control robots, read sensor information (such
The Raspberry Pi is set up, using GPIO Zero, to detect this as movement sensors or thermometers), we have
connection and respond. created a fantastic guide book: The MagPi Essentials:
Open Thonny and create a new file. Enter the code from Simple Electronics with GPIO Zero. Learn more at
button.py, save the file, and run the code. When you push magpi.cc/gpio-zero.
the button, the LED will light up.
HOW TO USE A
BREADBOARD
This humble plastic block full of holes can be used to create just about anything
M
ost of our projects are tested using a small
You’ll Need piece of plastic known as a breadboard.
Officially, it’s known as a ‘solderless
> B
readboard
breadboard’ because it enables you to use circuit parts
> L
ED light
without soldering them together.
> R
esistor Electrical components are connected by pushing
> M
ale-to-female them into the holes in a breadboard. These holes are
jumper leads connected in strips, as shown in the main image. If you
> M
ale-to-male push a wire, or a different component, into one hole in a
jumper leads strip, and another wire into the hole next to it, it’s as if
you’d physically joined (or soldered) the two wires.
In the old days, people would either solder wire
components together on an actual breadboard, or they’d
wrap wires together around nails in a pinboard.
For a lot of Raspberry Pi fans, using a breadboard is
part of life. But for many newcomers this quirky piece of
kit is baffling: a smorgasbord of holes arranged in rows
and columns that seem to make little sense.
So we think it’s a great idea to read this beginner’s
guide to how a breadboard works. In this tutorial, we’ll
explain how these holes are arranged, and how to set up
a circuit on your breadboard.
If you already know all this, feel free to move on.
If not, stick around and learn about one of the most
fun things you can do: building your own circuits and A hole in the blue (sometimes
black) rail is connected to a GND pin.
hooking hardware up to your Raspberry Pi.
It then becomes the ground rail
Fritzing diagram
01 Circuit diagrams can be a little hard to understand
for the novice. So we use visual breadboard diagrams, like
this. This complete diagram uses the power and ground pins
from a Raspberry Pi to light up an LED.
02 05
03
06
The ground rail
03 Take another female-to-male jumper and connect
the female end to a ground (GND) pin on the Raspberry Pi.
The male end goes into a hole on the blue (ground) rail. All
blue holes now act as a ground pin.
04
I
f you have just got a brand new
shiny Raspberry Pi, you may have
plugged it in and got it working.
You may have played a few of the games
or tried out the applications, or maybe To get started with coding is really easy. Coding
you’ve loaded one of the programming is just giving a Raspberry Pi an instruction to do
tools and then looked at it wondering something. The only thing you need to know is
what to do next. If you haven’t done what language to talk to it in. In this case we are
any programming before, we have going to talk in Python 3. We will need to write
wisdom for you here. In the next few our instructions somewhere so, to start, open a
Mark
pages you’ll find answers and probably
some questions, but then some more
answers. Before you know it you will be
Terminal window – click the icon in the top left
of the screen which is a grey box with a blue bar
across the top. This opens a black window with a
Vanstone
a coding, hacking ninja. prompt: pi@raspberrypi:~ $ in green. If you type
python3 and hit ENTER, Python starts and you Educational software
I f you have never done will see the triple chevron prompt: >>>. Now type
print("Hello") and hit ENTER. Bosh! Your first
author from the
nineties, author
any programming before, this program. You have instructed your Raspberry of the ArcVenture
Pi to print the word ‘Hello’ and, all being well, series, disappeared
may appear a bit daunting, it has obeyed. into the corporate
Entering programs like this is not going to be software wasteland.
but it’s quite easy really very useful most of the time, so now let’s look at Rescued by
an app we can write and save a program with. Raspberry Pi!
If you’re new to programming, this Go to the desktop menu (click the Raspberry
may appear a bit daunting, but it’s Pi logo in the top left of the screen) and in the magpi.cc/YiZnxL
quite easy really – you’ve just got to Programming section, select Thonny (which @mindexplorers
get stuck in and start with some simple should then open by default in its Simple mode).
things that will get you results. One Try typing in the following program in the
of the programming languages that is Thonny editor and save it, then run it by clicking
supplied with Raspberry Pi is Python. the Run button. The output will be displayed in
It’s very easy to get started with Python the Shell frame below the program editor.
and it can be used to program many
of the add-ons that are available for mwc1.py
Raspberry Pi – so this is going to be
very useful to learn. We can get you 001. import random Language: Python
up and coding in 30 seconds flat; just 002. magpi.cc/HNJhhd
read on… 003. correct = False
004. r = random.randint(1,10)
005. c = 0
006. while correct == False:
007. n = input("Guess my number between 1 and 10: ")
008. c = c + 1
009. if int(n) == r:
010. correct = True
011. else:
012. if int(n) > r:
013. print("Sorry, my number is lower. Try again.")
014. else:
015. print("Sorry, my number is higher. Try again")
016.
017. print("Well done. The correct answer was " + str(r) + ".
You got it in " + str(c) + " tries.")
Make new
answer string
Define data
startGuessing()
I
answer variable until the player guesses
n the last program, we get input from the all the letters or they run out of tries
keyboard and output text and numbers by
using the print() function. We have also used theWord. When we call a function that is inside
a condition structure in the form of if and else. a module, we use a full stop between the module
Coding Python is very particular about how you indent the name and the function name. Next, we want to get
guides
code with spaces (four per indent level); this shows the player to start guessing what the word is. If we
that the indented code is inside another structure. look at the bottom of the code, we can see that we
In the last program, everything indented after the call a function called startGuessing(). This is our
while statement will be part of that loop. Let’s take own function that we need to define.
Want to learn more a look at a few more coding techniques.
about coding? Check
out our guides to
Defining functions
Python coding and
Using lists 03
object-orientated
programming in
01 We are going to write a Hangman-style
Each time we call a function, the code inside
it runs. Sometimes functions have outputs, like our
The MagPi #53 and game, where we start with a secret word and the function updateAnswer() that returns the variable
#54 respectively. player has to guess it, letter by letter. If correct, we result. One of the rules of Python is that you must
show them where that letter appears in the word. define a function before you call it, so we will need
magpi.cc/53 They are allowed ten wrong attempts before the to define our startGuessing() function near the
magpi.cc/54 game ends. See the mwc2.py code to follow along. top of the code. To do so, we write def and then the
First, we make a list of words to choose from. A name of the function, followed by brackets and a
list is defined in Python using square brackets, colon. If we want to pass variables as inputs into a
like: list = ["a","b","c"]. We’ll call our list function, we can add them inside the brackets.
WORDLIST. In this case we’re writing the list name
in upper case to show that it is a constant, i.e. It is
not going to change throughout the program.
Getting loopy
04 Now for the code in our startGuessing()
function. We set the number of tries and dashes,
Pick a word
02 We can pick a word from our list using the
one for each letter of the secret word, then we go
into a loop. The code says: “While the player still
random module. We import the module at the top has some tries left and the answer we have is not
of our code, then we can use the random.choice() the secret word, run the following code.” In our
function to get a word and store it in a variable: loop, we print the answer we have so far and how
mwc2.py
Language: Python
Module 001. import random
magpi.cc/RqQdhR
A module 002.
is another 003. WORDLIST = ["orange", "table", "january", "balloon",
code file. It "mouse", "speaker", "lorry"]
004. theWord = random.choice(WORDLIST) Variable
can contain
005. A variable is a container for data,
functions,
006. def startGuessing(): in this case a string which can
variables,
007. triesLeft = 10 change as the program runs.
and data.
008. answer = "-" * len(theWord)
009.
Function
List 010. while triesLeft > -1 and not answer == theWord:
A function contains code
A list is a 011. print("\n" + answer)
that can be called from
collection 012. print(str(triesLeft) + " tries left")
elsewhere in the program.
of variables, 013. guess = input("Guess a letter:")
in this case 014. if len(guess) != 1:
string variables. 015. print("Just guess one letter at a time.") Output
016. elif guess in theWord: Output is anything
017. print("Yes that letter is in the word.") that the program
Loop
018. answer = updateAnswer(theWord, answer, guess) produces, in this case
A loop is a part
019. else: words printed to the
of the code
020. print("Sorry, that letter is not in the word.") shell window.
that is repeated
021. triesLeft -= 1
one or more
022.
times, usually
023. if triesLeft < 0:
depending
024. print("Sorry, you have run out of tries. The word was: " + theWord)
on an equation
025. else:
being True.
026. print("Well done, You guessed right. The word was: " + theWord)
027.
Input 028. def updateAnswer(word, ans, guess): Condition
An input is data that 029. result = "" A condition branches a program
a program receives, 030. for i in range(len(word)): to execute one set of code or
in this case from 031. if word[i] == guess: another. Sometimes there are
the keyboard. 032. result = result + guess several branches.
033. else:
034. result = result + ans[i]
035. return result Calling a function
036. When a function is called, the code inside
037. print("I'm thinking of a word....") the function is run and then returns to the
038. startGuessing() next line of code after the function call.
many tries the player has left. Then we use an if, guessed all the right letters in our word or they have
elif, else condition structure to respond to the got it wrong ten times, the program will drop out of
player, depending on what they typed. the loop to reach the final part of the function.
I
n the previous example, we imported a module
into our code and used functions from it. If we
want to control electronics from code, there
is a very useful module available called gpiozero.
GPIO stands for ‘general-purpose input/output’
and the line of double pins on one side of your
Raspberry Pi are called GPIO pins. For details about
the labels of all the pins, see pinout.xyz. If we
connect electrical components to these GPIO pins,
we can use the gpiozero module to make things
happen. When we import a module, there are often
many different functions inside. We can also make
new coding ‘objects’ with them. Objects are like
variables but have their own set of functions and
properties inside them that we can call or change,
and we do that using the same dot notation (full
stop) that we did with the random module. For
Now we’ve got the hang of the coding, let’s put more details on using coding objects (called object-
oriented programming or OOP), see issue 54 of
it to work with some electronic components The MagPi: magpi.cc/54.
The breadboard
You’ll Need 01 Breadboards come in various sizes, but
they all work in the same way. If there are tracks
marked red and black/blue (and/or + and –) on the
A breadboard long edges of the board, these are for power and are
magpi.cc/NtjSiy connected along the length – although sometimes
divided into sections. The matrix of holes which
An LED make up the main part of the board are connected
magpi.cc/WBVPxG in lines the other way (vertically in the diagram).
There is usually a break in the centre of the board
A resistor so that the two sides are not connected.
magpi.cc/iDTFag
2 × male-to-female
jumper wires
magpi.cc/OkMyVX
A resistor
03 Resistors do what their name
Potentiometer
suggests: they resist the flow of
electricity (current). Some components
05 A potentiometer is a variable resistor. It
need to have a certain amount of current usually has a turning spindle that changes the
in order to operate correctly. Resistors resistance from one value to another, quite often
enable us to set the current or voltage to from no resistance to full resistance (no electricity
a suitable level for the other components flowing). A potentiometer can provide us with
we are using. There are many different a variable output voltage which we can measure
types of resistors, with different with the GPIO, but there is a slight problem. The
resistance values. The resistance value potentiometer provides an ‘analogue’
can be read from the pattern of coloured output (varies continuously
Electronics
guide
stripes on the resistor. You can also between values) and the GPIO
get variable resistors, which are known inputs are only digital, i.e.
as potentiometers. on or off. So we need another
component: an analogue-to-
digital converter (ADC). For more details
about using electronic
Jumper wires
04 We need to connect
components with
Raspberry Pi, check out
Analogue-to-
our components to
Raspberry Pi’s GPIO pins.
06 digital converter
our Electronics Starter
Guide in issue 64 of
For this we use jumper ADC components come in various forms, but the The MagPi.
wires. The ones we will one we have in this example is called an MCP3008.
be using have a female It’s an integrated circuit (IC), meaning that it’s a magpi.cc/64
connector at one end, box with some circuitry inside it. We don’t need
to go on the GPIO pins, to know what is inside it – we just need to know
and a male connector what to connect to each of the legs of the IC. We
to go in the holes of the will need to wire up several of the legs to GPIO pins
breadboard. You can also and provide the IC with power; when we’ve done
get jumper wires with that, we can connect the potentiometer to the IC
both male connectors or and then read values in
both female connectors, showing the position
for different situations. of the potentiometer
They can be bought in spindle using the
strips all joined together, gpiozero module.
sometimes known as We’ll cover the code
‘jumper jerky’. in the next section.
O
magpi.cc/vhZkGh n the previous page we talked about function to write the graphics to the window, and
potentiometers and analogue-to- an update() function to update the game items
6 × male-to-female digital converters, and this is where between draw cycles.
jumper wires & we get to use them. It’s a bit more complicated
10 × male-to-male than lighting up an LED, but only a little. First,
jumper wires we are going to write a program which has two
magpi.cc/ffZNwL Running the code
rectangular bats at each side of the screen that
can be moved up and down by two players. A ball
02 The listing mwc3.py provides all the code
2 × potentiometers bounces backwards and forwards between the you need for the game to work. There is some code
magpi.cc/oZRFEe bats until one player misses the ball and the other in the updatePaddles() function for the keyboard
player scores a point. That’s right, you guessed to control the paddles or bats, just in case you want
MCP3008 it, the game is Pong and we are going to create a to test it before making the proper controllers. We
integrated circuit controller for each player from a potentiometer import several modules with this code. We have
magpi.cc/aCvXuo and wire it into our Raspberry Pi. covered pgzrun, but we also need random so that
the ball will move in a random direction each time
it starts. In addition, we need gpiozero to deal
with the input from the controllers, and we need
Super-fast game coding the math module for calculating the direction of
01 If you have been following other coding the ball.
articles in recent issues of The MagPi, you will
know that when writing a quick game on Raspberry
Pi, Pygame Zero is your friend. We can make the
Wiring it all up
basics of the game code very quickly by importing
the pgzrun module, which holds all the Pygame
03 One thing to bear in mind when connecting
Zero code. We need to call pgzrun.go() at the end any electronics to a computer is that if the
of our code, and that’s our game window sorted. As wires are connected in the wrong way, you may
with all Pygame Zero programs, we have a draw() cause damage to the computer or the electronic
components, so it’s always a good idea to power off case. You will see from the diagram that all the legs
your Raspberry Pi before connecting anything to on the top side of the IC are connected to either
the GPIO pins. Follow the wiring diagram (overleaf) GPIO pins or to power lines. There are two red
carefully, making sure that the jumper wires are connections going to the positive power track, then
connected to the right GPIO pins and to the correct a black lead to the negative or ground track. Then
places on the breadboard. Once you have put there are four coloured wires that go to: purple –
everything in place, it’s a good idea to have another GPIO 11; green – GPIO 09; orange – GPIO 10; and
check just to make sure. blue – GPIO 08. Then there is one last connector to
the ground track.
The MCP3008 IC
04 The inputs
The MCP3008 converts the voltage from our
potentiometers into a number with the help of the
05 All the MCP3008 pins on the bottom side
gpiozero module. It has eight channels for input, of the IC are input channels. We will use the first
but we are going to just use two of them in this two pins, which are channel 0 and channel 1. We
When everything is
plugged in and working,
you can play Pong!
mwc3.py
Language: Python
001. import pgzrun 050. p2Y = (
magpi.cc/umUcfq
002. import random pot2.value * 540) +30
003. from gpiozero import MCP3008 051.
004. import math 052. if keyboard.up:
005. 053. if p2Y > 30:
006. pot1 = MCP3008(0) 054. p2Y -= 2
007. pot2 = MCP3008(1) 055. if keyboard.down:
008. 056. if p2Y < 570:
009. # Set up the colours 057. p2Y += 2
010. BLACK = (0 ,0 ,0 ) 058. if keyboard.w:
011. WHITE = (255,255,255) 059. if p1Y > 30:
012. p1Score = p2Score = 0 060. p1Y -= 2
013. BALLSPEED = 5 061. if keyboard.s:
014. p1Y = 300 062. if p1Y < 570:
015. p2Y = 300 063. p1Y += 2
016. 064.
017. def draw(): 065. def updateBall():
018. screen.fill(BLACK) 066. global ballX, ballY, ballDirX, ballDirY,
019. screen.draw.line((400,0),(400,600),"green") p1Score, p2Score
020. drawPaddles() 067. ballX += ballDirX*BALLSPEED
021. drawBall() 068. ballY += ballDirY*BALLSPEED
022. screen.draw.text(str(p1Score) , center=(105, 069. ballRect = Rect((ballX-4,ballY-4),(8,8))
40), color=WHITE, fontsize=60) 070. p1rect = Rect((100, p1Y-30), (10, 60))
023. screen.draw.text(str(p2Score) , center=(705, 071. p2rect = Rect((700, p2Y-30), (10, 60))
40), color=WHITE, fontsize=60) 072. if checkCollide(ballRect, p1rect) or
024. checkCollide(ballRect, p2rect):
025. def update(): 073. ballDirX *= -1
026. updatePaddles() 074. if ballY < 4 or ballY > 596:
027. updateBall() 075. ballDirY *= -1
028. 076. if ballX < 0:
029. def init(): 077. p2Score += 1
030. global ballX, ballY, ballDirX, ballDirY 078. init()
031. ballX = 400 079. if ballX > 800:
032. ballY = 300 080. p1Score += 1
033. a = random.randint(10, 350) 081. init()
034. while (a > 80 and a < 100) or (a > 260 and a < 082.
280): 083.
035. a = random.randint(10, 350) 084. def checkCollide(r1,r2):
036. ballDirX = math.cos(math.radians(a)) 085. return (
037. ballDirY = math.sin(math.radians(a)) 086. r1.x < r2.x + r2.w and
038. 087. r1.y < r2.y + r2.h and
039. def drawPaddles(): 088. r1.x + r1.w > r2.x and
040. global p1Y, p2Y 089. r1.y + r1.h > r2.y
041. p1rect = Rect((100, p1Y-30), (10, 60)) 090. )
042. p2rect = Rect((700, p2Y-30), (10, 60)) 091.
043. screen.draw.filled_rect(p1rect, "red") 092. def drawBall():
044. screen.draw.filled_rect(p2rect, "red") 093. screen.draw.filled_circle((ballX, ballY), 8,
045. "white")
046. def updatePaddles(): 094. pass
047. global p1Y, p2Y 095.
048. 096. init()
049. p1Y = (pot1.value * 540) +30 097. pgzrun.go()
THE
RASPBERRY PI
ACCESSORIES
Our guide to the greatest add-ons, HATs,
and expansions for your Raspberry Pi
R
aspberry Pi is fantastic on its own. is where add-ons and accessories come in
With wireless LAN, Bluetooth, – there are hundreds of extras you can get
USB ports, the multitalented GPIO for your Raspberry Pi that will improve its
pins, and a full operating system, it really already impressive specs.
is a fully functional computer. What add-ons should you get, though?
What if you could make it better? Do We’re here to show you the best the
more? Make certain functions easier? This Raspberry Pi world has to offer.
Types of
s
accessoriofe
The glossary
s
add-on term
HAT
We’ll start with an important
one. HAT stands for ‘Hardware Attached
on Top’ (it’s a backronym), and is a standard for
add-ons. That means there are specific definitions of how
a HAT can connect and work. All you need to be concerned
with is that a HAT fits perfectly on top of a Raspberry Pi,
connecting to the GPIO pins. You will usually need to install
extra software to get them working.
pHAT/Bonnet/Cap/etc.
While the HAT standard has recently
been extended to different sizes, many
companies have created their own term
for add-ons that act like a HAT but
don’t quite meet the technical criteria.
Pimoroni coined pHAT, and Adafruit
uses Bonnet, and other firms
tend to use similar
variations on the
headwear theme
or HAT.
Add-on
A HAT is an add-on, but an add-on isn’t necessarily a HAT.
Add-ons can be connected via USB, only specific GPIO pins,
the camera port, etc. It’s a catch-all term for something
that you can add onto your Raspberry Pi in some way.
PROGRAMMING AND
MAKER ACCESSORIES
Improve your projects with these add-ons
ThunderBorg
magpi.cc/xcsSpm
price: £37 / $50
Developed for the Astro Pi mission, the Sense HAT is primarily a set of
environmental sensors. It can detect pressure, humidity, temperature, and
orientation/movement. It also has an 8×8 LED matrix and a little joystick for
very basic display and control. There are a couple of Sense HATs running on
Raspberry Pi boards up on the ISS at the moment.
Use it with: Weather stations, space stations
Hologram Nova
hologram.io/nova
price: From £53 / $64
Energenie Pi-mote
magpi.cc/FnezCP
price: £22 / $27
Witty Pi 2
magpi.cc/merPpf
price: £20 / $25
MEDIA ADD-ONS
Improve your listening, watching, and more
HiFiBerry DAC+
magpi.cc/aimAyy
price: From £20 / $24
HyperPixel 4.0
magpi.cc/WgSmAA
price: From £37 / $37
TV HAT
FLIRC USB
magpi.cc/ryviXi price: £20 / $25 flirc.tv
price: From £20 / $25
The official Raspberry Pi TV HAT is pretty amazing – its most basic
function is allowing you to tune into TV signals using your Raspberry Pi. For applications such as Kodi,
That’s pretty standard, but the amazing part is its ability to stream said TV there are plenty of ways to
not only around your network, but also over the internet if you’re abroad and control your Raspberry Pi-
missing the latest episode of GBBO. based home theatre PC via your
smartphone or tablet. FLIRC
Use it with: DIY DVR, TV anywhere
makes the whole thing a bit
simpler, though: take your
favourite remote, let FLIRC
know which button is which,
and then just plug it into your
HTPC. Simple.
Ever wanted your films to expand out of your TV? With Lightberry, you can
install DIY Ambilight-like effects to your TV so that special effects become
just that little bit more special. There are various kits to choose from as well.
Use it with: HTPCs, magic mirrors
Picade X HAT
magpi.cc/BupAFF
price: £16 / $16
Watch live TV
from Raspberry Pi
Phil
with the TV HAT
MAKER
King
Set up your new add-on to stream live TV from and to a Raspberry Pi
When not subbing
The MagPi and
T
editing Raspberry
Pi books, Phil he latest official Raspberry Pi add-on is
enjoys watching a a must for telly addicts. The Raspberry Pi
mixture of quality
Assemble and mount
(Endeavour, The
Crown) and other
TV HAT enables any Raspberry Pi (with
40‑pin GPIO) to decode live digital TV signals and
01 Insert the thin end of the supplied silver RF
(old Dynasty stream them to remote devices – such as another cable adapter into the gold connector on the side of
re‑runs) TV.
Raspberry Pi, computer, or even a smartphone. the HAT. Take the 40-pin header and insert its pins
magpi.cc The HAT’s built‑in Sony CXD2880 tuner supports into the holes in the underside of the HAT – not
DVB-T2 and DVB-T standards (Freeview in the UK), into the black female header on the top! Mount the
so you can watch all your favourite channels. Here HAT on your Raspberry Pi, with the RF adapter at
You’ll Need we show you how to set it up, and even use it to the microSD card slot end. To make it secure, you
turn a Raspberry Pi into an all‑in-one TV/PVR. can screw it in using the supplied stand-offs.
> Raspberry Pi TV HAT
> Computer
Top Tip
Recording
Add a hard drive
or USB stick to
Raspberry Pi to turn
it into a capacious Connect your TV aerial With the supplied header
homemade PVR cable to the HAT via inserted on its underside, the
with LibreELEC. the supplied adapter HAT is mounted on Raspberry Pi
Install Tvheadend
02 Connect a coaxial RF cable from a TV aerial
socket to the RF adapter on the HAT. You’ll need
decent digital terrestrial TV (Freeview in the UK)
reception for the tuner to work. With Raspbian
Stretch installed on its microSD card, turn on your
Raspberry Pi – a green LED will light on the HAT.
We need to install a back-end TV service to
stream video: we’ll use Tvheadend. To install it,
open a Terminal window and enter:
of tea. Once installed, a package configuration the TV HAT in your browser. In the EPG, click the
screen will appear and you’ll be prompted to TV icon to the left of any programme to show it in
enter a Tvheadend administrator user name. a window, which you can expand to full-screen.
For simplicity’s sake, enter kodi for this, then There are also options to schedule and record
also enter kodi for the password – you can always shows – use the Help option for more details.
change it later if you prefer. You’re now ready As well as using a web browser, you can view
to log in from another device. the TV stream from a variety of clients, including
Kodi, omxplayer, VLC, and smartphone apps –
see magpi.cc/ZpJtwd.
Log in remotely
04
Using LibreELEC
Now that Tvheadend is running, you can
access it from another computer (possibly a second
Raspberry Pi). In a web browser, enter this address:
http://raspberrypi.local:9981/extjs.html. If that The live TV stream from the TV HAT can be accessed
doesn’t resolve, use your Raspberry Pi’s IP address in the Kodi media player, most easily by using
instead, followed by :9981/extjs.html. Log in the LibreELEC OS on a Raspberry Pi. Install the
Tvheadend client by selecting Add-ons > Install from
using kodi for both the username and password. A
repository > PVR clients > Tvheadend HTSP Client.
configuration wizard will appear, enabling you to In addition, using LibreELEC, it’s possible to set up
choose the TV network type and transmitter. both the Tvheadend client and server on the same
Raspberry Pi – a Pi 2, 3, 3A+, 3B+, or 4 is recommended
– for an all-in-one TV/PVR device. To do so, select
Add‑ons > Install from repository > Services >
Configure TV network Tvheadend Server 4.2, and install it. Access it from
05 In the configuration wizard’s ‘Network
another computer using the IP address followed by
I
Marc Scott n this project, you will be making your very own
MAKER
You’ll Need
Add GPIO support
> Raspberry Pi (not a 02 A special GPIO extension in Scratch 2 on
Zero / Zero W)
Raspberry Pi is needed to control and read input
> Sense HAT and output components connected to the GPIO
> Speakers or pins. With Scratch 2 open, click on More Blocks
headphones in the Scripts menu. Next, click on the ‘Add an
Extension’ button. You can then double-click on
Step 2 Pi SenseHAT blocks appear under More Blocks
DOWNLOAD
THE FULL CODE:
magpi.cc/Nqwqmz
Top Tip
Analogue audio
If you’re using
headphones or
speakers, don’t
forget to change
the audio out on
your Raspberry
Pi from HDMI to
Analog. Right-
click on the
Plug headphones or speakers into the volume icon on
audio socket to hear the music play the desktop.
Analogue out
07 At this point you will need to change the
enter ‘track’ in the left field, and drag a track
variable into the right field (as shown in the Top Tip
sound output to analogue by right-clicking on the image). You can choose whichever colours you like.
speaker icon in the header bar of the desktop and Shuffle
then clicking the Analog option.
Next, you’re going to display the number of the A nice feature
Volume control to have on an
track that’s currently playing. Click on Data and
Make a Variable; call it ‘track’ (leave it set for all
09 You can now add some extra controls to your
MP3 player is the
option to shuffle
sprites and click OK). MP3 player. First of all, set up your script so that the tracks so
the Sense HAT joystick can control the volume. that they play in
Set track
08 Drag a set block above your play sound
Raspberry Pi treats the Sense HAT joystick in
the same way as the arrow keys on your keyboard.
a random order.
Pushing the Sense
block and choose track and 1. Click More Blocks This means that, for example, pushing the HAT joystick
inwards means
and drag a scroll message block under set track. joystick up is the same as pushing the up arrow
the same thing
The scroll message block can use the track on your keyboard. to Scratch as
variable with a join block. Drag a join block and Test your scripts again: click the green flag, and pressing ENTER
then use the Sense HAT joystick to change the on the keyboard.
volume of your music. Update the MP3
Step 8 Scroll the track number on the LED matrix player code so
that when the
joystick is pushed,
the code chooses
Change tracks
10 Now that you know how to use the joystick,
and plays a
random track.
it’s time to try to use it to change which track is
playing. When the program starts, you will need to
stop all sounds.
Use the when left arrow is pressed and the
Step 9 Controlling volume with the joystick
when right arrow is pressed blocks to stop all
sounds and to increase or decrease the value of your
track variable.
You can also use a scroll message block to show The Sense HAT is
again which track is being played. You can use the a versatile piece of
hardware made by
when arrow is pressed blocks to change the value Raspberry Pi. It’s
stored in your track variable. called a Sense HAT
due to all the sensors
That’s it – your MP3 player is complete! Click on on board (hardware
and motion), but
the green flag and then have a go at changing your
we’re using its other
tracks using the Sense HAT joystick. features here
Step 10 The complete code
CAMERA
MODULE
A Raspberry Pi Camera Module should be an essential
piece of any digital maker’s kit, as it can be used in a wide
variety of projects. Wesley Archer puts us in the picture
G
ive your Raspberry Pi the gift of sight We’ve seen many exciting builds take advantage
with an official Camera Module of these, but being able to see what is happening
(magpi.cc/xSXqyL). This handy add-on around your Raspberry Pi is very simple with
connects directly to the Raspberry Pi and is used the Camera Module. These are some of the best
in a wide range of vision-based projects. projects for beginners. They’re easy to set up and
Using a Raspberry Pi to monitor its produce visible results.
surroundings is a fascinating subject, especially Using the Camera Module is a great way to
with the huge array of sensors, accessories, HATs, add an extra dimension to most projects. Let’s
and pHATs available. get started…
night vision?
The Camera Module has two
variants – the standard version
and the NoIR version, which
has the infrared filter removed
to allow the camera to detect
infrared light. It makes a great
night-vision camera when used
with an IR light source!
SET UP YOUR
CAMERA MODULE
Before you can start snapping away with the Camera Module,
you’ll need to connect it to a Raspberry Pi and test it out
S
etting up a Camera Module couldn’t be includes the cable. As with a full-size Raspberry
You’ll Need
easier. You attach the Camera Module Pi, gently pull the plastic clasp and then slot the
> Raspberry Pi directly to the Camera Serial Interface (CSI) camera cable in – you should see the white part
Camera Module port on the Raspberry Pi board. facing upwards. You’ll know if the cable is in
magpi.cc/ Connecting it to your Raspberry Pi is the same correctly if the camera works, but it is best to check
kAtsHn whether you own a Raspberry Pi 3A+/3B+, 4, Zero, before booting your Raspberry Pi.
> Pi Zero Camera or even an earlier Model B with 26 GPIO pins.
Adapter (optional) However, if you are going to connect a Camera
3
magpi.cc/
Module to a Raspberry Pi Zero (1.3, W, or WH),
uAUbdp
you’ll need to use a Pi Zero Camera Adapter. This is Connect the
> microSD card often sold separately (£4, magpi.cc/uAUbdp), and Camera Module
> Raspbian sometimes included with the Official Raspberry Pi Similar to the way the camera cable connects to
Zero case (magpi.cc/LECcmF). Raspberry Pi, gently pull the small plastic clasp on
If you received a Raspberry Pi Zero W free the Camera Module and then slot the other end of
with a 12-month subscription to The MagPi the camera cable into the port – this time the blue
(magpi.cc/subscribe), you will have got a Zero part should be facing you, with the camera lens
Camera Adapter cable free with your Starter Kit. pointing the opposite direction. Gently close the
Once you’ve got your Camera Module and clasp, locking the cable in place – the clasps can be
Disable LED Raspberry Pi, you use the cable to attach the two fragile, so handle with care.
together. We’ll show you how…
The V1 Camera
Module lights a
red LED when
1
activated (the V2
Camera doesn’t Connect the cable to
have one). To a Raspberry Pi 2/3/3+/4
disable this, add On a full-size Raspberry Pi, you will need to
disable_camera_
connect the camera cable to the Camera port
led=1 to the
nearest the Ethernet port. Gently lift the small
/boot/config.txt
file (and reboot). plastic clasp on the Camera port and connect the
camera cable with the blue part facing towards
the Ethernet port, then gently push the clasp back
down so it holds the cable in place.
2
While small, the
Camera Module takes
high-resolution photos
Connect the cable
(up to 3280×2464 pixels) to a Raspberry Pi Zero W
and captures HD video The Raspberry Pi Zero W has a smaller Camera
(up to 1080p) without
breaking a sweat port, but the official Raspberry Pi Zero case usually
Raspberry Pi Zero
owners will need a Pi
Zero Camera Adapter
to connect the Camera
The cable is flexible, enabling you to position Module to the smaller
Camera socket on
and attach the Camera Module wherever you the board
want for your project. You can also buy different-
length cables to suit your project
have your Raspberry Pi connected to a mouse, command-line Raspberry Pi configuration tool Using a full-sized
Raspberry Pi? Why
keyboard, and monitor, you can use the Raspberry instead. Enter the following in a Terminal window:
not buy a Raspberry
Pi Desktop to enable the Camera function. Click
Pi case designed to
on the raspberry icon (top left) and choose sudo raspi-config accommodate the
Preferences > Raspberry Pi Configuration. Click the Camera Module,
Interfaces tab and set Camera to Enabled. Click OK; Now select ‘5 – Interfacing Options > P1 – Camera’ such as the PiShell?
when prompted to reboot, click Yes. and choose <Yes> to enable the camera. Press
ENTER on <Ok> and choose <Finish>. When
asked to reboot, choose <Yes>. We’re now set to
snap away.
raspistill -o /home/pi/hello.jpg
CAMERA MODULE
SETTINGS
Get the most out of your Camera Module by tweaking
the various settings and creating different effects
T
he Camera Module doesn’t just snap photos raspistill -w 640 -h 480 -br 40 -o /home/
– it also records video – but did you know pi/hello.jpg
that there are lots of different settings that
can be applied to customise how the photo or video This demonstrates how you can take a smaller
appears? In this guide, we’re going to explore some photo (640×480 pixels) with a brightness of 40, but
of the settings and commands that can be used feel free to experiment to see what works best.
to tailor how you use the Camera Module in your
project, and we’ll explore some of the more quirky
features too!
2 Adding text
If you’re old enough to remember actual
printed photographs, then you may have noticed
that some cameras added the date and time
to record when the photo was taken. If you’re
too young to remember, don’t worry as you’ve
1
just learned something new! With raspistill
Adjusting resolution you can add your own text to your photos too,
and brightness using the -a or --annotate parameter. Take the
The v2.1 Camera Module has a maximum resolution following example:
for a photo of 3280×2464 pixels, but images
this large can take up a lot of storage space over raspistill -a 4 -a "Pi Camera %d-%m-%Y
time and take longer to process by Raspberry Pi. %X" -o /home/pi/text.jpg
Fortunately, raspistill, the program that captures
photos on our Raspberry Pi, allows us to specify The first -a 4 part sets the bitmask notation in
the photo resolution very easily. For example, the metadata to record the time (more info on that
you can set the width (640 pixels) and height (480 here: magpi.cc/2egcYup).
pixels) using the -w and -h parameters accordingly. The second -a part includes our custom text
You can also specify the brightness with the -br (Pi Camera) and formats the date into dd-mm‑yy
parameter and a value between 0 and 100. The (%d-%m-%Y) before adding the time (%X) and then
image above was taken with the NoIR Camera saving the photo in our Raspberry Pi’s home
Module (hence the odd colours) using: directory (/home/pi) as text.jpg.
Camera
Essentials
We’ve only just
scratched the
surface of what
the Camera
Module can do
in our guide, so
why not take
a look at The
MagPi Essentials
Camera Module
Guide for a more
comprehensive
overview of all the
commands, hints,
and tips to ensure
you get the most
out of it?
magpi.cc/
camera-
essentials
CAMERA MODULE
PROJECTS
We’ve selected six Camera Module-related projects to try out.
If you need some inspiration, then take a look at the pick of the bunch
Stop-motion animation
Stop-motion animation – think Wallace &
Gromit – is where a series of photographs are
taken, but with minor changes made to the
‘scene’ being filmed. The scene is changed
slightly between shots – known as frames –
and when they are all stitched back together
afterwards, the illusion of animation is
complete! In this fantastic tutorial, learn how to
add a button to your Camera Module setup and
create your very own stop-motion animation!
More info: magpi.cc/KiYbdb
W
hat is Slow Scan TV (SSTV), then? You Firstly, switch the audio output to the 3.5 mm
convert a picture into sound (similar to headphone jack. This is needed for the way
Dave fax machine or dial-up modem noise) PulseAudio loops back the system audio as an
MAKER
Honess transmit the sound via radio, and convert the input device. On the Raspbian desktop, simply
received sound back into a picture at the other right-click the speaker icon in the menu bar and
Dave lives in end. The International Space Station (ISS) has choose Analog.
the Netherlands
a long history of transmitting SSTV pictures for Then, open a Terminal and install the required
and works at
the European global events, each lasting several days, where software for the project:
Space Research people the world over tune their radios to the ISS
and Technology
and try to receive the pictures every time it flies sudo apt-get update
Centre, where he
helps coordinate over their home. It’s a hobby of mine! sudo apt-get install rtl-sdr sox
the educational One such event began on 12 April 2019 to pulseaudio qsstv ntpdate -y
operations for celebrate the anniversary – to the day – of the
European crew on
the ISS.
launches of Yuri Gagarin in 1961 and the first Next, set your time zone and pull the correct time
Space Shuttle, 20 years later, in 1981. from the internet. In the Raspbian main menu,
@dave_spice
go to Preferences > Raspberry Pi Configuration >
Localisation tab > Set Timezone, change Area and
Location accordingly, then click OK.
Install prerequisites
01 and set the time
Finally, go back to the Terminal window to pull
the time:
We presume you are running a clean install of
Raspbian and are online. sudo ntpdate pool.ntp.org
> Raspberry Pi 2B or
later
This inexpensive
USB dongle acts as
the radio receiver
03 Listen to a commercial correct. In the main menu, select Internet > QSSTV, Top Tip
FM radio station then select Options > Configuration and choose the
Let’s tune into a commercial FM radio station to following options in the Sound tab: Play with SSTV
check that both the dongle and the antenna are on mobile
working correctly. The command below pipes Audio Interface – PulseAudio
raw data from rtl_fm into ‘play’, which will then Input and Output Audio Device – default -- Playback/ For a quick test,
produce the audio output. Modify the value after recording through the PulseAudio sound server you can try these
free mobile
the -f to specify your own FM station/frequency Sound Input – From sound card
apps: Robot36 on
and don’t forget to put the capital M after the Sound Output – To sound card Android; CQ SSTV
number so it knows you mean megahertz and not on iOS. Play this
hertz (98.8MHz is BBC Radio 1 in the UK). In a Click OK. Next, run the Calibrate function and go MP3 (magpi.cc/
Terminal, enter: make a cup of tea/coffee: Options > Calibrate. Click ruANWC) and put
OK when both progress bars reach 99%. the phone near
the speaker.
rtl_fm -M wbfm -f 98.8M | play -r 32k -t
raw -e s -b 16 -c 1 -V1 -
Use VIS – on
Set up QSSTV
04 QSSTV is the program that will listen to
Auto Slant – on
Autosave – on
the audio output on the Raspberry Pi and decode Signals – Normal
the pictures from the fax/modem noise when the Mode – Auto
Click the play ► button. Nothing will happen, but At the time of writing, for instance, an SSTV
Top Tip just click it to start the receiver. event was scheduled to start on 4 August 2019
Open sstv_test.mp3 in the Chromium browser. to honour NASA astronaut Owen Garriott, the
RTL-SDR You can either drag and drop the file from File first person to operate amateur radio from space.
starter kit Manager, or enter file:///home/pi/sstv_test.mp3 These events usually last for a few days at a time,
into the address bar. meaning you will get multiple ISS passes during
Your author Let it play and watch the picture appear in QSSTV. which you can receive the SSTV signal.
personally Notice the waveform and waterfall display activity on
recommends
the right of the screen. Other SSTV test recordings
this starter kit
that comes with can be found online, such as: magpi.cc/dXpjRr.
When is the ISS flying over me?
the USB dongle
and a good
07 There are many websites you can use
v-dipole antenna: for this, but your author’s personal favourite
magpi.cc/uBMKQg Prepare for the next SSTV event
06 To get pictures from the ISS you need to
is heavens-above.com.
Click ‘Unspecified’ in the top right to set your
know three things: location. Type your postal code and country into
‘Enter place to search for’ and click Search. Scroll
• When the ISS will be transmitting the SSTV down and click Update. You’ll now be back on the
signal. It’s not always-on. homepage; under Satellites, click ISS. For ‘Passes
• What frequency the SSTV signal will be to include’, select ‘all’.
transmitted on (usually 145.8MHz). The table now showing lists the times of the
• When the ISS will fly over your location. upcoming ISS passes for your location. The Alt
Imagine holding this
picture above your value under ‘Highest point’ is the maximum
head and aligning The ISS flies over most places a few times every elevation of the pass above the horizon; 90 would
it with the compass
directions. The line day (unless you live in the Arctic/Antarctic). You mean it goes directly overhead. Passes with higher
shows the flight path
can find out when the ISS is transmitting on this maximum elevation will give better results than
of the ISS across the
sky above you website: ariss-sstv.blogspot.com. lower ones. Clicking on any row in the table shows
the sky chart for that pass. Imagine holding that
picture above your head and aligning it with the
compass directions. The line shows the flight path
of the ISS and this is useful for roughly positioning
your antenna. It can also be useful to look at the
‘Ground track’ (see link in top right). Plan ahead
and set up your ground station with time to spare
before the ISS flies over.
doppler.py
> Language: Python
001. #!/usr/bin/python3
002. import urllib.request
003. import math
004. import socket
005. import ephem
006. import time
007. import sys
You can potentially get a certificate like this, even if you only
decode a few lines of one picture 008. import ssl
009.
010.
Compensate for 011. C = 300000000.0
14 Doppler shift (optional) 012. F0 = 145800000.0
It doesn’t make much difference, but if you 013.
want to have some fun with this, your author 014. LATITUDE = "52.219308"
has created a Python script to compensate for 015. LONGITUDE = "4.419926"
Doppler shift. It tracks the ISS using ephem, 016. ALTITUDE = 20
computes the corrected frequency for when the 017.
ISS is passing over, and retunes rtl_fm using a 018.
UDP socket: magpi.cc/zNtRDB. 019. class tle_reader(object):
To use it you’ll first need to run sudo pip3 020. """
install ephem and then just start the script 021. For keeping ephem two line element sets up to date
in another Terminal window. But first you will 022. """
need to modify the code to set your location. 023. def __init__(self,
See the LATITUDE, LONGITUDE, and ALTITUDE 024. tle_name="ISS (ZARYA)",
variables at the top. Get the values from the top 025. tle_file=
right of heavens‑above.com and just estimate "https://celestrak.com/NORAD/elements/stations.txt",
your altitude. 026. tle_max_age=3600):
027. self._tle_name = tle_name
028. self._tle_file = tle_file
029. self._tle_max_age = tle_max_age
Wait for the ISS to arrive 030. self._tle = None
15 You may want to leave your ground station 031. self.reload()
overnight or over the weekend to capture several 032.
passes. When you return, select the Gallery tab 033. def build_index(self, tle_lines):
in QSSTV to see what images were received. 034. index = {}
Alternatively, it’s always exciting to watch the 035. for i in range(0, len(tle_lines), 3):
pictures coming in live as the ISS is above you! 036. index[tle_lines[i].strip()] = (tle_lines[i +
1], tle_lines[i + 2])
037. return index
038.
Get an SSTV award! 039. def reload(self):
16 On your Raspberry Pi, the decoded pictures 040. print("Loading: %s" % self._tle_file)
can be found in /home/pi/qsstv/rx_sstv. You can 041.
upload them on this website for verification and 042. try:
recognition: magpi.cc/Kdjnmy. 043. ctx = ssl.create_default_context()
Check the information for the event on 044. ctx.check_hostname = False
ariss-sstv.blogspot.com to find out how to apply 045. ctx.verify_mode = ssl.CERT_NONE
for the award certificates. This will be a PNG file 046. with urllib.request.urlopen(self._tle_file,
that is emailed to you and will show a unique context=ctx) as response:
number. Good luck!
DOWNLOAD
THE FULL CODE:
magpi.cc/zNtRDB
THE 50
E R R Y P I
RASPB
R R A S P B IAN
MASTE 01
Boot from USB
AND RA S
models (3B, 3B+, 3A+, 2B v1.2)
from a USB port instead of a microSD
KS,
card. It’s faster and more reliable for
WITH TH
extra storage space. See the official
documentation at magpi.cc/eXHfjq.
T S & T R I C KS 02
Power over Ethernet
HIN The official Raspberry Pi PoE
HAT enables you to power
a Raspberry Pi 3B+ or 4 via an
Ethernet cable. Great for those
projects that require a constant
wired connection.
01
08
09 02
10 06 03
04
07
Touchscreen
07 A Raspberry Pi Touch Display
05
(magpi.cc/CAPxtI) gives users
the ability to create all-in-one,
integrated projects such as tablets,
infotainment systems, and embedded
projects. Its ribbon cable connects to
the DSI port present on all Raspberry
Power it up
05
Pi boards (except Raspberry Pi Zero
Audio output
03
The power requirements of your and Zero W).
All Raspberry Pi models have a Raspberry Pi increase as you
GPIO pins guide
composite out port to connect
analogue devices. Model B+ and later
make use of the various interfaces.
The GPIO pins can draw 50 mA safely, 08 Open a Terminal and enter:
combine the audio out and composite distributed across all the pins; an
out on to the same 3.5 mm jack plug. individual GPIO pin can only safely pinout
This requires a particular type of lead, draw 16 mA. The HDMI port uses
with audio left on the tip, audio right 50 mA, the Camera Module requires …for a quick visual guide to the GPIO
on ring 1, ground on ring 2, and video 250 mA, and keyboards and mice can pins. Or enter:
on the sleeve. See magpi.cc/tDfjLV. take as little as 100 mA or quite a bit
more. Buy the Official Power Supply pinout -x
Switch sound options
04
and check the power rating of your
The HDMI port outputs audio devices: magpi.cc/xfszUR. …to open the web browser and point it
as well as video. If your display to the interactive model at pinout.xyz.
Use a camera
06
lacks a built-in speaker, you’ll want
Hardware diagrams
09
to use the speaker jack. If so, right- You can use a webcam, but
click on the volume icon in the menu Raspberry Pi has a dedicated You can see the mechanical
bar and switch from HDMI to Analog. option: the Camera Module drawings for Raspberry
Alternatively, use the command line: (magpi.cc/jbKzbf). This is attached Pi 3B+ (and all other models)
to the CSI (Camera Serial Interface). on the Raspberry Pi website:
amixer cset numid=3 1 The Camera Module is used to take magpi.cc/WWFUji.
high-definition video and still
Wireless hotspot
10
Set the last number to ‘1’ for Analog, images. It’s easy to use for beginners,
or ‘2’ for HDMI. Use raspi-config to but has plenty to offer advanced Many Raspberry Pi models
change the audio setting at boot: users if you’re looking to expand feature a wireless LAN adapter
your knowledge. There are lots of to connect to local network. But you
sudo raspi-config examples online of people using it for can also use the access point to create
time-lapse, slow-motion, and other a wireless hotspot. The process is a
Choose Advanced Options > Audio and video cleverness. You can also use the little long, but it’s great for learning
‘Force 3.5 mm (‘headphone’) jack’ or libraries Raspberry Pi has developed more about how wireless LAN works.
‘Force HDMI’ to set this as the default. to create visual effects. Read more at magpi.cc/nnriRT.
A N T I P S
RASPBI
p b e rr y P i’ s operating
a s
Customise R
Add some
cks.
e tips and tri
visual flair to
w it h t h e s the Raspbian
system
interface using
ersley
the Screensaver
By Lucy Hatt
program
Demo programs
11 Raspbian comes with a bunch of demo sudo apt-get update
programs that demonstrate various sudo apt-get install xscreensaver
features. Find them here:
Understand config.txt
13
You will now be able to run the .bin files in
each example folder. For instance, run: Note: this is for advanced users only!
Raspberry Pi uses a configuration file
cd hello_tiger instead of the BIOS found on most PCs. This
./hello_tiger.bin file is normally accessible as /boot/config.txt
from Linux, and must be edited as root.
…to see a large rotating image of a tiger on the
screen. For more info, see magpi.cc/tpNaGV. sudo nano /boot/config.txt
Screensaver
12
Any changes will only take effect after you
By default, the Raspberry Pi Desktop have rebooted your Raspberry Pi. After Linux
Raspbian has a doesn’t have easy-to-use screensaver has booted, you can view the current active
selection of demo
software installed. Firstly, you should install settings using the following commands:
programs hidden in
the opt directory the X Windows screensaver application.
vcgencmd get_config <config>
Y T I P S
SECURIT
k a b o u t s e curity when
o thin rld
You’ll need t rr y P i t o t h e outside wo
aspbe
connecting R
Change your password
16 With the standard install of Raspbian, the
default username is pi and the password is
Free up space
14
raspberry. If you haven’t at least changed this
You can save space on your microSD card password, anyone can log into your Raspberry
for projects, documents, and code by Pi! Go to Menu > Preferences > Raspberry Pi
removing some of the programs provided in Configuration. In the System tab, click Change
Raspbian by default.You can remove software Password, enter one, confirm it, and click OK.
from the command line:
Keep Raspbian up to date
sudo apt purge mathematica
sudo apt clean
17 From time to time, security
vulnerabilities are found in software, so
sudo apt autoremove it’s always best to get the latest versions on a
regular basis. In a Terminal, type sudo apt-
But it's much better to choose Menu > get update to update your package lists, then
Preferences > Recommended Software. Clear sudo apt-get dist-upgrade to get the latest
the tick next to the unwanted program and version of the packages on your system.
click OK.
Install Fail2ban
Kernel update (& rollback) 18
15
If someone wants to hack into a Raspberry
If you use the standard Raspbian update/ Pi, they may try to guess your username
upgrade process, this will automatically and password. It will probably take a lot of
update the kernel to the latest stable version. attempts, but this is called ‘brute-forcing’. To
This is the recommended procedure. However, prevent this, you can install a program called
sometimes you may wish to update to the Fail2ban. Install using sudo apt install
latest ‘bleeding edge’ or test kernel. fail2ban and a user will be banned for ten
minutes if they fail login five times.
sudo rpi-update
Change default SSH port
The rpi-update utility will download the 19 If you change the default SSH port,
latest (unstable, testing) kernel version and anyone trying to connect would need to
copy all required files onto your system. Note know which port to use. To alter it, sudo nano
that the latest kernel from rpi-update is /etc/ssh/sshd_config and change the line
not guaranteed to work correctly! Make sure #Port 22 to read Port 2222 (without the #) or
that it doesn’t conflict with your distribution another memorable number. Save and exit
packages. It doesn’t provide a way of (CTRL+O, ENTER, CTRL+X), then restart SSH
automatically uninstalling the files. with sudo service ssh restart.
To revert to the current stock Raspbian
Turn off interfaces
20
kernel after trying rpi-update or a custom
kernel, you need to reinstall both these you don’t need
packages, by running: The safest way to stop hackers is to not
have any network connection, but another way
sudo apt-get install --reinstall of shutting down the system a bit more is to
raspberrypi-bootloader raspberrypi- go into Main Menu >→ Preferences >→ Raspberry
kernel Pi Configuration and select the Interfaces tab.
Make sure everything you don’t need is disabled.
K I N G T I P S
G A N D M A
CO D I N
sp berry Pi.
o m y o u r m akes with Ra
Get more fr
ersley
By Lucy Hatt your project together, and less time figuring
out how to get it to work. Bookmark the
Switch to Thonny
21
documentation: gpiozero.readthedocs.io.
If you’re still programming in Python
Make circuit diagrams
23
IDLE or using Text Editor, then switch
to Thonny. It is just as easy as the other Fancy making a circuit board diagram
programs, but has a simple debugger that like the ones you see in The MagPi
makes it much easier to fix flaws in your magazine? The software you’re looking for
code. Press CTRL+F5 instead of F5 to run is Fritzing. It’s currently in beta, and we
a program step-by-step. Unlike more mostly use the Windows version to create
advanced IDEs, you don’t need to set the images you see in The MagPi. However, a
breakpoints. Press F6 for a big step and F7 version is available for Raspberry Pi.
for a small step. It’s ideal for makers because
it enables you to fix problems, but isn’t so sudo apt-get update
involved that you get completely absorbed in sudo apt-get install fritzing
code and so you can carry on with your build.
Restart your Raspberry Pi and you’ll find the
GPIO Zero
22
program under Menu > Programming. We are
Make sure you learn to code using the currently having trouble opening the parts
The Thonny
IDE (integrated GPIO Zero Python library (now in version bin on Raspberry Pi; if any readers have a fix,
development 1.5). This boilerplate library is designed then please let us know.
environment) makes
it easier to debug to take the hassle out of using electronics
Raspberry Pi and Arduino
24
your programs components and kits with Raspberry Pi. With
without getting
too distracted GPIO Zero you can spend more time putting Raspberry Pi works fantastically well
with an Arduino attached. Despite
looking visually similar, the two boards are
very different. Raspberry Pi is a complete
single-board computer, while the Arduino
range are microcontrollers. They work
fantastically well together because the
Arduino is handy for controlling parts, with
Raspberry Pi better for the higher-level
interface and master control. You can install
the software to control an Arduino from
Raspberry Pi:
25
Codewars is a good
web resource for
breadboard in our diagrams, so if you get that practising and flexing
One of the best ways to boost your
type you’ll find it much easier to follow our your programming
programming skills is to complete muscles
projects: magpi.cc/dXHByV.
challenges. If you are looking for some Learning the
programming challenges, then sign up for ‘Western Union’
Second-hand
splice technique will
28
Codewars on your Raspberry Pi. The website make your soldering
joints stronger
(codewars.com) has a video game style, and Get to know your local second-hand
you get points and advance through levels by (‘thrift’) store. Used objects can be a
completing challenges (kata). We’ve even seen great source of inspiration, and upcycling old
the latter being used in job interviews and to tech with new Raspberry Pi parts is a popular
gain entry to coding boot camps. pastime. High-profile maker Martin Mander
has rescued old radios, televisions, and toys.
Learn to solder
26
Follow him on Twitter (@MartinWMander)
There’s a technique to soldering wires for inspirational ideas.
together called the ‘Western Union’ or
Share early and often
29
‘Lineman’ splice, and you should learn it if
you’re going to solder (magpi.cc/mckKVW). It The best way to get inspiration and help
was developed during the introduction of the for your project is to share it with the
telegraph (hence the name), and the wrapping Raspberry Pi community. In March 2019,
pattern is designed to tighten as the two ends The MagPi ran #MonthOfMaking on Twitter, to
pull against each other. encourage readers to share projects with one
another. But don’t wait till next year – share
Make a maker kit
27
your project on our forum (magpi.cc/forum),
We can’t recommend highly enough Facebook (magpi.cc/facebook), or Twitter
putting together a maker kit. This should (@TheMagPi). The more other readers see your
contain a wide range of electronics parts, bits, project, the more likely you’ll be to finish it.
and tools. Find a good components case and
Tips for makers
30
put in it a selection of resistors, capacitors,
LEDs, buttons, potentiometers, a piezo buzzer, Element14 has two collections of Tips for
and a breadboard with lots of jumper cables. Makers packed with interesting ideas.
You can pick up kits and parts from most Sign up with the Element14 website to access
Raspberry Pi resellers, or visit the Raspberry them: magpi.cc/XQaCyC.
G T I P S
NE T WORKIN i
o re a b o u t Raspberry P
wm s
Need to kno re are some of the basic
He ady
networking? s t in g t ip s if you’re alre
tere
and some in You can connect your Raspberry Pi to a
p
networked u
local area network and the internet using
an RJ45 cable or by configuring WiFi
Wired or wireless
31
provide similar information. Your local
You’ll Need Raspberry Pi has two standard ways of IP address will be the number that looks
connecting to a network: with an Ethernet something like 192.168.0.34. You can also
> N
etwork cable cable or on-board WiFi (on newer models). find your IP address by hovering over the
> Internet router The Ethernet cable is usually either a Cat5e network icon (top right) of your desktop.
or Cat6 (for fast networks) type, with an RJ45
> Internet connection
IPv4 and IPv6
33
connector on each end. One end plugs into a
router or hub and the other end into Raspberry The terms IPv4 and IPv6 are descriptions
Pi. Wired connections are generally faster of the internet protocol and address.
than WiFi and will connect as soon as the IPv4 uses 32-bit numbers for the address
cable is plugged in. Home wireless network and looks something like: 192.168.1.23. As
connections can usually be connected to by the internet has now grown so large, the
just selecting the network and typing in a limited number of available IPv4 addresses
password – see magpi.cc/HiDkyk. has become a problem. A new version of
IP (IPv6), using 128 bits for the IP address,
Know your IP
32
has been defined. In July 2017, the final
An IP (Internet Protocol) address is a definition of the protocol was published,
number allocated to your Raspberry Pi although IPv6 has been in use for over 20
so that other computers know where to find years. An IPv6 address looks something like:
it on the network. There are several ways to fe80:94c:38c8:4600:7b33:64bb:baf7:e866. On
find your Raspberry Pi’s current IP address. a home network you will normally be using
In a Terminal window, there are a couple of IPv4 format addresses, but look out for that
You can use the commands you can use. The old command to change in the future.
curl tool to download (which still works) is ifconfig. There is a
Useful commands
files, such as PDFs of
34
The MagPi issues new shorter command now, ip, which will
You can do quite a lot with network
commands in the Terminal. Some
commands need to be installed first. The
ping command is there by default. If you type
ping and then either an IP address or a web
domain, it will tell you how long it takes to
send a message to that computer/server and
then get a reply. Cat is also pre-installed.
Type cat /sys/class/net/wlan0/operstate
to see the status of your WiFi connection.
Install whois with sudo apt-get install
whois and then type whois with a domain
name and you will find the registration
details of that domain.
Networking files
35 Raspberry Pi has several files where
it holds details about networking. It’s
quite useful to know where some of these
are, as you may need to change some of the
information for custom configurations. The
file /etc/hosts has a list of names that map
to IP addresses. You could have an entry that
says ‘192.168.0.3 myserver’ and that would
mean that if you typed ‘myserver’ into a web
browser address bar, the network would try
to connect to 192.168.0.3. Other useful files
are /etc/networks, which has network names can connect to any Telnet server. For example, You can use lots
of different tools
mapped to IP addresses; /etc/protocols, which enter telnet towel.blinkenlights.nl 23 to find out about
has a list of all the network protocols that can to see an ASCII version of Star Wars, or try your Raspberry Pi
network connections;
be used; and /etc/services, which has a list of telnet mtrek.com 1701 for a Star Trek you can even play
all the network services available. game. There are lots of Telnet sites still online games in the
Terminal window!
out there, some of which can be found at:
Network traffic
36 If you want to know what’s happening
telnet.org/htm/places.htm.
PiServer
between your Raspberry Pi and the rest of
the network, there are a few commands you can 38 PiServer is a useful tool for networking
install. A simple stats command is available many Raspberry Pi boards together
with sudo apt-get install vnstat. When without needing SD cards in them. For info on
you run this command, it will give you some how to set it up, go to magpi.cc/RQDQXx.
basic data transmission totals. If you want
Downloading files with curl
39
some extra tools, you could install iptraf-ng,
which has a menu of different tools and filters You can download files directly in the
to analyse the network traffic. To see some Terminal with the curl tool. Use curl -O
real-time data transfer stats, install bmon, <URL>. See magpi.cc/JrKoTA for more info.
which shows data quantities per second.
Headless wireless
37
Telnet
Although Telnet is a very old networking
40 If you use the Raspberry Pi in a ‘headless’
mode (without the Raspbian interface), it
system (first designed in 1969), it is still can be tricky to connect to a wireless network.
available and can be installed on Raspberry Pi You will need to define a wpa_supplicant.conf
using sudo apt-get install telnet. Telnet file for your particular wireless network and
is a bit like a very early version of websites put this file in the boot folder. See here for
and when this is installed, your Raspberry Pi more information: magpi.cc/RHviuV.
E T R I C K S
COMM AND LIN
-line
g t o u p y o ur command most
Lookin s in troduces the
P J E v a n
game? t s and tricks command1; command2; command3
r s h o rt c u
popula
To only proceed if the previous command
Piping
41
has succeeded:
Applications in Linux systems,
such as Raspbian, have three ways command1 && command2 && command3
of communicating with you and other
applications: standard in (stdin), standard For example:
out (stdout), and standard error (stderr).
Output from a command-line application mkdir ~/myDir && cd ~/myDir && nano
arrives on stdout and you can use the pipe myFile.txt
character ‘|’ to send that output directly into
another application, like this: …will create a directory, move into it, and
open up the nano text editor with a new file,
ls -l | wc -l myFile.txt. You can save this line somewhere
for future use or create an alias (see Tip 47).
Here we get a long-form listing of the current
Run background tasks
44
directory and pipe that output into ‘wc’, a
counting application. The -l argument means Running a command ‘in the background’
‘count the lines’, so we now have a ‘new’ app enables you to issue other commands
that tells us how many items are in a directory. while it works. If you’re using the Desktop,
You can chain as many commands as you wish the simplest solution is to open another
to achieve complex tasks. Terminal window. Alternatively, to have
a process run in the background, add an
Output redirection
42
ampersand (&) at the end of the command:
Try this:
very-long-command &
curl https://cataas.com/cat
This works well, but any output to stdout and
The command downloads a cat image – but stderr will appear on your console screen. To
you’re on the Terminal, which can’t show avoid this, use ‘nohup’:
graphics. The image arrives as a lot of
nonsense on stdout. We can use redirection to nohup very-long-command &
save it as a file like this:
Now all output is written to nohup.log in
curl https://cataas.com/cat > cat.jpg your current directory.
less text.txt
tail text.txt
tail -f text.txt
46
A miscellany of shortcuts
S H O OT I N G
TROUBLE
Tilde – The tilde character ‘~’ always refers
to your home directory in paths. So cd ~
always takes you home (as does cd on its own).
Get in remotely
50
nano ~/.bash_aliases
We’ve all been there: happily working
For each alias you want to create, enter a line away in Raspberry Pi Desktop and
following this pattern: something goes awry. Now the screen has
locked up, your Doom high score is lost, and
alias howmany="ls -l | wc -l" the only option is to unplug your Raspberry
Pi, which risks data corruption. Well, you
Now you can run howmany for that command. may be able to get in using SSH, which allows
you to log into your Raspberry Pi (so long as
It’s got stuck!
48
you’ve already enabled SSH on it) from another
Stuck with a crashed program on your computer and get to the command line:
screen? To gain access back to the
prompt, try CTRL+C to stop the process, or ssh raspberrypi.local
CTRL+Z to put it in the background. Now enter
killall <commandname>. You can use ps ax to Then, if you get to a prompt:
show a list of running processes. Still there?
Try sudo killall <commandname>. As a last sudo shutdown -h now
resort, use sudo kill -9 <processid> (get
the process ID from ps ax). …and your Raspberry Pi is rescued.
Build a
Lucy Samba file server
MAKER
Hattersley
Lucy is the editor Use Samba/CIFS to share a Raspberry Pi directory
of The MagPi
magazine. She
enjoys hacking and
with other computers on a network
fixing technology,
and building quirky
I
projects. She’s
done the Samba all
t’s easy to use a Raspberry Pi as a Samba We also assume you’re using a 32GB (or smaller)
weekend long! file server where you can store backups and microSD card, which provides a reasonable amount
magpi.cc share files from all the other computers on of storage space without requiring any extra steps
your network. to make it accessible. However, if you need extra
Samba is the Linux implementation of the SMB/ storage, it’s possible to mount a large external USB
CIFS file-sharing standard used by Windows PCs drive and create a Samba entry for it.
and Apple computers, and widely supported by Alternatively, if you want to keep things
media streamers, games consoles, and mobile apps. compact, you can install Raspbian on microSD
With Samba activated, you can quickly copy files cards of up to 256GB, although we think it’s
from a computer on your network to a Raspberry Pi wiser to install Samba on an external drive and
using wireless LAN (or a direct Ethernet connection). use a smaller microSD to boot Raspbian and
This tutorial assumes that you’ll use a keyboard, connect to it.
mouse, and monitor to set up your file server; We suggest checking non-working microSD
alternatively, you can enable SSH (magpi.cc/ssh) cards online (magpi.cc/2q97aGO) before you buy,
and connect to it remotely from another computer to make sure you get one that’s fully compatible
on your local network. with the Raspberry Pi.
You’ll Need
> Raspberry Pi
Top Tip
Status report
You can see the
status of the
Samba drive using
sudo service
smdb status.
And you can use
smbd restart to
turn the service
off and on again.
Once set up, you can mount your home file is fully updated, and install Samba using APT. Open
server on all the other computers on your a Terminal and type:
network, and use it as a convenient place to store
everything from music files you want to share sudo apt update
with your housemates, to backups of important sudo apt upgrade
documents and save-game files you’d like to share sudo apt install samba samba-common-bin
between computers.
We recommend using a wired Ethernet Answer Y when prompted.
connection for stability and fast transfer speeds.
The project will still work if you connect your
Raspberry Pi via WiFi, although performance will be
Create shared directory
affected, particularly when it comes to copying over
large files.
03 Now we’re going to create a dedicated
shared directory in our home directory.
Install Samba
02 Samba is available in Raspbian’s standard
software repositories. We’re going to update our
repository index, make sure our operating system
directory from other computers on your network. of the file and add the configuration code from the
Files you drop in here are accessible on other smb-pi.conf listing. Press CTRL+O to save the file,
computers, and files you drop into the directory and CTRL+X to exit nano.
from other computers will appear on Raspberry Pi.
valid users = pi
browsable = yes
writable = yes
testparm
smb-pi.conf DOWNLOAD
sudo smbpasswd -a pi THE FULL CODE:
Enter a simple and memorable password for > Language: ASCII magpi.cc/ryrLvF
testing (you can create a more secure one later by
rerunning the command at any time). 001. [share]
Now restart your Samba server: 002. path = /home/pi/shared
003. available = yes
sudo service smbd restart 004. valid users = pi
005. read only = no
The Samba service will restart and the shared drive 006. browsable = yes
will now be available on the network. 007. public = yes
S
SH (also known as ‘Secure Shell’) is an SSH also enables you to share files to, and
encrypted networking technology that from, a Raspberry Pi using SCP (secure copy)
enables you to manage computers from on the command line, or SFTP (SSH File
Lucy
MAKER
You’ll Need
> Raspberry Pi
> Raspbian OS
hostname -I
Top Tip
This will return four numbers separated by dots.
For instance, ours is: SSH from boot
You can activate
192.168.0.41
SSH when setting
up Raspbian
S
SH is turned off by default in Raspbian and has to Write this number down. You’ll need it shortly. by placing a
be enabled. The easiest way is to use Raspberry Pi
Configuration Tool file named ssh,
without any
extension, onto
Activate SSH in Raspbian Connect via SSH the boot partition
01 For security reasons, Secure Shell is
04 Open Command Prompt on a Windows PC,
of the microSD
card from another
not turned on by default in Raspbian. On your or a Terminal window in Linux or macOS. computer. When
Raspberry Pi, choose Menu > Preferences > Enter this command: Raspberry Pi
Raspberry Pi Configuration. Click on Interfaces and boots, it looks for
set SSH to Enabled. Click OK. You don’t need to ssh pi@<IP> the ssh file. If it
restart your Raspberry Pi, and SSH will be enabled is found, SSH is
enabled and the
whenever you use that installation of Raspbian Replace <IP> with the IP address of your Raspberry
file is deleted. The
from that point on (be sure to have updated your Pi. In our case, we enter ssh pi@192.168.0.41.
content of the file
password from the default, which is ‘raspberry’). The first time you do this, you’ll get a message does not matter; it
saying that the authenticity can’t be established, could contain text,
followed by a long cryptographic hash of letters or nothing at all.
and numbers. It will say, ‘Are you sure you want to
Activate SSH Client in Windows
02 Linux and macOS both support SSH out-of-
continue connecting?’
Enter yes and press RETURN. You’ll be asked to
the-box; skip ahead to Step 3 if you are using one enter the password for your Raspberry Pi.
of those operating systems.
Windows 10 supports SSH, but you need to
activate it. Click on Search and look for ‘Manage
On Raspberry Pi
Optional Features’. Click it in Search to open the
Settings window.
05 You will now see your usual command line
Click ‘Add a feature’ and wait for the list of replaced with pi@raspberrypi: ~$. You are now
Optional Features to load. Scroll down the list to logged in and working on the command line from Use the hostname
command in
Open SSH Client (Beta). Click Install. your Raspberry Pi. Enter ls and you’ll see Desktop, Terminal to confirm
Downloads, Documents, and the other unique the host name
‘raspberrypi’,
Raspberry Pi folders and files. You can create, edit, and add the -I
flag to get your
move, and work with files as if you were using
assigned IP (internet
Get your IP address
03 Connect your Raspberry Pi to a local network.
Terminal on your Raspberry Pi. protocol) address
hostname
raspberrypi
Visual interfaces
Top Tip 06 There are limitations to SSH. A plain
SSH connection can’t open programs that use a
Turn SSH on graphical interface, so you should learn to use
and off command-line alternatives (such as nano or vim
instead of Leafpad for text editing). See How to Edit
You can activate Text files on Raspberry Pi (magpi.cc/BNFKeP).
and start
On Linux computers, you can forward your X
SSH from the
command line on
session over SSH, to allow the use of graphical
your Raspberry Pi: applications, by using the -Y flag:
SWITCH TO THE
COMMAND LINE
By using the command line, you are able to work faster and smarter.
Discover how to get started today…
T
here’s nothing wrong with GUIs (graphical pi@raspberrypi:~ $
You’ll
Need user interfaces), and Raspbian comes with
a rather fine desktop interface. But beneath You are now at the command line. You enter commands
> R
aspberry Pi
the icons sits a whole other world: the command using the text interface. Enter echo Hello World and
> R
aspbian line. This is where your real computer is. With the press RETURN, you’ll see ‘Hello World’ printed on the
command line, you’re not locked into doing just line. Below this is another $ prompt, ready to accept
what desktop applications enable you to do. You can another command.
do just about anything to your computer, and you Most users get to the command line via the
can do it much faster. Terminal app, but there is another way known
Think of it like driving a car. If you’ve only ever used as ‘virtual console’. Press CTRL+ALT+F1 and
a GUI then you’re driving an automatic. The command the desktop will vanish. A black screen appears,
line is like switching to manual. It can be daunting for displaying ‘Raspbian (or Debian) GNU/Linux 8
newcomers, but it really needn’t be. With just a few raspberry pi tty’ and below it, ‘raspberrypi login’.
commands, you can master the command line. If you are not automatically logged in , enter pi and
press RETURN, then enter your password (raspberry
Typing commands by default, but you should always change it).
When you boot a Raspberry Pi, you start by default You can now use the command line in full-
inside the desktop interface. The fastest way to get screen mode. You can get back to the desktop using
access to the command line is through the Terminal CTRL+ALT+F7 and switch back to the virtual console
app. Click on the Terminal icon in the top menu bar using CTRL+ALT+F1. Additional virtual consoles can
(or choose Menu > Accessories > Terminal). A window be accessed using CTRL+ALT+F2 to F6. Each has its
opens with a black background and some green and own login and operates independently.
blue text. You will see the command prompt: If you prefer the command line, you can boot
Raspbian directly to the command line instead of the
desktop interface. Open Raspberry Pi Configuration
(Menu > Preferences > Raspberry Pi Configuration).
Change the Boot setting to ‘To CLI’ and click OK. Now
when you reboot, you’ll start in the command line
(enter startx to start up the desktop).
Locate yourself
The first thing you need to learn is how to find out
where you are. You are in your home folder by default.
Most people access
the command
Enter the following command and press RETURN:
line through the
Terminal app in the
desktop interface pwd
pi@
The first part of the
command line is your
user name followed
by an @ symbol. You
can see this on the
command line by
entering whoami.
raspberrypi
After the @ comes
your host name.
It is the name of
your computer:
‘raspberrypi’ by default.
~/Documents
After the host name is
your current working
directory. This displays
just ‘~’ when you are in
your home folder.
$
The dollar sign shows
you’re operating as a
normal user.
ls
The first part of a
command is the
command itself. Here we
have ls, which lists the
contents of a directory.
-lah
After the command
come options. These
start with a hyphen
and are typically single
letters. Each modifies
the command. Here we
have ‘l’, ‘a’, and ‘h’. These
stand for long listing
mode, all files, and
human-readable.
/home/pi/
Documents
The final part of the
command is the
arguments. These
are often file names
or file paths. Here we
are listing an absolute
(direct) path to the
Documents directory. If
you omit the argument,
it’ll display the contents
of the current directory.
The eagle-eyed reader may have noticed the weird directories like bin (for binaries), boot (files used to
backslash character: ‘\’. You can’t have spaces in file start up the system), and home. Enter:
names, so you use a backslash followed by a space at
the command line. Most of the time you’ll also use ls /home/pi
the TAB button to quickly enter long file names (see
‘Tab completion’). …and you’ll view the contents of your home folder,
File paths come in two types: relative and absolute. just as if you had entered ls from within it.
Relative paths are ‘relative’ to your working directory, You can use absolute paths no matter what your
which is /home/pi/ when you start. Entering ls alone working directory might be, because they always
shows the contents of the current directory. You can start from the root.
view the contents of a directory inside your working
directory using ls and its name: Moving around
Up until now we’ve stayed in the home folder
ls Documents and looked around using ls. You move from
one directory and another using the cd (change
You can also view the contents of the directory above directory) command:
you using two dots (..):
cd Documents
ls ..
Now enter:
This displays files relative to where you currently are
in the file system. If you moved into the Downloads pwd
folder and entered ls Documents, it’d cause an error,
because there is no Documents directory inside the …and you’ll see a different working path:
Downloads folder. /home/pi/Documents. To move back up a directory
An absolute path, on the other hand, always starts (known as the ‘parent’ directory), you use two dots.
with a slash ‘/’, which is the root directory (the base of
your hard drive). Enter: cd ..
…and you’ll be in the root directory. Enter ls to view > Owner: Typically this will be the person who created
the folders at the base of your hard drive. Enter: the account.
> Group: This is a group of users. You have only one
cd /home/pi group, pi, by default, containing just one
user (also pi).
…to move back to your home folder. There’s a > Other: These are users from other systems.
shortcut for this:
Each of the three groups contains letters: ‘rwx’. These
cd ~ letters are always in that order and each is either the
letter or a hyphen. A letter indicates that the person,
The tilde (~) character is a shortcut for your home group, or other has access to read, write, or execute the
folder. You can use it at the start of an absolute file. A hyphen means they don’t have that level of access.
directory too. For instance, entering: Some examples include:
cd ~ space) and a newline marker at the end (you can see this
mkdir test character using od -c test.txt if you’re curious).
cd test Let’s try deleting files. This command removes the file:
To create files, you use the touch command; if the file rm test.txt
doesn’t exist, it creates an empty one. Enter:
Now move up to its parent directory and use another
touch test.txt command, rmdir, to remove the empty test directory.
Options
Most commands have options that affect how they
work. It’s common to use these three options with
the ls command:
ls -lah
• a = all including hidden files But with it, you can remove or delete vital system
• h = human-readable (makes large file sizes files. Enter ls /bin and you’ll see many programs
more readable) (known as ‘binaries’) used by Linux. These include
the ls command you just used. Accidentally deleting
Options are case-sensitive. So ls -l and ls -L are these files could make your system unstable.
two different things (small ‘l’ is long listing format; So use sudo with care. In Raspbian you don’t need to
large ‘L’ is dereference mode). Sometimes options are enter the password to use sudo. On many other Linux
listed out in full. These start with two hyphens and systems, however, you will be asked for the password
have a single hyphen for spaces. This command is the before you can use sudo.
same as ls -lah:
What’s up, man?
ls -l --all --human-readable There are lots of ways of getting help inside the
command line. The first command you should turn
But it’s more common to see (and use) the single to is man. This stands for ‘manual’ and gives you
letter approach. instructions on Linux commands and tools. Enter:
Sudo man ls
Sudo stands for ‘substitute user do’, although it’s
often also called ‘superuser do’. If you have multiple …and you’ll see the manual for the list command.
users on your system, it can be used to perform Notice under the SYNOPSIS it says:
commands as another user.
It’s mostly used to get root access to your Linux ls [OPTION]... [FILE]...
installation. There is an account that controls your
pi user, called ‘root’. This is an all-powerful account, This shows you the structure of the command.
which can change just about anything on your system. Almost all commands are in the ‘command, option,
Your default account can view files in the root of argument’ structure, although some arguments have
the hard drive, but it can’t create or delete files at more than one [FILE] argument (such as copy, which
the root. Enter: requires a source and destination file).
Press the space bar to move down the instructions.
cd / Here you will see a list of all the available options.
touch test.txt With man, you can get detailed information on just
about every tool on the command line. You can even
You’ll see touch: cannot touch ‘test.txt’: Permission get a manual for the man command with:
denied. However, enter:
man man
sudo touch test.txt
If you need a quick reminder on how to use a
…and the test.txt file will be created on the root of command, try using it with -h or --help as an option:
your hard drive. You can see it using ls -l.
Now try to delete it: touch --help
rm test.txt …tells you what options are available with the touch
command. You can use this with many command-line
It will say rm: remove write-protected regular empty tools to get a quick refresher on how they work.
file ‘test.txt’?” Enter Y and it’ll say rm: cannot Moving from a GUI to a command line is a vital skill for
remove ‘test.txt’: Permission denied. hackers and coders. Everything on your computer, from
You need to use sudo to remove the file: programs to preferences, is stored in the file system
somewhere. Learning to use the command line makes
you a more capable Raspberry Pi user.
sudo rm test.txt So, the next time you make a file, move a file, or
delete something, don’t head to the File Manager.
You can see why sudo is such a powerful tool. Without Open Terminal and perform tasks from the
it, you couldn’t install software using apt or apt-get. command line. Soon it’ll be second nature.
3A+
Raspberry Pi
T
he last time the Raspberry Pi family had a
new A-form-factor design, more compact
and lightweight than the full-size B and B+
ranges, it was Raspberry Pi A+, released four years
ago. Since then, the family has grown considerably:
we’ve seen Raspberry Pi 2, 3, Zero, Zero W and WH,
3B+ and, most recently, Raspberry Pi 4.
UK suppliers:
SPECS
SoC:
Broadcom
BCM2837B0 Full-size display (DSI) and
quad-core A54 camera (CSI) ports make
connecting peripherals a snap
(ARMv8) 64-bit
@ 1.4GHz
GPU:
Broadcom
VideoCore IV
NETWORKING:
2.4GHz and 5GHz The radio, originally developed
802.11b/g/n/ac for 3B+, makes Raspberry Pi
wireless LAN 3A+ the first A-model to feature
on‑board networking
RAM:
512MB LPDDR2
SDRAM
BLUETOOTH:
Bluetooth 4.2,
Bluetooth Low Raspberry Pi 3A+ benefits
from the same clever
Energy (BLE)
power management chip
(PMIC) as 3B+
GPIO:
40-pin GPIO
header,
populated
STORAGE:
microSD
PORTS:
HDMI, 3.5 mm
QuickStart guide
analogue audio-
video jack,
1 × USB 2.0, Raspberry Pi 3A+ is directly compatible with 3B+
Camera Serial
and all other Raspberry Pi models. If you’ve already
Interface (CSI),
Display Serial got a power supply and microSD card with a new
version of Raspbian installed, you’re ready to go. Unlike the Zero family,
Interface (DSI)
Raspberry Pi 3A+ includes
If 3A+ is your first Raspberry Pi, check out pages both full-size HDMI and
analogue audio-video outputs
6–13, or see our online QuickStart guide to get up
DIMENSIONS:
67×56×11.5 mm and running fast.
magpi.cc/quickstart
Raspberry Pi 3A+
Pi 3A+ loses any performance
compared to 3B+
F
or projects where a full- lightweight, and less power- which runs at the same 1.4GHz
size Raspberry Pi is simply hungry package, but the only frequency. While 512MB of RAM
too bulky, there hasn’t way to see if that is true or not is less than the 1GB of a 3B+, the
been much choice: aside from is to put it through its paces in a smaller Raspberry Pi 3A+ can
the Compute Module 3, which range of benchmarks. certainly hold its own.
is targeted at industrial users, Looking back at the original
the choices were the four-year- Raspberry Pi A+, it’s hard to
old Pi A+ or ultra-compact Pi Spec comparison imagine they’re from the same
Zero family – and in either At its heart, Raspberry Pi 3A+ is family: from a single-core
case it meant a dramatic drop a cut-down version of 3B+. It has 32-bit 700MHz processor and
in performance. the same Broadcom BCM2837B0 no networking to a quad-core
Raspberry Pi 3A+ comes system-on-chip (SoC) roughly in 64-bit 1.4GHz processor with
with the promise of full- the centre of the board, hidden built-in wireless LAN and
size performance in a small, under a metal heat-spreader, Bluetooth. What an upgrade!
Higher is better
264.5
Designed to highlight a real-
world bottleneck, the Python
GPIO benchmark switches a 181.9
single pin on and off while a
frequency counter measures 62.32
58.55 48.75
how quickly the pin is toggled. 43.07 42.63 42.62
The faster the processor, the
faster the pin can be toggled
before the processor hits its limit. Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+ Pi 3A+
857.96 856.48
SysBench 1kB READS (MBps)
Memory Throughput 1kB WRITES (MBps) 719.76
638.27
Higher is better 632.27
547.9
Processor performance is only 425.87
part of the puzzle regarding
overall system performance: in the 314.31
SysBench Memory Throughput test, 147.27 139.01
measurements show how quickly 120.12
118.14
a Raspberry Pi can read and write 108 105.65
106.9 103.03
99.97 81.25
to the random-access memory 89.43 75.99
(RAM) in 1kB chunks, reported in
megabytes per second (MBps). Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+ Pi 3A+
42 42
39 40
3930 3930
30
29
23
2074 2074
10
8
Bringing back A+
“What’s the cost to do a certification “The A+ form factor was always a good form
campaign,” Eben asks. “Couple of factor,” says Roger Thornton, Principal Hardware
hundred thousand?” Engineer. “A lot of people have asked us for an A+
“For a five-gig one, yeah, it’s about again, and we were able to make that, so we did.”
250… 300 000,” answers Roger – the cost With both Raspberry Pi 2 and 3 having
of clearing a radio-containing product launched exclusively in larger B-variant form
like the Raspberry Pi 3 for general sale. As with any Raspberry Pi, factors, the A+ has been absent from the line-up
3A+ undergoes in-depth
Raspberry Pi 3B+ moved to a modular for a full two generations. “It was skipped for
testing before it’s released
radio certification, so the existing to the public Raspberry Pi 2 because it simply wasn’t around
compliance work remains largely valid
for 3A+. “A lot of the work we’d done to
modularise the board meant that we
could copy over pretty much all of our
compliance work,” Roger explains, “so
thankfully this product’s been just a bit
of paperwork. There’s definitely been an
improvement in time-to-market.”
“If we have an
opportunity to bring
our best tech down
a bit, then we do,”
explains Eben Upton
for long enough,” recalls Eben. “It normally takes Filling a hole
six to nine months for us to get our feet under “There’s a massive performance gulf between the
ourselves, and by that time it was very clear that 3B+ and Zero,” explains Eben. “3A+ represents us
the 3B was imminent.” bringing our best technology to the lowest possible
“The Zero W happened the year after the 3B,” price point. We can’t bring this technology down
Roger adds, “and to some extent addressed the gap to the Zero price point, at the moment, but we can
that an A+ might have occupied.” bring it down a bit.
The Zero family isn’t a complete replacement for “We don’t just like to sit there at $35 feeling
the A+, though, as the launch of Raspberry Pi 3B+ pleased with ourselves. If we have an opportunity
hammered home. to bring our best tech down a bit, then we do. I
• Faites attention lors de la manipulation de ce alle normative e agli standard pertinenti 한국어 być zgodne z odpowiednimi normami
produit pour éviter tout dommage mécanique applicabili nel paese di utilizzo previsto. dla kraju użytkowania i być odpowiednio
ou électrique au niveau de la carte de circuit L'alimentatore utilizzato dovrà fornire 5 V CC e Raspberry Pi 3 모델A+/ B+ oznakowane, aby zapewnić spełnienie
imprimé et des connecteurs. una corrente nominale minima di 2,5 A. 중요: 추후 참조를 위해 이 정보를 wymagań bezpieczeństwa i wymogów
• Évitez de manipuler ce produit lorsqu'il est Istruzioni per l’utilizzo in sicurezza 보관하십시오. eksploatacyjnych.
sous tension. Ne manipulez que par les bords • Questo prodotto non deve essere Wszystkie certyfikaty zgodności i numery
afin de minimiser les risques de dommages overcloccato. 경고 można znaleźć na stronie www.raspberrypi.org/
dus aux décharges électrostatiques. • Non esporre questo prodotto all’acqua o • Raspberry Pi 와 함께 사용되는 모든 외부 compliance.
• Tout périphérique ou équipement utilisé all’umidità e non collocarlo su una superficie 전원 공급 장치는, 해당 국가에서 적용되는
avec le Raspberry Pi doit être conforme aux conduttiva mentre è in funzione. 관련 규정 및 표준을 준수해야합니다. 전원 Português do Brasil
normes applicables dans le pays d'utilisation • Non esporre questo prodotto a fonti di calore. 공급 장치는 5V DC, 최소 정격 전류 2.5A를
et être marqué en conséquence pour garantir Il prodotto è progettato per un funzionamento 공급해야 합니다. Raspberry Pi 3 Modelo A+/ B +
la sécurité et les performances. affidabile solo alla normale temperatura 안전한 사용을 위한 지침 IMPORTANTE: POR FAVOR, GUARDE ESTAS
Pour tous les certificats et numéros de ambiente. • 본 제품을 '오버클럭’ 해서는 안됩니다. INFORMAÇÕES PARA REFERÊNCIA FUTURA.
conformité, veuillez consulter www.raspberrypi. • Utilizzare questo prodotto in un ambiente ben • 본 제품을 물이나 습기에 노출시키지 말고,
org/compliance ventilato e non coprirlo durante l’uso. 작동 중에 전도성 표면 위에 놓지 마십시오. Avisos
• Per l’uso, collocare questo prodotto su una • 본 제품을 모든 소스의 열에 노출시키지 • Qualquer fonte de alimentação externa
superficie stabile, piana e non conduttiva. 마십시오. 일반적인 실내 온도에서 안정적인 usada com o Raspberry Pi deve cumprir os
Deutsch Evitare che venga in contatto con oggetti 작동을 하도록 설계되었습니다. regulamentos e normas aplicáveis no país
conduttivi. • 본 제품을 통풍이 잘되는 환경에서 de utilização. A fonte de alimentação deve
Raspberry Pi 3 Modell A+/ B+ • Durante l’uso o lo spostamento del prodotto 사용하고, 사용 중에는 덮지 마십시오. fornecer 5V CC e uma corrente nominal
WICHTIG: BITTE BEWAHREN SIE DIESE prestare attenzione ad evitare danni • 이 제품을 사용하는 동안 안정적이고 편평한 mínima de 2,5A.
INFORMATIONEN FÜR ZUKÜNFTIGE REFERENZ. meccanici o elettrici al circuito stampato e 비전도성 표면에 놓고, 전도성 물품에 Instruções para o uso seguro
ai connettori. 접촉시키지 마십시오. • Este produto não deve ser usado em
Achtung • Evitare di maneggiare questo prodotto • 인쇄회로기판 및 커넥터의 기계적 또는 overclock.
• Jedes externe Netzteil, das mit dem mentre è alimentato. Afferrare solo dai bordi 전기적 손상을 방지하기 위해, 본 제품을 • Não exponha este produto à água ou à
Raspberry Pi verwendet wird, muss den per ridurre al minimo il rischio di danni da 취급할 때 주의하십시오. umidade, e não o coloque em uma superfície
einschlägigen Vorschriften und Normen scariche elettrostatiche. • 전원이 공급되는 동안에는 본 제품을 다루지 condutora durante a operação.
entsprechen, die im Bestimmungsland • Tutte le periferiche e le apparecchiature 마십시오. 정전기로 인한 손상 위험을 • Não exponha este produto ao calor de
gelten. Die Stromversorgung sollte 5 V utilizzate con il Raspberry Pi devono essere 최소화하기 위해 가장자리만 잡으십시오. qualquer fonte; Ele é projetado para operação
Gleichstrom und einen minimalen Nennstrom conformi agli standard pertinenti per il • Raspberry Pi 와 함께 사용되는 모든 주변 confiável à temperatura ambiente.
von 2,5 A liefern. paese di utilizzo ed essere dotate del relativo 장치 또는 장비는, 해당 사용 국가의 관련 • Opere este produto em um ambiente bem
Anweisungen für die sichere Verwendung marchio a garanzia della conformità con i 표준을 준수해야 하며 또한 안전 및 성능 ventilado e não o cubra durante o uso.
• Dieses Produkt sollte nicht übertaktet requisiti di sicurezza e prestazioni necessari. 요구사항을 충족하도록 표시해야 합니다. • Coloque este produto em uma superfície
werden. Per informazioni su numeri e certificati di 모든 준수 인증서 및 번호는, 다음 사이트를 estável, plana e não condutora durante o
• Setzen Sie dieses Produkt nicht Wasser conformità, visitare www.raspberrypi.org/ 참조하십시오. www.raspberrypi.org/compliance. uso, e não deixe que entre em contato com
oder Feuchtigkeit aus und stellen Sie es compliance. dispositivos que conduzem eletricidade.
während des Betriebs nicht auf eine leitfähige Polski • Tome cuidado ao manusear este produto
Oberfläche. para evitar danos mecânicos ou elétricos à
• Setzen Sie dieses Produkt keiner 日本語 Raspberry Pi 3 Model A+/ B+ placa de circuito impresso e aos conectores.
Wärmequelle aus. Es ist für einen WAŻNE: PROSIMY ZACHOWAĆ TE • Evite manusear este produto enquanto
zuverlässigen Betrieb bei normalen Raspberry Pi 3 モデルA+/ B+ INFORMACJE NA PRZYSZŁOŚĆ. estiver ligado. Somente manuseie pelas
Raumtemperaturen ausgelegt. 重要: 将来参照できるようこの情報は保管して bordas (laterais) para minimizar o risco de
• Betreiben Sie dieses Produkt in einer gut おいてください。 Ostrzeżenia dano por descarga eletrostática.
belüfteten Umgebung und decken Sie es • Wszelkie zewnętrzne źródła zasilania • Qualquer periférico ou equipamento usado
während des Gebrauchs nicht ab. 警告 używane z Raspberry Pi powinny być zgodne com o Raspberry Pi deve cumprir os padrões
• Stellen Sie dieses Produkt während des • Raspberry Pi と共に使用する外部電源は使 z odpowiednimi przepisami i normami de fabricação e uso relevantes para o
Gebrauchs auf eine stabile, flache, nicht 用対象国内の規制や基準に準拠したものに obowiązującymi w kraju przeznaczenia. país e assim garantir que os requisitos de
leitende Oberfläche und lassen Sie es nicht してください。 電源の出力は 5V DC で最 Zasilacz powinien zapewniać napięcie 5V DC segurança e desempenho sejam atendidos.
mit leitfähigen Gegenständen in Berührung 低定格電流が 2.5A でなければなりません。 i minimalny prąd znamionowy 2,5A. Para todos os certificados conformidade
kommen. 安全な使用のための説明 Instrukcje bezpiecznego użytkowania e números, visite www.raspberrypi.org/
• Seien Sie vorsichtig beim Umgang mit • 本製品をオーバークロックしてはなりま • Ten produkt nie powinien być przetaktowany. compliance.
diesem Produkt, um mechanische oder せん。 • Nie należy wystawiać tego produktu na
elektrische Schäden an der Leiterplatte und • 本製品を水や湿気にさらしたり、動作中に działanie wody ani wilgoci, ani umieszczać go Pусский
den Anschlüssen zu vermeiden. 導電性の面に置いてはなりません。 na powierzchni przewodzącej podczas pracy.
• Vermeiden Sie die Handhabung dieses • 本製品をどんな熱源からの熱にもさらさな • Nie należy wystawiać tego produktu na Raspberry Pi 3 Модель A+/ B+
Produkts während der Stromversorgung. いでください。本製品は通常の室温で動作 działanie ciepła z jakiegokolwiek źródła; ВАЖНО: СОХРАНИТЕ ЭТУ ИНФОРМАЦИЮ
Produkt nur an den Rändern anfassen, するように設計されています。 produkt zaprojektowano tak, aby działał ДЛЯ БУДУЩЕГО ИСПОЛЬЗОВАНИЯ.
um das Risiko von elektrostatischen • 本製品は通気性の良い環境で使用し、使用 niezawodnie w normalnej temperaturze
Entladungsschäden zu minimieren. 中に密閉しないでください。 pokojowej. Внимание!
• Alle Peripheriegeräte oder Geräte, die mit • 本製品の使用中は本製品を平らな安定した • Używać w dobrze wentylowanym otoczeniu i • Любой внешний источник питания,
dem Raspberry Pi verwendet werden, 非導電性の面に置き、導電性の物に接触さ nie zakrywać podczas użytkowania. используемый с Raspberry Pi, должен
müssen den geltenden Normen für せないでください。 • Podczas użytkowania należy соответствовать соответствующим
das jeweilige Land entsprechen und • 本製品を扱う際は慎重に取り扱い、プリン umieścić produkt na stabilnej, płaskiej, нормам и стандартам, применяемым в
entsprechend gekennzeichnet sein, um zu ト基板およびコネクター類への物理的また nieprzewodzącej powierzchni i nie dopuścić стране предполагаемого использования.
gewährleisten, dass die Sicherheits- und は電気的損傷を避けてください。 do kontaktu z przedmiotami przewodzącymi Источник питания должен обеспечивать
Leistungsanforderungen erfüllt werden. • 電源が入っている状態で本製品に触れるこ prąd. 5 В постоянного тока и минимальный
Alle Konformitätszertifikate und -nummern とは避けてください。 静電放電による損傷 • Należy zachować ostrożność podczas номинальный ток 2,5 А.
finden Sie auf www.raspberrypi.org/compliance. のリスクを最小限にするため、持つ際は端 obchodzenia się z produktem, aby uniknąć Инструкции по безопасному использованию
を持ってください。 mechanicznego lub elektrycznego • Этот продукт не должен использоваться
Italiano • 安全と性能の要件を満たすため、Raspberry uszkodzenia płyty z obwodami drukowanymi вопреки нормативам произодителя.
Pi と共に使用する周辺機器または装置は使 i złączy. • Не подвергайте этот продукт
Raspberry Pi 3 Model A+/ B+ 用国内の規制や基準に準拠したものにし、 • Nie należy przenosić produktu, gdy jest воздействию воды или влаги и не
IMPORTANTE: CONSERVARE QUESTE 該当する表記のあるものにしてください。 podłączony do zasilania. Trzymać wyłącznie размещайте его на проводящей
INFORMAZIONI PER RIFERIMENTO FUTURO. すべての順守証明書および番号については za krawędzie, aby zminimalizować поверхности во время работы.
www.raspberrypi.org/compliance を参照して ryzyko uszkodzenia w wyniku wyładowań • Не подвергайте этот продукт
Avvisi ください elektrostatycznych. воздействию тепла из любого источника;
• Tutti gli alimentatori esterni utilizzati con • Wszelkie urządzenia peryferyjne lub он предназначен для надежной работы
il Raspberry Pi devono essere conformi sprzęt używany z Raspberry Pi powinny при нормальной комнатной температуре.
• Эксплуатируйте этот продукт в хорошо Svenska type equipment, operates at a maximum e.i.r.p. • Connect the equipment into an outlet on a
проветриваемой среде и не накрывайте of 23dBm (5150-5350MHz) and 30dBm (5450- different circuit from that to which the receiver
его во время использования. Raspberry Pi 3 Modell A+/ B + 5725MHz). is connected • Consult the dealer or an
• Поместите этот продукт на устойчивую, VIKTIGT: BEHÅLL DENNA INFORMATION FÖR experienced radio/TV technician for help. For
плоскую, непроводящую поверхность во FRAMTIDA REFERENS. In accordance with Article 10.10 of the Radio product available in the USA/Canada market,
время использования и не позволяйте Equipment Directive, and as per below list only channel 1~11 can be operated and these
ему контактировать с проводящими Varningar of country codes, the operating bands 5150- channel assignments deal with only the 2.4GHz
изделиями. • Alla externa strömförsörjningar som 5350MHz are strictly for indoor usage only. range This device and its antenna(s) must
• Соблюдайте осторожность при används med Raspberry Pi måste uppfylla not be co-located or operation in conjunction
обращении с этим продуктом, alla tillämpliga regler och standarder i det with any other antenna or transmitter except
land där de används. Strömförsörjningen
BE BG CZ DK
чтобы избежать механического или in accordance with FCC’s multi-transmitter
электрического повреждения печатной måste tillhandahålla 5 VDC och ha en lägsta procedures. This device is going to be operated
DE EE IE EL
платы и разъемов. märkström på 2,5 A. in 5.15~5.25GHz frequency range, it is restricted
• Избегайте обращения с этим продуктом Instruktioner för säker användning in indoor environment only
ES FR HR IT CY
во время его питания. Используйте • Produkten bör inte överklockas. IMPORTANT NOTE: FCC Radiation Exposure
только края, чтобы свести к минимуму • Utsätt inte produkten för vatten eller fukt, och Statement; This appliance and its antenna must
LV LT LU HU MT
риск повреждения электростатического placera den inte på en ledande yta medan not be co-located or operation in conjunction
разряда. den är i drift. NL AT PL PT RO with any other antenna or transmitter. A
• Любое периферийное устройство • Utsätt inte produkten för värme från någon minimum separation distance of 20cm must be
или оборудование, используемое с värmekälla. Den är utformad för tillförlitlig SI SK FI SE UK maintained between the antenna and the person
Raspberry Pi, должно соответствовать drift vid normal rumstemperatur. for this appliance to satisfy the RF exposure
соответствующим стандартам • Använd produkten i en väl ventilerad miljö, requirements. This raspberry Pi product is
для страны использования и быть och täck inte över den vid användning. The Raspberry Pi complies with the relevant certified for usage as a Single Module under
соответствующим образом маркировано • Placera produkten på en stabil, isolerad yta provisions of the RoHS Directive for the the requirements of 15.212. The integration of
для обеспечения соблюдения требований vid användning, och låt den inte komma i European Union. this module into end products is subject to the
безопасности и производительности. kontakt med ledande föremål. following requirements:
Для всех сертификатов соответствия и • Var försiktig när du hanterar produkten för att WEEE Directive Statement for the European USER MANUAL OF THE END PRODUCT:
номеров, пожалуйста, посетите www. undvika mekaniska eller elektriska skador på Union In the user’s manual of the end of product, the
raspberrypi.org/compliance . kretskortet och kontakterna. This marking indicates that this product end user has to be informed:
• Undvik att hantera produkten med strömmen should not be disposed with other household • To keep at least 20cm separation with the
Español på. Håll den endast i kanterna för att undvika wastes throughout the EU. To prevent possible antenna while this end product is installed
elektrostatiska urladdningar. harm to the environment or human health and operated.
Raspberry Pi 3 Modelo A+/ B + • Eventuell kringutrustning och utrustning from uncontrolled waste disposal, recycle it • That the FCC radio-frequency exposure
IMPORTANTE: POR FAVOR CONSERVE ESTA som används med Raspberry Pi måste responsibly to promote the sustainable reuse of guidelines for an uncontrolled environment
INFORMACIÓN PARA FUTURA REFERENCIA. uppfylla relevanta standarder i det land där material resources. To return your used device, can be satisfied.
den används, och den bör märkas så att please use the return and collection systems • That any changes or modifications not
Advertencias säkerhets- och prestandakraven uppfylls. or contact the retailer where the product was expressly approved by the manufacturer
• Cualquier fuente de alimentación externa Besök www.raspberrypi.org/compliance, för alla purchased. They can take this product for could void the user’s authority to operate this
utilizada con la Raspberry Pi deberá cumplir certifikat och nummer om överensstämmelse. environmental safe recycling. Note: A full online equipment.
con las correspondientes regulaciones y copy of this Declaration can be found at www. • That, if the size of the end product is smaller
normas aplicables en el país de uso previsto. raspberrypi.org/compliance/ than 8x10cm, then additional FCC part15.19
La fuente de alimentación debe proporcionar EU statement is required to be available in the
5V DC y una corriente nominal mínima de Radio Equipment Directive (2014/53/EU) China user’s manual; This device complies with
2.5A. Declaration of Conformity (DoC) Raspberry Pi 3 Model B+ CMIIT ID: 2018AJ2147 Part 15 of FCC Rules, Operation is Subject
Instrucciones para un uso seguro to following two conditions: (1) This device
• Este producto no debe ser usado con una We, Raspberry Pi (Trading) Limited, 30 Station FCC may not cause harmful interference, and (2)
frecuencia de reloj superior a la nominal. (No Road, Cambridge, CB1 2JH, United Kingdom, This device must accept any interference
se debe overclockear). Declare under our sole responsibility that the Raspberry Pi 3 Model B+ FCC ID: 2ABCB-RPI3BP received including interference that cause
• No exponga este producto al agua o a product: Raspberry Pi 3 Model B+ to which Model A+ FCC ID:2ABCB-RPI3AP undesired operation. Caution: Any changes
la humedad, y no lo coloque sobre una this declaration relates is in conformity with or modifications to the equipment not
superficie conductora mientras está en the essential requirements and other relevant This device complies with Part 15 of FCC Rules, expressly approved by the party responsible
funcionamiento. requirements of the Radio Equipment Directive Operation is Subject to following two conditions: for compliance could void user's authority to
• No exponga este producto a ningún tipo (2014/53/EU). (1) This device may not cause harmful operate the equipment.
de fuente de calor; está diseñado para interference, and (2) This device must accept
un funcionamiento fiable a temperatura The product is in conformity with the following any interference received including interference
ambiente normal. standards and/or other normative documents: that cause undesired operation. Caution: Any LABEL OF THE END PRODUCT:
• Utilice este producto en un ambiente bien changes or modifications to the equipment not The final end product must be labelled in a
ventilado, y no lo cubra durante el uso. SAFETY (art 3.1.a): IEC 60950-1: 2005 (2nd expressly approved by the party responsible visible area with the following " Contains TX
• Coloque este producto sobre una superficie Edition) and EN 62311: 2008 EMC (art 3.1.b): EN for compliance could void user s authority to FCC ID: 2ABCB-RPI3A/BP". If the size of the end
estable, plana y no conductora mientras esté 301 489-1/ EN 301 489-17 Ver. 3.1.1 (assessed operate the equipment. This equipment has been product is larger than 8x10cm, then the following
en uso, y no permita que entre en contacto in conjunction with ITE standards EN 55032 and tested and found to comply within the limits FCC part 15.19 statement has to also be
con elementos conductores. EN 55024 as Class B equipment) SPECTRUM for a Class B digital device, pursuant to part 15 available on the label: This device complies with
• Tenga cuidado al manipular este producto (art 3. 2): EN 300 328 Ver 2.1.1, EN 301 893 of the FCC Rules. These limits are designed to Part 15 of FCC rules. Operation is subject to the
para evitar daños mecánicos o eléctricos V2.1.0 provide reasonable protection against harmful following two conditions: (1) this device may not
en la placa de circuito impreso y en los interference in a residential installation. This cause harmful interference and (2) this device
conectores. In accordance with Article 10.8 of the Radio equipment generates, uses, and can radiate radio must accept any interference received, including
• Evite manipular este producto mientras está Equipment Directive: The device ‘Raspberry frequency energy and, if not installed and used interference that may cause undesired operation.
encendido. Sujételo solo por los bordes para Pi 3 Model B+’ operates in compliance with in accordance with the instructions, may cause
minimizar el riesgo de daños por descargas harmonised standard EN 300 328 v2.1.1 and harmful interference to radio communications. ISED
electrostáticas. transceives within the frequency band 2,400 However, there is no guarantee that interference
• Cualquier periférico o equipo utilizado con la MHz to 2,483.5 MHz and, as per Clause 4.3.2.2 will not occur in a particular installation. If this Raspberry Pi 3 Model B+ IC: 20953-RPI3P
Raspberry Pi debe cumplir con las normas for wideband modulation type equipment, equipment does cause harmful interference Raspberry Pi 3 Model A+ IC:20953-RPI3A
aplicables en el país de uso y debe estar operates at a maximum e.i.r.p. of 20dBm. to radio or television reception, which can be This device complies with Industry Canada
marcado en consecuencia para garantizar The device ‘Raspberry Pi 3 Model B+’ also determined by turning the equipment off and license-exempt RSS standard(s). Operation is
que se cumplen los requisitos de seguridad operates in compliance with harmonised on, the user is encouraged to try to correct the subject to the following two conditions: (1) this
y rendimiento. standard EN 301 893 V2.1.1 and transceives interference by one or more of the following device may not cause interference, and (2) this
Para obtener todos los certificados de within the frequency bands 5150-5250MHz, measures: • Reorient or relocate the receiving device must accept any interference, including
conformidad y sus números de registro, visite 5250-5350MHz, and 5470-5725MHz and, as antenna • Increase the separation between the interference that may cause undesired operation
www.raspberrypi.org/compliance. per Clause 4.2.3.2 for wideband modulation equipment and receiver of the device.
SUBSCRIBE TODAY
FROM ONLY £5
Subscriber Benefits
FREE Delivery
Get it fast and for FREE
Exclusive Offers
Great gifts, offers, and discounts
Great Savings
Save up to 35% compared to stores
FREE Raspberry Pi
Zero W Starter Kit
WITH YOUR SUBSCRIPTION
Subscribe in print
for 12 months today
and you’ll receive:
Raspberry Pi Zero W
Raspberry Pi
Zero W case with
three covers
USB and HDMI
converter cables
Camera Module
connector
Offer subject to change or
withdrawal at any time
SUBSCRIBE
on app stores
GET
STARTED
WITH RASPBERRY PI
The world’s favourite single-board computer, Raspberry Pi is packed with
potential: it can be a digital camera, a programmable games machine,
or even a sensor for the International Space Station. While creating a
Raspberry Pi project, you’ll learn computing, coding, and electronics.
It’s fun, and creative, and it’s changing the world.
magpi.cc
Not to be sold separately