You are on page 1of 128

Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Creative Commons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

The Maker Movement in Education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

Chapter 1 - A Very Brief History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2 - Where to Start? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Raspberry Pi as a Desktop Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Anatomy of the Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Accessories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Purchasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 3 - Setting Up the Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11


Network/internet access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Minimum Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Setting Up Your Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Now What? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Chapter 4 - Command-line with the Terminal . . . . . . . . . . . . . . . . . . . . . . . . . 18


Terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Linux/Raspbian Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Conquer the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Chapter 5 - Coding with the Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . 22


Computational Thinking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Programming Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Chapter 6 - Beginner Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39


Standards, Curriculum, Objectives … Oh My! . . . . . . . . . . . . . . . . . . . . . . . . 39
Project #1 - Sweet Shop Reaction Game . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Project #2 - Burping Jelly Baby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Chapter 7 - Physical Computing with Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . 50


CONTENTS

What is Physical Computing? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50


Physical Computing w/ Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Physical Computing w/ Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Chapter 8 - Minecraft: Pi Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77


Project # 1 - Getting Started with Minecraft Pi . . . . . . . . . . . . . . . . . . . . . . . . 77
Project # 2 - Whac-a-Block Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Chapter 9 - Curriculum Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100


A Model for Maker Education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Constructionism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
From Theory to Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Instructional Design Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Classroom Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Chapter 10 - Going Further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107


Internet of Things (IoT) - Connect the Raspberry Pi to the World! . . . . . . . . . . . . . 107
Google Coder - A simple way to make “web stuff” on Raspberry Pi . . . . . . . . . . . . 109
PiNet - Centralized user accounts and file storage for the classroom . . . . . . . . . . . . 110
Resources to Explore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Closing Thoughts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Appendix A - Headless Mode via SSH and VNC . . . . . . . . . . . . . . . . . . . . . . . . 112

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Introduction
Hello and welcome to Build, Think, and Create with Raspberry Pi in the Classroom! I presume you
found this book because you are interested in learning more about the Raspberry Pi and its uses in
learning environments. That’s great! The Raspberry Pi was designed to encourage new learners to
tinker, play, and make with technology. The founder of the Raspberry Pi, Eben Upton, wanted to
rekindle the past when the curious could pick up a computer and make something with it. Today,
consumer technologies often hide this capability from the user. The Raspberry Pi is different. It
provides a platform for new learners to create hundreds of hardware and software projects.
This book is designed for complete newbies (new users)! The approach is this: You are an educator.
You know how to teach students. You know most students learn best when they are mentally and
physically active, constructing knowledge as they work. You want to introduce your students to new
and interesting technologies, but you are not sure where to start. Many educators have purchased
a Raspberry Pi, opened the box, and are confused on what to do next. The honest truth is there are
a vast of amount of resources available online (mostly free) for you to dive into and explore. The
reality, however, is that as an educator this might not be the best option for you. I suspect you want
to know just enough to get your students started and let them teach you! If that is the case, you are
most certainly in the right place. My goal is to give you a good foundation from which to start from,
then let you (and your students) discover more from there.
The activities found in this book are geared toward educators working with learners ages 12 to 15.
That said, precocious younger learners can certainly accomplish the activities with guidance. Older
learners (of all ages!) should find value, as well.
The educational benefits of using the Raspberry Pi are numerous. I am confident you will discover
them as you read this book. We start with a brief history of the Raspberry Pi. We then explore some
basic beginner projects with step-by-step instructions written from the perspective of a classroom
educator. Finally, we learn and explore more advanced projects perfect for project-based instruction
and learning.
I hope you find joy in learning with the Raspberry Pi. It is a remarkable little device. I envy you. You
are now going to experience the thrill of making something new for the first time with a Raspberry
Pi computer. Enjoy the journey!
Cheers!
Michael C. Renne
@mr_renne
www.mikerenne.com
Creative Commons
The Raspberry Pi Foundation, the creators of the Raspberry Pi, make available a large amount of
Creative Commons-licensed educational material on their website. In this book you will find several
examples of projects sourced directly from the Foundation. Their requirement is that you must use
the same license when using their material. I have done just that. This book is licensed [CC BY-
SA 4.0] (http://creativecommons.org/licenses/by-sa/4.0/). When using their work, I have provided a
direct link to the source material.

According to their website, Creative Commons is a nonprofit organization that works to


increase the amount of creativity (cultural, educational, and scientific content) available in
“the commons” — the body of work that is available to the public for free and legal sharing,
use, repurposing, and remixing.¹

Raspberry Pi is a trademark of the Raspberry Pi Foundation


CC BY-SA 4.0 Material:

• Raspberry Pi Foundation Raspberry Pi Learning Resources


• Richard Hayler CodeClub and Coderdojo Ham Resources (UK)

¹http://wiki.creativecommons.org/images/3/35/Creativecommons-what-is-creative-commons_eng.pdf
The Maker Movement in Education
The Raspberry Pi computer is an amazing tool to help students become “makers”. You may have
heard of the “maker movement” and its gaining popularity in schools. Put simply, a maker is someone
who uses their head, hands, and heart to create something meaningful. This something could be as
simple as a traditional art project to a product as complex and esoteric as a heat-sensing, motion-
controlled cat food dispenser! The product really does not matter. What does matter is the process
the participant goes through to make the product (or a prototype of a product) and the thinking,
problem-sovling, and resilience needed to be successful. The maker movement aims to tap into young
people’s natural inclination to use their head, hands, and heart to learn, while embracing the idea
of “learning by doing”.
The educational underpinnings influencing the maker movement can be found in two similar
sounding theories of learning - constructivism and constructionism. Constructivism is the idea
that a learner constructs knowledge, individually and socially, through the process of making
connections between prior knowledge and new ideas. It’s primary focus is on how a learner forms
new “models” of information in their head.² Constructionism is an extension of this idea with
a focus on the physical world. It states learning is a student-centered process where the learner
obtains new knowledge by building physical models in the real world and using those objects to
make connections with prior knowledge. This is often accomplished through a tangible product, i.e
a computer, a scale model, or a piece of artwork.³
The Raspberry Pi computer is a perfect fit for the maker movement and its associated learning
theories. It is accessible to young learners, while still providing enough challenge to embrace learners
at all levels. It encourages the construction of both mental and physical models, namely through
computer programming/coding and the construction of electronic circuits. Furthermore, rather than
hiding away the details and discouraging exploration as found in traditional desktop/laptop/tablet/s-
martphone computers, the designers of the Raspberry Pi computer chose to present the user with
an exposed, single board computer where the complexity is demystified, the learner is encouraged
to figure out how the system works, and experimenting with the electronics of the computer is not
only permitted, but is intentional designed to be accessible to curious learners.
To learn more about the maker movement and its impact on education visit:
MakerEd
Invent to Learn
FabLearn Labs
Makerspace For Education
²http://www.exploratorium.edu/education/ifi/constructivist-learning
³http://tltl.stanford.edu/content/seymour-papert-s-legacy-thinking-about-learning-and-learning-about-thinking
Chapter 1 - A Very Brief History
“Making is a universal language especially for learning and discovery.”
–Dale Dougherty

Before we begin to build, think, and create with the Raspberry Pi, I think it is healthy to look back
at the brief (as of mid 2016), yet impactful history of this tiny device. The Raspberry Pi computer
was released in the UK by the Raspberry Pi Foundation in February 2012.⁴ The original intention
of the device was to inspire young people to discover how a computer worked inside and out -
both from a hardware and software perspective. Eben Upton, the creator of the Raspberry Pi, was
concerned youth were only learning rudimentary computer skills (word processing, presentation
software, etc.) in school computing courses rather than gaining an understanding of the relationship
between writing computer software and its interaction with computer hardware.⁵.

According to their website, the Raspberry Pi Foundation works to put the power of digital making
into the hands of people all over the world, so they are capable of understanding and shaping our
increasingly digital world, able to solve the problems that matter to them, and are equipped for the
jobs of the future.
http://www.raspberrypi.org/about/

Mr. Upton, who at the time was assisting with college admissions at the University of Cambridge,
noticed most students enrolling in technical university programs had little, if any, computer
programming experience before entering university. This was concerning to him. Upton was
inspired by early personal computers designed to be modified or “hacked”, such as the BBC Micro⁶.
Introduced in the 1980s in the UK, the BBC Micro computer did not have a graphical user interface
(GUI), rather the learners had to learn the relationship between the software, through computer
code, and the hardware in order to get the machine to operate according to the their needs.⁷ Modern
computers, tablets, and smartphones intentionally hide this relationship from the user, making them
not great tools to teach higher-level computing skills. Eventually, Upton worked with colleagues at
Broadcom Corporation - where he is a microprocessor chip engineer - to start the Raspberry Pi
Foundation and the $35 credit card-sized computer was born.⁸
⁴http://www.bbc.com/news/technology-17190918
⁵http://www.theguardian.com/education/2012/jan/09/raspberry-pi-computer-revolutionise-computing-schools?newsfeed=true
⁶http://spectrum.ieee.org/geek-life/profiles/eben-upton-the-raspberry-pi-pioneer/
⁷http://www.penguintutor.com/linux/raspberrypi
⁸http://www.zdnet.com/article/we-thought-wed-sell-1000-the-inside-story-of-the-raspberry-pi/
Chapter 1 - A Very Brief History 2

Although the Raspberry Pi computer was originally intended to spark an interest in creative
computing amongst young people, the device quickly began attracting a much broader audience
upon release. Computer hobbyists found the Raspberry Pi to be a perfect platform for many of
their DIY computer projects.⁹ Why spend hundreds of dollars on a laptop or smartphone when the
Raspberry Pi has more than enough computational power for most hobby projects, and costs only
$35?
Today, the Raspberry Pi Foundation produces several models of the Raspberry Pi computer. As of
September 2016, the Foundation has sold more than ten million units, making it the all-time best
selling computer in the UK. ¹⁰
⁹http://www.pcworld.com/article/2020572/raspberry-pi-model-b-review-a-tasty-confection-for-hobbyists-and-budding-programmers.html
¹⁰http://www.raspberrypi.org/blog/ten-millionth-raspberry-pi-new-kit/
Chapter 2 - Where to Start?
“Schools have a responsibility to expose kids to things they don’t yet know they love.”
–Gary Stager

You are probably thinking - where do I start? It may be a little intimidating when you look online
for information about the Raspberry Pi or when you purchase one, open the box, and realize there is
not much direction on what to do next. We will explore some basic information about the Raspberry
Pi before we jump in and start creating with it. It is important to know what models are available,
what accessories may be of use to you and your students in the classroom, and where to purchase
these items.

Raspberry Pi as a Desktop Computer


Before we begin, a quick note - The Raspberry Pi can be used as a traditional desktop computer, but
its real educational value lies in its abilities to be hacked and tinkered with. Remember the device
is only $35 and you can expect $35 worth of performance. The Raspberry Pi 2 B and Raspberry Pi 3
B are fast enough to be used as a traditional computer without much frustration. The other models
will be VERY slow and often frustrating to use as a desktop computer.
Another option is to use the Raspberry Pi is in what is called “headless” mode. This simply means
you operate the computer without a monitor/display, mouse, or keyboard directly connected. You
connect to the Raspberry Pi computer via a network through technologies called SSH and VNC. See
Appendix A for details - note this does require a network/internet connection.

Models
The Raspberry Pi computer comes in several models. As of September 2016¹¹, the following variants
are available:

• Raspberry Pi 1 A+
• Raspberry Pi 1 B
• Raspberry Pi 1 B+
• Raspberry Pi 2 B
• Raspberry Pi 3 B
¹¹http://www.raspberrypi.org/products/
Chapter 2 - Where to Start? 4

• Raspberry Pi Zero

While each of these models have their own advantages/disadvantages this book will focus on the
Raspberry Pi 2 B or Raspberry Pi 3 B. Either one of these models generally costs $35, by itself, and
will be sufficient for the classroom. The Raspberry Pi 3 B has the advantage of built-in WiFi and
Bluetooth (i.e. you do not have to purchase a separate WiFi dongle), so if they are the same price
when you go to purchase, pick up the Raspberry Pi 3 B! The other models are either older (and thus
often sold for a lower price) or are purpose-built for specific applications. In a classroom environment
we want to ensure maximum compatibility. The Raspberry Pi 2 B or Raspberry Pi 3 B will do just
that.

Anatomy of the Raspberry Pi


!(images/pi2_labels.png)
The Raspberry Pi is a single-board computer. All components are surface-mounted. That means they
are attached to one circuit board.

The Raspberry Pi computer is very vulnerable to static electricity. It comes to you in an


anti-static bag and should be stored in one, unless you purchase a case. If the board gets a
static charge, it could be permanently damage it.

HDMI Connector
The Raspberry Pi computer requires an HDMI monitor/display (older models allowed for RCA-style
television connector). If you do not have a HDMI monitor/display, you can purchase an inexpensive
adapter that converts the older style monitor connector (VGA) to HDMI.

Micro USB Power Connector


You power the Raspberry Pi via the micro USB connector. A standard mobile phone charger should
be sufficient for the Raspberry Pi 2 B or lower models. If you are using a Raspberry Pi 3 B, you will
Chapter 2 - Where to Start? 5

need at least a 5V, 2.5mA power supply. A typical mobile charger generally does not output this
amount of power. Notice there is no On/Off switch on the Raspberry Pi. Plugging in the micro USB
power connector = turning on the Raspberry Pi computer! You shut down the Raspberry Pi using
the Shutdown command via the computer menu system.

Memory Card Slot


The Raspberry Pi computer uses a Micro SD card for storage/hard drive. You will need a 4GB
(minimum) Micro SD card. This is one of the great educational features of the Raspberry Pi. Students
can experiment with different operating systems on the Raspberry Pi simply by swapping out SD
cards!

Micro SD Card

General Purpose Input/Output Pins (GPIO)


Arguably, the best feature for educational use. GPIO pins allow you to add electronics, LEDs,
sensors, and other devices to your Raspberry Pi. This allows for almost limitless creative projects!

GPIO

Sound Out
Plug in headphones, ear buds, or a powered speaker. If your HDMI monitor/display has speakers,
you can use HDMI for sound output, as well.
Chapter 2 - Where to Start? 6

Processor
The “brain” of the computer. The Raspberry Pi uses a Broadcom SOC (system-on-a-chip).

A system on a chip or system on chip (SoC or SOC) is an integrated circuit (IC) that
integrates all components of a computer or other electronic system into a single chip.¹²

USB Ports
Plug in wired/wireless mouse and keyboard here. You can also plug in many standard USB devices -
printer, USB key/flashdrive, USB headset, gamepad, etc. Not all USB devices will work properly on
a Raspberry Pi. Check with the peripheral manufacturer for compatibility with the Raspberry Pi.

Accessories
On its own, the Raspberry Pi computer is a great device for digital building and creating, but there
are several extras for purchase that can make your classroom projects even better.

Case

As previously mentioned, having a case is a good idea. A case protects your device from electric
shock/charge. There are clear, as well as many designed, cases available. Cases generally cost $5 to
$15.

You can also 3D print Raspberry Pi cases. If you have access to a 3D printer, visit Thingiverse
and search for Raspberry Pi cases to print. Better yet - make your own!

¹²http://en.wikipedia.org/wiki/System_on_a_chip
Chapter 2 - Where to Start? 7

Camera Module

The Raspberry Pi camera module can be used to take high-definition video, as well as still
photography. It’s easy to use for beginners, but has plenty to offer advanced users if you’re looking
to expand your knowledge. It costs $25.

Sense Hat

The Sense HAT is an add-on board for Raspberry Pi. It was designed for the Astro-Pi project that
went to the International Space Station in December 2015. It contains 8×8 RGB LED matrix, a five-
button joystick and includes the following sensors:
*Gyroscope
*Accelerometer
Chapter 2 - Where to Start? 8

*Magnetometer
*Temperature
*Barometric pressure
*Humidity
The Sense Hat is a “must-have” for the classroom. It makes collecting, processing, and analyzing data
very accessible. Students can easily setup a weather sensing station in an hour using the Raspberry
Pi and the Sense Hat. More about this project can be found in Chapter 9 - Curriculum Connections.
The Sense Hat costs $40.

In December 2015, British ESA Astronaut Tim Peake blasted off to the International Space Station
for Mission Principia with two Raspberry Pi computers containing a Sense Hat to gather data. As
part of his mission, he ran experiments which utilised the board’s sensors, created and coded by
school students.
http://astro-pi.org/about/

Touchscreen

The 7″ Touchscreen Monitor for Raspberry Pi gives makers the ability to create all-in-one, integrated
projects such as tablets, infotainment systems and embedded projects.
Chapter 2 - Where to Start? 9

With the Touchscreen you make your own Internet of Things (IoT) devices including a
visual display. Simply connect your Raspberry Pi, develop a Python script to interact with
the display, and you’re ready to create your own home automation devices with touch
screen capability. Really cool!!! The Touchscreen costs T> $60.

Purchasing
There are several places to purchase the Raspberry Pi computer. While Amazon often offers the best
in terms of price and convenience, I prefer Adafruit.com. They are a US-based company (Brooklyn,
NYC) and in my opinion offer the best mix of exceptional customer service with a wide variety of
purchasing options. They provide educator and bulk discounts, purchase ordering, and a plethora of
tutorials designed for beginners. They have not paid me for this endorsement, I just genuinely like
what they have to offer.
The standard Raspberry Pi computer costs $35 by itself, but you are going to need more than just
the computer itself for effective use in the classroom. The computer comes shipped in a tiny box
with little else - no cables, no SD card, and only minimal instructions. You can purchase Raspberry
Pi computer kits (complete with from SD card, USB power chord, etc.) from Adafruit.com or other
vendors. Buying a pre-packaged kit of is often the best place to start. Below are a few I find great
for classroom use:

Official Raspberry Pi Starter Kit (from Raspberry Pi Foundation)


www.raspberrypi.org/blog/ten-millionth-raspberry-pi-new-kit/

This is an unashamedly premium product: the latest Raspberry Pi, official accessories, the best USB
peripherals around, and a copy of the highest-rated Raspberry Pi book. The kit is available to order
online in the UK from element14 and RS Components, priced at £99+VAT. It will be coming to the
rest of the world in late 2016.

Raspberry Pi 3 Model B Starter Pack


www.adafruit.com/products/3058

This kit comes with a Raspberry Pi 3 and LOTS of extra electronics components. It also includes a
power supply and SD card pre-installed with the NOOBS operating system.

Raspberry Pi Projects Kit by Science Buddies


store.sciencebuddies.org/SPF-6000-KIT/raspberry-pi-projects-kit.aspx
Chapter 2 - Where to Start? 10

For students who love to create games, artwork, or music, Science Buddies has put together a kit
that allows all of these things with a modern twist: interactivity! The Science Buddies Raspberry Pi
Projects Kit teaches students basic programming and electronics skills so that they can use sensors,
sounds, images, and lights to create interactive projects.

Kano Computer Kit


kano.me

The Kano Computer Kit is an all-in-one (minus a monitor/display) Raspberry Pi kit aimed at helping
young learners understand computer hardware and software. The kit comes with a Raspberry Pi 3
B, a small keyboard with trackpad, a reloaded SD card, and all necessary cables. Their version of
the operating system - Kano OS - is the best part of this kit. It is designed for young students to get
them started making with the Raspberry Pi straight away. Kano’s mission is to give people a simple,
fun way to create with technology, and take control of the world around them.

CanaKit Raspberry Pi 3 Complete Starter Kit


Amazon.com

An exclusive Starter Kit from CanaKit that includes the Raspberry Pi 3 Model B and everything you
need to get up and running within minutes in the exciting world of Raspberry Pi! Also included in
this Raspberry Pi 3 Starter Kit is a high quality Raspberry Pi 3 case as well as the recommended
Raspberry Pi 32 GB Class 10 MicroSD Card pre-loaded with NOOBS. Just Plug and Play! The kit
also includes a CanaKit 2.5A Micro USB power supply (UL Listed) specially designed and tested for
the Raspberry Pi 3.

pi-top and pi-topCEED


pi-top.com

If you are interested in using the Raspberry Pi as a desktop/laptop computer, check out the pi-top
and pi-topCEED. These are pre-assembled devices, with a built-in monitor, for your Raspberry Pi.
Both devices allow for multiple-viewing angles and hardware expansion. You still need to provide
your own mouse and keyboard, but this is a nice option for those without an available monitor for
their Raspberry Pi and/or for those looking for a compact solution.
Chapter 3 - Setting Up the Raspberry Pi
“Don’t worry about what anybody else is going to do! The best way to predict the future is to invent
it. Really smart people with reasonable funding can do just about anything that doesn’t violate too
many of Newton’s Laws!”
–Alan Kay

Raspberry Pi 3 B

When students first see a Raspberry Pi computer they are often curious because it looks different and
enticing. This is your teachable moment. They may ask: How is this is a computer? Is this similar to
a smartphone or tablet? Where is the hard drive? How do you plug it in? I have found it is through
these questions that students begin to want to learn more about the device. The Raspberry Pi ethos
encourages tinkering and it is through this exploration, problem-solving, and the making of mistakes
where students learn best.
A question you may have straight away is: How many Raspberry Pi computers do I need for effective
teaching and learning in the classroom? The best answer is: As many as you can afford! A more
practical answer is: two/three students per Raspberry Pi computer seems to work best.
Before you unleash your students unto the power of the Raspberry Pi computer, you should dive in
first yourself! Gather all the necessary cables and accessories before plugging the Raspberry Pi in
and get ready to log-in for the first time.
Chapter 3 - Setting Up the Raspberry Pi 12

Network/internet access
This book will focus on using the Raspberry Pi as a standalone device outside the school network.
This allows you and your students to write programs and make electronic projects without the fear
of harming school-owned devices and/or the school network. As such, I will not be detailing how to
connect your Raspberry Pi to a network/internet via WiFi. There is obviously tremendous value in
having your Raspberry Pi connected to a network and the internet. There are far too many school
network variations for me to address them all here. I would encourage you to talk to your school or
district IT staff before purchasing a Raspberry Pi to see if they can assist you in connecting it to the
school network. If they can/will not, do not worry. There are plenty of projects your students can
complete without network/internet connectivity. Most projects in this book do not require an active
network/internet connection. If they do, it will be clearly noted.

Minimum Requirements
At a minimum, in order to use the Raspberry Pi computer in the classroom you will need the
following:

• A Raspberry Pi computer (any model will work, but Raspberry Pi 2 B or Raspberry Pi 3 B are
recommended)
• SD card (4 GB or higher - 8GB is recommended)
• Power supply (for Raspberry Pi 3 B you will need a 5V 2.5mA power supply)
• A monitor/display (HDMI or VGA w/ adapter)
• Monitor cable (HDMI or VGA w/ adapter)
• A keyboard (USB or wireless)
• A mouse (USB or wireless)
• Internet connection for Windows or Apple computer to download the Raspberry Pi operating
system

There are ways to connect to the Raspberry Pi via another Windows, Mac or Chromebook
computer (called “headless mode”) so that you can use the monitor/display, mouse,
and keyboard of the host machine in lieu of separate peripherals. This is an advanced
topic and will be covered in Appendix A. T> This setup may be better suited for many
classroom/computer lab environments. It will most likely involve T> the assistance of your
school/district IT staff because it involves connecting to the school network.
Chapter 3 - Setting Up the Raspberry Pi 13

Setting Up Your Raspberry Pi


Prepare the SD card
Video Tutorial from the Raspberry Pi Foundation

1. You will need a Windows or Apple computer with an SD card reader to setup the Raspberry
Pi operating system. Go to Raspberry Pi Downloads and download NOOBS (New Out of the
Box Software). NOOBS is an easy operating system installer which contains Raspbian - the
official operating system developed for the Raspberry Pi. NOOBS also provides a selection of
alternative operating systems which are then downloaded from the internet and installed.

If you want to skip this step, you can purchase a pre-installed NOOBS SD card from many online
retailers, such as Amazon, Adafruit or Sparkfun.

In September 2016 the Raspberry Pi Foundation released an updated version of their


Raspbian operating system called PIXEL. This update includes many desktop appearance
improvements as well as updated software, including a switch to the default web browser,
Chromium, and updates to the VNC viewer.

1. Click on the Download Zip button under NOOBS and select a destination folder to save
extracted files
2. Extract the files from the zip
3. Download SD Formatter 4.0
4. Follow the instructions to install the software
5. Insert your SD card into the computer’s SD card reader and make a note of the drive letter
allocated to it, e.g. G:/
6. In SD Formatter, select the drive letter for your SD card and format it.
7. Once the SD card is formatted, drag-and-drop all the files from the extracted zip folder onto
the drive letter of the SD card
8. When this process has finished, safely remove the SD card and insert it into your Raspberry
Pi. This may take several minutes … be patient and do not eject card until ALL files have been
copied to the SD card
Chapter 3 - Setting Up the Raspberry Pi 14

Another option for advanced users is Pi Bakery. The key feature of PiBakery is the ability to create
a customized version of Raspbian that you write directly to your Raspberry Pi. This works by
creating a set of scripts that run when the Raspberry Pi has been powered on, A> meaning that
your Pi can automatically perform setup tasks, and you don’t need to configure anything.

First Boot

1. Plug in your keyboard, mouse, and monitor cables.


2. Now plug the USB power cable into your Pi. Note - You MUST plug in the monitor cable
before you power on the Raspberry Pi.
3. The Raspberry Pi will now boot and you will see lots of text scroll by. This is the computer
preparing itself for use. At the first screen, select Raspbian and click Install.
4. Once the Raspbian operating system is installed (which make take a while) the Raspberry Pi
configuration will begin.
5. You can now setup the time, date, and other more advanced options.
6. Use the Tab key to navigate to Finish.

Logging in
The Raspberry Pi computer requires a username and password to log-in. When typing in a password,
you will not see any text appear on screen. This is a security feature.
The defaults are:
Username: pi
Password: raspberry
To load the Graphical User Interface (GUI) - type: startx
You are now at your “desktop” which is similar to your Windows or Mac desktop. From here you
can launch software, program the next great app, or begin connecting peripherals to your Raspberry
Pi to extend its capabilities.

One great application you should try straight away is Minecraft: Pi Edition. This is a free,
hackable version of Minecraft designed to encourage learners to write code - often called
“modding” in Minecraft. Learn more about Minecraft: Pi Edition in Chapter 8.
Chapter 3 - Setting Up the Raspberry Pi 15

Now What?
Application Menu
Great! You booted the Raspberry Pi for the first time. Many people look at the desktop and are not
sure what to do next. I recommend looking through each application category and launch each one.
Discover what each one does, or at least, what you think it does. This is a great way to become
familiar with each application and be able to answer student questions.

Application Menu

When working with students, have them navigate, with a partner, through each appli-
cation category. They should open each application document via a journal, blog post,
VoiceThread, etc. on what they think each application does. This is a great activity to
complete once the computer has booted for the first time. It can easily be accomplished
by a young learner in under 45 minutes.

Raspberry Pi Configuration
There are a few settings you may want to change straight away. To do this you will use the Raspberry
Pi Configuration tool. Click Menu –> Preferences –> Raspberry Pi Configuration
Chapter 3 - Setting Up the Raspberry Pi 16

Password
You should change your password by clicking the Change Password button.

Configuration Screen

Localization
The Raspberry Pi is designed in the UK. As such, the default configuration uses British English and
a British keyboard layout. This can be lead to confusion because some keys are in different spots
on British English keyboards. Change the Locale, Timezone, Keyboard, and WiFi Country settings,
accordingly.
Chapter 3 - Setting Up the Raspberry Pi 17

Chapter content is derived from Raspberry Pi Foundation learning resources found at Raspberry Pi
Foundation under a Creative Commons license.
Chapter 4 - Command-line with the
Terminal
“The truth is rarely pure and never simple.”
–Oscar Wilde

The Raspberry Pi computer uses a version of the Linux operating system called Raspbian. Raspbian,
like all versions of Linux, has powerful features built into it for system administrators and/or “power
users”. This is accomplished through the Terminal application and the use of Linux (or terminal)
commands. It will be necessary for you to learn a few very basic Linux commands. You will often
find terminal commands useful to get the Raspberry Pi to do something, such as startx to show your
desktop.

“Linux, in the simplest terms, is an operating system much like Windows, macOS, or iOS. It
is the software that enables applications and the computer operator to access the devices on
the computer to perform desired functions. The operating system (OS) relays instructions
from an application to, for instance, the computer’s processor. The processor performs the
instructed task, then sends the results back to the application via the operating system.”¹³

Many computer tasks can only be completed by using the command-line. This can be a little daunting
for new Raspberry Pi users, but it is a valuable skill for young people to learn because it teaches
them a computational thinking skill - abstraction. More about computational thinking can be found
in Chapter 5. Also, it shows new users the computer is fundamentally a dumb device - it needs
instructions from the user to operate. Modern computers use graphical user interfaces (GUIs) to
accomplish the same tasks, but in a much simpler manner. Touchscreen smartphones and tablets
have purposely hidden these details away from today’s computer users.
When you type a command, it has to be exact. All the letters, numbers, or words have to be in the
correct position. This can be frustrating for new users, but eventually once you get used to typing a
few basic commands you will begin to see the power and value of having complete control over the
computer via the terminal.

Terminal
You access the command-line on a Raspberry Pi via the Terminal. You may often hear the terms used
interchangeably: command-line = terminal or terminal = command-line. This is fine. The Terminal
¹³http://www.linuxfoundation.org/what-is-linux
Chapter 4 - Command-line with the Terminal 19

is similar to the Command Prompt found on Windows computers. The Terminal can be accessed
via Menu –> Accessories –> Terminal.

Access the Terminal

Linux/Raspbian Commands
Here is a very brief list of Raspberry Pi/Linux/Raspbian commands you should know:

Command Description
pwd Displays the name of the current working directory
mkdir Makes a new directory
rmdir Remove empty directories
rm Removes the specified file (or recursively from a directory when used with -r). Be careful,
with this! Files deleted in this way are mostly gone for good!
cp Makes a copy of a file and places it at the specified location (essentially, doing a
‘copy-paste’)
ls lists the content of the current directory (or one that is specified).
cd Changes the current directory to the one specified
Chapter 4 - Command-line with the Terminal 20

More commands can be found at: Raspberry Pi Documentation

Online Tool - ShortcutFoo


Practice your command line skills with this fun online tool - ShortcutFoo
www.shortcutfoo.com/app/dojos/command-line

Practice:

1. Find the Terminal application in Menu –> Accessories.


2. You start in your Home directory which is
called “pi”. Use the pwd command to verify.

3. Make a new directory called “practice” in the “pi” directory using the mkdir
command.
4. Move to the “practice” directory using the cd command and verify with pwd.
5. Move back to your home directory - “pi” - using the cd command.
6. Remove the “practice” directory using rmdir.
7. Pat yourself on the back - you are a Linux/command line ninja. (Not really, but one
has to start somewhere!!!)
Chapter 4 - Command-line with the Terminal 21

Conquer the Command Line


If you are going to use the Raspberry Pi in the classroom you should become pretty familiar with
the command line. There are hundreds of combinations of commands you can use to accomplish
tasks quickly and efficiently. The best beginner resource I have found for learning the command
line is the “Conquer the Command Line” ebook. It is available as a free PDF download - here. You
can also purchase a hard copy of the book for a very reasonable price. I would recommend this
because it 1) will be a nice desktop reference guide for you and your students as you learn more
about the command line 2) the purchase price goes towards supporting the work of the Raspberry
Pi Foundation.
Chapter 5 - Coding with the Raspberry
Pi
“Education is not preparation for life; education is life itself.”
–John Dewey

Computer programming (sometimes called “coding”) is rapidly becoming an essential skill in our
modern digital world. In fact, a recent study found 90% of surveyed U.S. parents wanted schools
to teach computer science/computer programming.¹⁴ The unfortunate truth is most schools do not.
The reasons for this are varied. First, most schools do not have the requisite staff trained/certified to
teach computer programming as a standalone course. Second, many educators know the benefits of
coding in the classroom, but have trouble figuring out where to start. Third, there are many resources
available online to “teach” coding, but educators often feel overwhelmed knowing where and how
the topic fits within their curriculum. Since you have read this far, I assume you may fall into one
of the above categories … until now! The Raspberry Pi computer is an excellent way to introduce
coding to your students. Even if coding is not something you think will fit into your curriculum, I
can guarantee you computational thinking does.

Computational Thinking
Computational Thinking is a problem solving approach geared toward understanding and learning
in the 21st century. Computational thinking is a multi-faceted idea, but often involves skills such
as algorithm design, pattern recognition, debugging, and problem decomposition. Computational
thinking is essential to the process of computer programming, but it can also be used to support
problem solving across all subject areas including math, language arts, the humanities, science,
the arts, and health/PE. Students who learn computational thinking across the curriculum will
begin to see a relationship between their school courses, as well as connections between real-
world interactions they encounter outside of the classroom.¹⁵ One, but certainly not the only,
method of teaching computational thinking is through computer programming. Learners begin to
see how problems can be broken-down into smaller pieces. They see how patterns emerge to solve
complex problems. I strongly believe teaching computational thinking skills, over straight computer
programming/coding skills, can be extremely beneficial to a young learner’s ability to problem solve
and think critically in ALL school subjects. In fact, some have suggested computational thinking IS
the most important skill students can learn today in order to be successful for an unpredictable
future.¹⁶
¹⁴http://services.google.com/fh/files/misc/searching-for-computer-science_report.pdf
¹⁵http://computationalthinkingcourse.withgoogle.com/unit?lesson=8&unit=1
¹⁶http://www.cs4fn.org/computationalthinking/
Chapter 5 - Coding with the Raspberry Pi 23

To learn more about computational thinking for educators, check out Google’s free online course
- “Computational Thinking for Educators”.

I often hear educators acknowledge the benefits of coding but assume there is no place for it in
their curriculum. I understand that completely. I think it is quite natural since most educators may
have never coded and/or have never learned about it in their teacher preparation programs. I argue
educators do not have to have a background in coding to teach coding. In fact, educators really only
need to spend a marginal amount of time learning how to use it in the classroom. I often suggest
the Raspberry Pi as a possible solution. In particular, I think physical computing projects can be
beneficial in almost all subject areas. These projects involve building a physical object and “bringing
it to life” through computer code. Learn more about physical computing in Chapter 7.

Programming Choices
I will suggest five methods of coding using the Raspberry Pi:

1. Scratch
2. Python
3. Sonic Pi
4. Physical Computing with Scratch or Python
5. Minecraft: Pi Edition using Python

A sixth method (Web development) will briefly be detailed in Chapter 10 - Going Further.

This chapter will focus on Scratch, Python, and Sonic Pi. Chapter 7 will discuss physical computing.
Chapter 8 will show how you can control and program Minecraft: Pi Edition on the Raspberry Pi.

Scratch and Python


The best places to start coding using the Raspberry Pi computer are with Scratch and Python.
Scratch is a visual programming language with a drag-and-drop interface. It allows users to create
their own computer games, interactive stories, and animations using programming techniques
without actually having to write code. It’s a great way to get started programming on the
Raspberry Pi with young people. Once students get comfortable with Scratch, they should move
to Python. Python is professional text-based language used in many industries and by many
companies, including NASA, Google, and Facebook. The “Pi” in Raspberry Pi comes from the Python
programming language. They chose “Pi” instead of “Py” to make math geeks happy!
Chapter 5 - Coding with the Raspberry Pi 24

A programming language is a set of instructions (code) typed by the user (programmer) that
directs the computer hardware to execute a specific task. When the programmer organizes these
instructions into a logical order for the purpose of solving a problem or task, we call that
an algorithm. Algorithms are designed to solve problems. Programming languages are used to
implement algorithms. In short, a programmer creates the programs (software) that communicate
instructions to a computer.
http://www.bbc.co.uk/education/guides/zgmpr82/revision

Scratch on the Raspberry Pi


Getting Started With Scratch by the Raspberry Pi Foundation is licensed under a Creative Commons
Attribution 4.0 International License
Getting started
You’ll find Scratch in the Menu under Programming. Once opened you will see a window like this:
Chapter 5 - Coding with the Raspberry Pi 25

Make the Scratch cat move

The cat in the white preview window is an example of a sprite in Scratch. Currently the Scratch cat
sprite is on a blank stage. Let’s get the cat to move.

1. Click on the Scratch cat sprite.


2. Then click on the blocks palette and select Control.
3. Next drag a When green flag clicked block and place it on the scripts area in the middle of
the screen.
4. Add a blue Move 10 steps block from the Motion blocks palette and connect it to the When
green flag clicked block.
5. Now click the green flag icon in the top right hand side of the screen and see the cat move!
6. How would you get the cat to move further?
Chapter 5 - Coding with the Raspberry Pi 26

Changing the way the sprite looks

All sprites in Scratch can wear different costumes.

1. Click on your sprite to select it. In the Scripts area in the middle of the screen, click on the
Costumes tab.
2. You will see that the cat has two costumes. Click on Copy to make a third costume and a new
cat costume should appear.
3. Select costume3 and click on Edit. This will open the Paint Editor. Experiment with all the
buttons and tools to find out what they do.
4. Next, draw some clothes on the costume and click OK.
5. To switch between costumes, click on the Scripts tag. Add the purple Looks block, Switch to
Costume, to the other blocks and connect it.
6. Select costume3 from the drop-down menu on the purple block.
7. Now run your program to see the costume change.

Add Sprites

If you feel that the Scratch cat sprite does not suit your needs then you can add other sprites, or even
create your own!

1. At the top of the Sprites palette are three icons to create a new sprite.
2. The first allows you to Paint your own sprite. Click on this and it will open the Paint Editor
window. Here you can use shapes, lines, and freehand drawings to make fun characters.
3. The second icon allows you to Choose a new sprite from those already built into Scratch
or saved on your Raspberry Pi. Click on this, and you will be able to navigate to the folders
containing those sprites and select one you like.
4. The third icon will, when clicked, give you a surprise sprite. Click this and see what happens!
Chapter 5 - Coding with the Raspberry Pi 27

What next?
• Now you know the basics of the Scratch, why not try completing the Robot Antenna Resource
to make an LED blink.
• You could also try creating a button using candy sweets with the Sweet Shop Reaction Game

Python on the Raspberry Pi


Python is a text-based computer programming language designed to be relatively easy for new
learners to learn. We call the text (or code) we type syntax. Python is considered a high-level
programming language. High-level languages look more like English when you type them and are
often better suited to new learners. The opposite is a low-level programming language. Low-level
languages are more terse and often more difficult to learn. Computers can only execute programs
written in a low-level language. Thus, programs written in a high-level language, like Python, have
to be translated into low-level languages before they can be run.¹⁷

Python is named after the famous 1970s British television show and comedy troupe - Monty
Python’s Flying Circus. There are other homages to the famous group in Python, mainly the name
of the Python IDE - IDLE!

Just like there are many human languages, there are dozens of computer programming
languages, as well. Examples of other high-level computer programming languages include
C++, Java, C#, PHP, and Javascript. Low-level languages are often referred to as assembly
or machine code.

We will type our Python code in an application called an Integrated Development Environment (IDE).
The IDE we will use for Python is called IDLE.
Exercise 5.0 - Interactive Interpreter/Shell
¹⁷http://openbookproject.net/thinkcs/python/english3e/way_of_the_program.html
Chapter 5 - Coding with the Raspberry Pi 28

1. Click the Menu button


2. Click Programming
3. Click Python 2 (IDLE)
4. You are now in the Iteractive Interpreter. The prompt >>> on the last line indicates
that you are now in an interactive Python interpreter session, sometimes also called
the Python shell. Note - This is different from the normal terminal command
prompt!
5. Enter some code, type print(“Hello World”) and press Enter
6. Type (2+5) * 5 and press Enter
7. Type help() and press Enter to explore other options

You may have noticed two versions of Python - Python 2 and Python 3. We will use Python
2 for the exercises in this chapter. It is probably obvious Python 3 is the newer version. There
are differences, but they are not relevant here. In later chapters, we will use Python 3.

The best way to learn a text-based language is to start typing code in our IDE, run it, and observe
what it does (or does not!) do. Before you begin typing the code, I want to highlight one feature of
Python that makes it great for new learners - the Python module. See if you can identify the name
of the module in this first program. Also, there are several new terms and concepts introduced here.
It may be useful to look up the bolded words in the glossary. Ready… Let’s give it a try!

A Python module is a collection of pre-written code aimed at a particular task. In a high-level


language like Python we do not have to necessarily concern ourselves with using higher-order math
to get the computer to generate a random number. Instead, we can use code written by someone
else that simply gives us a random number. In computer programming and computational thinking
this concept is called an abstraction.

Exercise 5.1 - Fortune Teller


Chapter 5 - Coding with the Raspberry Pi 29

1. Open Python 2 (IDLE) from the Programming Menu


2. Click File –> New
3. Type the code listed in Listing 5.1
4. Save your program
5. Run the program
6. Debug (if necessary)

Listing 5.1

1 import random
2 fortunes=['Yes','Probably','Certainly','Maybe','Not sure','Ask again','Doubtful'\
3 ,'No']
4 how_many_fortunes=len(fortunes)
5 raw_input('Think of a question, press Enter for the answer')
6 which_fortune=random.randint(0,how_many_fortunes-1)
7 print fortunes[which_fortune]

How did it go? Did it work? Did you identify the Python module we used? Did you have to debug?
Debugging a program involves finding mistakes in your program, whether they are mistakes in
logic, mistakes in syntax, or mistakes while the program is running. Python is a great language for
beginners because the code is very readable. Python is a high-level language and as such you can
understand the code in Listing 5.1 without much prior knowledge. Let’s go through each line.
Line 1 - We use the import statement to load a Python module called random.
Line 2 - We setup a list of possible fortunes. We name the list “fortunes”
Line 3 - We use the len function to find how many fortunes are possible. We name this length
“how_many_fortunes”.
Line 4 - We use raw_input function to ask the user a question.
Line 5 - We have the computer randomly pick one of the possible answers from the list we setup in
line 2. We do this using the randint function from the random module.
Line 6 - We print out the fortune to the screen.
Easy, no? Just kidding. For a new coder, this can be a little daunting because of the many new
concepts and terms. One of the many benefits of coding, however; is to try and figure out what
this syntax means. In a sense, it is much like when we learn new words and concepts as a young
child. We try to use context to figure out meaning, then we consult others to “fill in the gaps”. In
lieu of having a professional programmer sitting next to you, what is one to do? Learning to code
in a new programming language involves consulting the documentation - often called the “docs”.
Chapter 5 - Coding with the Raspberry Pi 30

Even professional programmers have to consult documentation because they do not have every
concept/syntax statement memorized. The idea is to learn some basic concepts and syntax, then use
that foundational knowledge to learn more. Let’s try one more program. This one introduces a few
new concepts.
Exercise 5.2 - Guess the Number

1. Open Python 2 (IDLE) from the Programming menu


2. Type the code listed in Listing 5.2
3. Save your program
4. Run the program
5. Debug (if necessary)

Listing 5.2

1 import random
2 num = random.randint(1,100)
3 while True:
4 print('Guess a number between 1 and 100')
5 guess = input()
6 i = int(guess)
7 if i == num:
8 print("You guessed right!")
9 break
10 elif i < num:
11 print("Higher")
12 elif i > num:
13 print("Lower")

Can you follow the logic of this code? If not, do not worry. By typing, running, and thinking
about several small programs you will quickly begin to see the logic and algorithms used to create
programs. Let’s go through each line.
Line 1 - We use the import statement to load a Python module called random.
Line 2 - We ask the computer to choose a random integer between 1 and 100. An integer in Python
just means a whole number (no fractional/decimal component). We then store that number in a
variable called num.
Line 3 - We use a loop for the first time. A loop is simply a way to repeat something. Remember,
computers are REALLY good at doing things over-and-over VERY, VERY quickly. Loops are one of
Chapter 5 - Coding with the Raspberry Pi 31

the most fundamental building blocks of computer programming. In this case, we are saying repeat
the following statements as along things are “True”. Well, since we never change “True” to “False”,
we will always repeat the lines. We call this an infinite loop. Python uses this convention quite
often.
Lines 4 & 5 - We ask the user to make a guess by typing a number between 1 and 100 and then we
store that guess in a variable called “guess”.
Line 6 - We convert the user’s guess into an integer, using the int function, just in case they typed in
a number with a decimal. This is called data validation in computer programming. We then store
that converted number into a variable called “i”.

Garbage In, Garbage Out - This is a popular expression in computer programming. If our
program is given “garbage”, then we generally cannot expect to get much of anything out
of our program. Data validation is one way to address this.

Line 7 - We use an if/else statement to see if the user’s guess evaluates to “True”, or the same number
as the computer chose. An if/else statement is also called a conditional in computer programming.
Line 8 & 9- If it is the same, we tell the user “You guessed right!” and we end the program.
Line 10 - If Line 7 evaluates to “False”, or in other words the numbers are NOT the same, then we
have to determine if the guess was too high or too low. In this line we are checking to see if the
user’s guess is LESS THAN the computer’s number.
Line 11 - If it is LESS THAN the computer’s number, then we tell the user to guess a bigger number.
Line 12 - If it is GREATER THAN the computer’s number, then we tell the user to guess a smaller
number.
Line 13 - Tell the user to guess a smaller number.
How was that? This program was a little more complex, but hopefully not too bad. So … how can you
change it? Can you make a different guessing game using the same logic/algorithm? Can you create
a new variable that keeps track of the number of guesses the user makes. Give it a try! Improving
and iterating on your code is the essence of computational thinking.

Sonic Pi on the Raspberry Pi


Sonic Pi is a free application, included with the Raspberry Pi, used to program digital music. It uses
the Ruby programming language. It is very easy to get started and allows learners to

Getting started with Sonic Pi

Getting Started With Sonic Pi by the Raspberry Pi Foundation is licensed under a Creative Commons
Attribution 4.0 International Licence
Chapter 5 - Coding with the Raspberry Pi 32

Ever wanted to make funky music like Daft Punk or will.i.am but you’re not sure how to hold a
cello, let alone play it? Sonic Pi could get you there.

Sonic Pi is also available as a free download for Windows PCs and Apple Mac OS X
computers. Find it [here] (http://www.sonic-pi.net)

First sounds with Sonic Pi

This is the Sonic Pi interface; it has three main windows. The largest one is for writing your code,
and we call it the Programming Panel. There is also an output panel that displays information about
your program as it runs. When you click on the help button at the top of the window, the third panel
appears along the bottom displaying help documentation. This contains information about different
code you can try and use, as well as different synth sounds, samples, and much more.

1. Launch Sonic Pi from the Applications menu.


2. Select Buffer 1 and type:
Chapter 5 - Coding with the Raspberry Pi 33

1 play 60

3. Click on the play icon at the top of the screen. What happens?
4. What happens if you type pley 60 and click on the play icon?
This is an example of a bug in your code. In later activities, if the error panel displays text you
will know that you have a bug that you need to fix. It could be that you have misspelt a word
like play.
5. Now type:

1 play 60
2 play 67
3 play 69

6. Click on the play icon at the top of the screen. What happens?
7. The computer is playing each note in sequence (one after the other), but it is happening so
fast that to us they sound like they are playing at the same time.
We need to tell the computer to pause between each note. We can do this by typing the
following after each play:

1 sleep 1

The value entered after the word sleep represents time in seconds. Using the value 1 represents
one second. What would you type for half a second?
8. Now write a sequence of play and sleep to make a cool-sounding tune!

Loop a tune

Now you have mastered the basics of Sonic Pi, let’s code a tune!

1. Select Buffer 2.
2. Type the following code:

1 play 60
2 sleep 0.5
3 play 62
4 sleep 0.5
5 play 64
6 sleep 0.5
7 play 60
8 sleep 0.5
Chapter 5 - Coding with the Raspberry Pi 34

3. Now click on the play icon at the top of the screen and it will play the first part of a tune. Can
you tell what it is?
Answer: Frere Jacques!
This first section plays twice. How could you repeat it? You could type the same section out
again, or we could start to introduce loops to your code.
4. At the top of your code, above the first play 60, type:

1 2.times do

5. And at the bottom of your code, below sleep 0.5, type:

1 end

6. Click on the play icon at the top of the screen. What happens?
Let’s play this part in Sonic Pi.
In the example below, you can see that some lines of code are indented. This makes it easier
to read your code, and check for any bugs if it does not work when you press the play button.
You can press the space bar twice to indent a line of code.

1 2.times do
2 play 60
3 sleep 0.5
4 play 62
5 sleep 0.5
6 play 64
7 sleep 0.5
8 play 60
9 sleep 0.5
10 end

Loop forever?

Looping notes for a set number of times is certainly useful, but what if you want to loop your tune
forever?
Instead of using 2.times do and end you can use loop do and end, like this:

1 loop do
2 play 60
3 sleep 0.5
4 end
Chapter 5 - Coding with the Raspberry Pi 35

MIDI notes and music notes

The values that you have been typing after the word play represent notes; in fact, they are MIDI
note numbers. This means we can translate songs played on a piano into Sonic Pi using a table like
so:
C D E C or 60 62 64 60 in MIDI notes.

Music Notes to MIDI Note Values


C D E F G A B
60 62 64 65 67 69 71

This is quite a long process if you know the notes of the song you are trying to play. With Sonic Pi
you are able to use standard sheet music notation too.

1. In a new buffer tab type:

1 play :c4
2 sleep 0.5
3 play :d4
4 sleep 0.5
5 play :e4
6 sleep 0.5
7 play :c4
8 sleep 0.5

2. Press play to hear your tune. Does it sound the same as when you used MIDI notes?

Change the sounds

It’s time to make your tune sound more interesting! We can do this by changing the synthesizer
sounds it is using. The default Sonic Pi synth is called beep.
To use a different synth, you need to add the code use_synth :name of synth above the sequence
of code you want to use it in.
In this example, fm is the name of the synth:
Chapter 5 - Coding with the Raspberry Pi 36

1 use_synth :fm
2 2.times do
3 play 60
4 sleep 0.5
5 play 67
6 sleep 0.5
7 end

Synths to try

There are lots of cool-sounding synths included with Sonic Pi. To find the names of them, click
on the help icon at the top of the screen so that the help documents window appears. Then select
Synths from the tabs along the left hand side of the help window. Click on any of the synth names
to get more information on how to use it.

Use samples

Not only can you create music in Sonic Pi using single notes, you can also create music with samples.
Samples are pre-recorded sounds or tunes that you can bring into your music. This is a really simple
way to make your music sound amazing!
To use a sample, you need to add the code sample :name of sample in the sequence of your music
program where you want it to play.
In this example, loop_amen is the name of the sample:

1 2.times do
2 sample :loop_amen
3 sleep 1.753
4 end

Samples to try

There are lots of samples included with Sonic Pi. To find the names of them, click on help followed
by samples on the left hand side of the help window. Click on any of the sample names to get more
information on how to use it.

Playing two tunes at the same time

Music often has a repeating backing track, with a separate melody played over the top. So far in
Sonic Pi you have played one tune. Let’s try playing two tunes at the same time!

1. Click on a new buffer tab.


2. The code we use to play two tunes at the same time needs to be between in_thread do and
end.
3. Underneath in_thread do, type your tune. Here I’ve used a sample for my backing track:
Chapter 5 - Coding with the Raspberry Pi 37

1 in_thread do
2 loop do
3 sample :loop_amen
4 sleep 1.753
5 end
6 end

This first ‘thread’ will act as the melody of your music. Underneath, you can type the code
for your backing track or baseline.
4. Type:

1 in_thread do
2 16.times do
3 play 75
4 sleep 1.753
5 play 74
6 sleep 0.25
7 end
8 end

5. Now press play and you should hear both threads playing at the same time.

Live code!

Sonic Pi has been developed to be a platform for the live coding of music, so that the code can be
manipulated, changed and adapted in real time; this means coders can perform their code rather
than playing pre-written programs. Why not have a go?

1. In a new buffer tab type:

1 define :play_my_synth do
2 use_synth :prophet
3 play 50, attack: 0.2, release: 1.3
4 sleep 0.5
5 end
6
7 loop do
8 play_my_synth
9 end

2. Press play to start the program.


3. Whilst the tune is playing, comment out the last three lines by adding a # symbol to the start
of each line like this:
Chapter 5 - Coding with the Raspberry Pi 38

1 # loop do
2 # play_my_synth
3 # end

4. Next change some of code in the function, and press play again. Now you are really rocking!

What next?

Explore more features of Sonic Pi.


Sonic Pi offers so much more functionality to both coders and musicians alike than has been
mentioned here. If you want to try some more features then move onto the next tutorial here
Also, check out this really great free e-book - Code Music with Sonic Pi by Sam Aaron, the creator
of Sonic Pi. He has written this book to complement the software’s built-in tutorial and to help
you jump-start your live-coding career. The book is packed with fun, instantly rewarding examples
designed to highlight many of the amazing things Sonic Pi enables you to do.
Chapter 6 - Beginner Projects
””There are those who look at things the way they are, and ask why… I dream of things that never
were, and ask why not?”
–Robert Kennedy

Standards, Curriculum, Objectives … Oh My!


Before we begin, you may have looked at the Table of Contents and still be wondering how exactly
you can incorporate these projects into your curriculum. If you are an English/Language Arts
teacher, a Social Studies educator, or a teacher of “X” you might feel there is not much relevance
here. While it may be stretch to connect these Beginner Projects directly to your curriculum and
associated standards/objectives, there are - in fact - many non-cognitive skills students will be
practicing while completing these projects. If you are in need of standards/objectives in order for
you to even begin thinking about using these in your classroom, I would encourage you to look
at the College and Career Readiness (CCR) Anchor Standards found within the Common Core
State Standards (CCSS). (Note: I loathe educational acronyms). These standards focus on the skills
necessary for post-secondary success. These include, among others, skills in reading, writing, and
critical thinking.¹⁸ Whether you find value in the CCSS/CCR or not (the subject of a book of its
own) is not the point here. The reality is many educators must conform to these standards in their
lesson preparation. I think you will find crossover in these standards and the skills required to
be successful with Raspberry Pi projects. Chapter 9 will discuss more curricular connections. As I
argued in Chapter 5, I believe strongly in the benefits of computational thinking across all disciplines.
As you complete these projects, I challenge you to think about how you and your students will use
computational thinking to aid in the completion of these activities.
One of the best ways to get your students engaged with the Raspberry Pi computer in the classroom
is for them to build a project straight away. Brand new learners should start with the “Getting
Started” project found in Chapter 3. The following projects are great “next steps” and introduce
basic building, thinking, and creating with the Raspberry Pi.

Project #1 - Sweet Shop Reaction Game


Sweet Shop Reaction Game by the Raspberry Pi Foundation is licensed under a Creative Commons
Attribution 4.0 International Licence
¹⁸http://www.corestandards.org/ELA-Literacy/CCRA/
Chapter 6 - Beginner Projects 40

Some penny sweets or candy can make great input devices for a game using a Raspberry Pi. Let’s
turn a squidgy sweet into an input button for your Raspberry Pi. You will then create a quick reaction
game in Scratch which counts how many times seconds a player can squeeze your sweet input device
in ten seconds!

Create a sweet munching sprite


The sweet shop reaction game needs a munching face to entertain the player. You will draw a face
using the paint editor in Scratch, and animate it to open and close its mouth.

1. Open Scratch by clicking on Menu, Programming and Scratch. It is very important that you
use this version of Scratch on Raspberry Pi to be able to control the GPIO pins.
2. Once Scratch is running choose Start GPIO Server from the Edit menu.
3. If asked, click Ok to enable remote sensor connections.
4. Delete the Scratch Cat sprite by right-clicking on it with your mouse and selecting delete.
5. Click on the paint new sprite icon above the sprites palette, and draw a face with a closed
mouth using the paint editor. When you are happy with your sprite click OK.
6. Next, with your newly painted sprite selected, click on the Costumes tab. Rename the costume
to face1 by clicking on the sprite name followed by the edit button, and typing the new name.
7. Click the copy button to make an exact copy of the face. You will now have two identical
faces on the costumes tab called face1 and face2.
8. The next step is to edit face2 to change the mouth from closed to open. With face2 selected,
click on the edit button to open the paint editor.
9. Erase the mouth using a paintbrush tool or an erase tool and then replace it with an open
mouth. When you are happy with your sprite costume click Ok.
10. To animate your sprite to switch between costumes, you will need to click on the Scripts tab
of your sprite. Drag the control block when green flag clicked from the blocks palette to
the scripts area.
11. Next, drag the look block switch to costume face1 and connect it to the control block.
12. Then add the control block forever underneath the look block.
The forever block is a loop that will run the same sequence of blocks inside it over and over
again.
13. Add the control block wait 1 secs and the look block next costume inside the forever loop.
14. Change the time from one second to half a second. How could you represent time as a value?
If one is a whole, what would half of one be?
15. Time to save your work so far and test that your script to animate a sprite works. Go to File
and Save As. Name your file SweetShopGame and click Ok.
16. Finally, click on the Green Flag in the top right hand of the screen and you should see your
sprite face open and close its mouth.
Chapter 6 - Beginner Projects 41

Design a sweet shop background


To make the game a little more interesting, let’s set the scene by changing the background from the
default white to something a little more exciting, like a gradient colour or sweets in a shop!

1. Click on the stage icon next to the sprites palette to change the background.
2. Next, locate the backgrounds tab and select it with your mouse.
3. If you want to draw your own background, click on the edit button underneath the
background1 label: this will open the paint editor. Use the drawing tools to make a more
interesting and colourful background.
Or

If you would rather add a new background using an image, delete background1 by clicking on the
x underneath the background1 label. Then click on the import button to use a background from the
image library, or from a picture that you have saved.

1. When you are happy with your background, click on sprite1 in the sprites palette, ready to
program the reaction game mechanics in the next step.

Program the sweet shop reaction game mechanics


Many people enjoy testing their reaction time against a clock. Let’s create a reaction game using
ScratchGPIO that we can connect to a squidgy sweet button later on. The object of the game is to
see how many times you can squeeze the sweet button in ten seconds.
You will need to create two variables for this game: one to count the button presses, and one to count
time.

1. Click on variables from the blocks palette and select make a variable. Name the first variable
counter and click ok.
2. Repeat the first step to create another variable named timer.
3. Click on the control blocks palette and drag the When green flag clicked block on to the
scripts tab of your face sprite.
4. Next, add the variable block set counter to 0 so that at the start of each game the counter
is reset to 0, ready to test the player’s button-pushing skills.
Chapter 6 - Beginner Projects 42

5. Add a forever looping block, connect it and then place an if block inside the forever block.
6. There is a small blank space on the if block; this is so that you can add other blocks. In this
space, you first need to add the operator block ‘ = ‘.
7. Blocks can be added on either side of the = block. On the left hand side add the sensing block
slider sensor value and on the right hand side type the value 0. Using the drop-down menu
change slider to pin3.
8. Inside the if block add the variable block change counter by 1 and play drum 48 for 0.2
beats. You can select any drum noise that you like from the drop down menu.

To set a time limit that counts upwards for the game, you need to add two further scripts:

1. Add when green flag clicked block to the scripts and connect the sensing block reset
timer to it.
2. Underneath, connect a forever looping control block.
3. Inside the loop add the variable block set control to 0 and using the drop-down menu on
the block, change control to timer so that the block reads set timer to 0.
4. Replace the value 0 in the set timer to 0 block with the operator block round.
5. Then add the sensing block timer inside the space on the ‘round’ block. The completed block
should look like:

6. Add another when green flag clicked control block to the scripts area and connect a wait
until block to it.
Chapter 6 - Beginner Projects 43

7. Add the operators block = to the space in the wait until block. In the left hand space, add
the variable block timer. On the right hand side, type a value to represent time. If you want
your game to last for ten seconds, type 10.
8. Connect a stop all control block to the end of this script.
9. Finally, save your game by clicking on the save icon at the top of the screen.

Wire up your sweet button


You will need to connect a sweet or piece of candy to your Raspberry Pi to act as an input device
and test it.

1. If you are using metal paper clips, unfold them to make straight wires.
2. Insert the paper clip wire or dress pin into the end of a female to female jumper cable.
3. Do the same to the other jumper cable so that the two cables are identical.
4. Insert the paper clips into a soft sweet so that they are close to each other but not touching.

You will be using pin 3 and a GND pin.


5. Take the other end of one of the jumper cables (not connected to a paper clip) and push onto
pin 3 of the General Purpose Input-Output (GPIO) header, which is connected to one of the
GPIO channels.

GPIO stands for General Purpose Input Output. It is a way in which the Raspberry Pi can control
and monitor the outside world by being connected to electronic circuits. The Pi is able to control
LEDs, or motors, or many other things. It is also able to detect whether or not a switch has been
Chapter 6 - Beginner Projects 44

pressed.

1. Take the end of the other jumper cable and push onto a pin labelled ‘GND’ which is connected
to ground.
Warning! You can damage your Raspberry Pi if you do not use the GPIO pins correctly!

Remember that your sweet input device is not a real button and will not give accurate results for
your game. It is just a bit of fun.

Put it all in a box


Congratulations on making your Sweet Shop Reaction Game! If you have time, why not make and
decorate a box to put the Raspberry Pi and cables into?

What’s next?
• Can you add user input to your scratch program to find out the name of the player?
• Can you connect a real physical button instead of a sweet?
• Can you write a similar program using a text-based programing language like Python?

Project #2 - Burping Jelly Baby


Burping Jelly Baby by the Raspberry Pi Foundation is licensed under a Creative Commons Attribution
4.0 International Licence
In this silly project, you will make a jelly baby burp by pressing it!

Wire up a jelly baby


To turn a simple jelly baby into a switch, you will attach cables to it and then connect them to the
GPIO pins on a Raspberry Pi. You will need some female to female jumper wires and paperclips for
this project.
Chapter 6 - Beginner Projects 45

Female to Female Jumper

1. Looking at the following GPIO diagram, compare it to your Raspberry Pi.


You’ll be using a single ground pin (marked GND) and a GPIO pin (marked GPIO):

Note that if you have an older Raspberry Pi model you’ll only have 26 pins but they have the same
layout, starting at the top row (3V3 and 5V and ending at GND and GPIO7).

1. Take the metal paper clips and unfold them to make a straight wire.
2. Take a female to female jumper wire and push the paper clip wire into one of the ends.
3. Do the same to the other wire so that you have two identical jumper cables with paper clip
wires in one end.
Chapter 6 - Beginner Projects 46

4. Insert the paper clips into a jelly baby so that they are close to each other but not touching.
The diagram above the pins shows the GPIO pin numbers. You will be using GPIO 3 and any
GND pin.
Note that you will be only able to have one burping jelly baby button. Only use GPIO 3 and
GND for this tutorial.
5. Take the other end of one of the jumper leads and push it onto GPIO 3 of the General Purpose
Input-Output (GPIO) header which is connected to one of the GPIO channels.
6. Take the end of the other jumper lead and push it onto the pin next to GPIO 3 labelled GND.
Warning: You can damage your Raspberry Pi if you do not use the GPIO pins correctly!
7. Make sure your Raspberry Pi has speakers or headphones so that you can hear your jelly baby
burping. If you are using headphones or a speaker on the Raspberry Pi, you will need to type
the following command to redirect sound to the headphone socket in the Terminal which can
be opened by clicking on Menu and then Accessories:
amixer cset numid=3 1

Sound of a burp!
So far you have created your input device and have your Raspberry Pi set up and running. You
now need to find a burping sound file and move it into a new folder. This can all be achieved in a
Terminal window:

1. Create a new folder called jellybaby with the following command:

1 mkdir jellybaby

2. Enter the folder with cd jellybaby


We’re going to need a burping sample sound file for this project so we’ll use one from Sonic
Pi.
3. Make a copy of Sonic Pi’s sound of a burp with the following command:

1 cp /opt/sonic-pi/etc/samples/misc_burp.wav burp.wav

This will copy the misc_burp sound file from the sonic-pi folder into the jellybaby folder and
rename it to burp.wav
4. Now test that you can play the sound file using omxplayer by typing:

1 omxplayer burp.wav
Chapter 6 - Beginner Projects 47

omxplayer will play the sound file and you should hear it from the speakers or headphones
connected to your Pi.
If you cannot hear anything, make sure that your headphones or speakers are connected
correctly. If the jack/plug looks like the picture below (notice the three black bands) you may
find that it will only work if you pull the plug out by a few millimetres.

Write a program in Python


The final step to make your jelly baby burp is to write a program in Python; it will detect when you
press the jelly baby input device and output the burp sound.

1. This time we will open the Python 3 IDE - also called IDLE - from the command line. To do
this type the following command in the Terminal:

1 sudo idle3

2. Once IDLE3 has opened, click on File and New File. This will open a blank file. Click on File
and Save As and name the file burp.py
Chapter 6 - Beginner Projects 48

Image by Richard Hayler

1. Begin your program by importing the modules and libraries needed to make it work. Type the
following:

1 import time
2 import RPi.GPIO as GPIO
3 import os

The time library will be used to make the program pause for a fixed amount of time. The Raspberry
Pi GPIO libraries will be used to connect the Raspberry Pi to other physical devices via the General
Purpose Input-Output (GPIO) pins, in this case your jelly baby input device! The os library will
allow you to play the burp sound in omxplayer, but this time from within your code.

1. Now you will need to set up the GPIO pins to use GPIO board pin numbers. Leave a line
empty by pressing Enter on your keyboard, then type:

1 GPIO.setmode(GPIO.BCM)

2. To switch off the “Ports already in use” warnings, press Enter to give you a new line and type:

1 GPIO.setwarnings(False)

3. Set GPIO 3 on the GPIO header to be an input with the following command:

1 GPIO.setup(3,GPIO.IN)

4. Create a loop that runs forever and plays the burping sound file when the two wires inside
the jelly baby are touching by typing the following:
Chapter 6 - Beginner Projects 49

1 while True:
2 if GPIO.input(3) == False:
3 os.system("omxplayer burp.wav")
4 time.sleep(1)

5. Save the file by clicking on File and Save.


6. Finally, run the program by clicking on Run and Run Module

Congratulations! Now when you press the jelly baby, the wires will touch and the burp sound file
will play.

What’s next?
• Using a real button or switch connected to a breadboard
• Changing the sound that plays when the device is pressed
• Why not create a whole music box with the GPIO Music Box tutorial.
Chapter 7 - Physical Computing with
Raspberry Pi
“The role of the teacher is to create the conditions for invention rather than provide ready-made
knowledge.”
–Seymour Papert

What is Physical Computing?


The GPIO (General Purpose Input Output) pins allow the Raspberry Pi to control and monitor
the outside world through electronic circuits. The Pi is able to control LEDs - turning them on
or off - run motors, and many other things. It’s also able to detect whether a switch has been
pressed, the temperature inside a room, or light levels. In simple terms, you can think of the GPIO
pins as switches that you can turn on or off (input) or that the Pi can turn on or off (output).
We refer to this ability as physical computing. Physical computing is a great way to get your
students started with building, thinking, and creating with the Raspberry Pi. Programming can be
fun and engaging for some students, but many students want to build something tangible. Physical
computing provides the opportunity for both coding and building. Additionally, physical computing
can fit nicely into project-based learning units, as it allows for “Do-It-Together” (DIT) methods of
instruction. Students can work in groups with assigned roles such as designer, coder/programmer,
engineer/builder, project manager, evaluator, etc. This type of learning simulates real-world teams
and can help students connect skills (technical and non-cognitive) learned in the classroom to future
careers. Finally, physical computing is a great introduction to the Internet of Things (IoT) projects.
Learn more about IoT and the Raspberry Pi in Chapter 10.

Physical Computing w/ Scratch


Scratch is generally the easiest language to use when getting started with physical computing
projects. As you saw in Chapter 5, Scratch is an easy-to-use, “drag-and-drop” programming language
designed for new learners. Physical computing can often become quickly complex since you are
now having to write code AND design a circuit or assembly some type of hardware. Often new
learners will have the circuit wired correctly, but the code is wrong. Simplifying the code for physical
computing projects helps new learners focus on the logic and problem-solving skills needed to be
build their circuits successfully. Once learners are comfortable with circuit building, they can then
move to Python coding, which offers greater flexibility and opportunities for advanced physical
computing projects.
Chapter 7 - Physical Computing with Raspberry Pi 51

Project #1 - LEDs and Buttons

Physical Computing With Scratch by the Raspberry Pi Foundation is licensed under a Creative
Commons Attribution 4.0 International Licence
WARNING: If you follow the instructions, then playing about with the GPIO pins is safe and fun.
Randomly plugging wires and power sources into your Pi, however, may destroy it, especially if
using the 5V pins. Bad things can also happen if you try to connect things to your Pi that use a lot
of power; LEDs are fine, high-voltage motors are not. If you’re worried about this, then you might
want to consider using an add-on board such as the Explorer HAT until you’re confident enough to
use the GPIO directly.

GPIO pins

There are 40 pins on the Raspberry Pi (26 pins on early models), and they provide various different
functions.
This guide can help you to identify the pin numbers:

You’ll see pins labelled as 3V3, 5V, GND and GP2, GP3, etc:

3V3 3.3 volts Anything connected to these pins will always get 3.3V of
power
5V 5 volts Anything connected to these pins will always get 5V of
power
GND ground Zero volts, used to complete a circuit
GP2 GPIO pin 2 These pins are for general-purpose use and can be
configured as input or output pins
ID_SC/ID_SD/DNC Special purpose pins
Chapter 7 - Physical Computing with Raspberry Pi 52

Lighting an LED

You can test whether your GPIO pins and LEDs are working by building the circuit below.

1. The LED is connected directly to the 3.3V and GND pins, and should light up.
2. Be sure to connect your LED the correct way round; the longer leg should be connected to the
3V3 pin:

Test Circuit

Using a switchable pin

1. To control the LED, you’ll need to adapt your circuit to use a switchable pin.
2. In the diagram below pin 17 has been used, but you can use any numbered pin you wish.
Chapter 7 - Physical Computing with Raspberry Pi 53

Test Circuit

Constructing a Scratch program

1. Locate the Scratch program by clicking on Menu followed by Programming, and selecting
Scratch.
2. The familiar Scratch interface will then load.
3. Click on Control in the top-left display. Drag the when GreenFlag clicked block onto the
scripts area:

greenflag

1. Scratch uses broadcast blocks to communicate with the GPIO pins; the first broadcast you
need is gpioserveron which activates the GPIO functionality:
Chapter 7 - Physical Computing with Raspberry Pi 54

gpioserveron

1. As your GPIO pin can be used as either input or output, you’ll need to specify in which mode
your pin is being used with the config17out broadcast:

config17on

1. From this point on, you can control your LED using two broadcasts: gpio17high to turn it on
and gpio17low to turn it off. Using these two messages and some pauses, you can make an
LED flash continuously:

Flashing LED
Chapter 7 - Physical Computing with Raspberry Pi 55

Connecting a button

1. As well as controlling the physical world, you can react to it using an input device such as a
button.
2. Connect your button to a breadboard, then connect one pin to a ground pin and the other to
a numbered GPIO pin. In this example pin 2 has been used. Make a circuit like this:

Button wiring

Configuring your button

1. Before Scratch can react to your button, it needs to be told which pin is configured as an input
pin.
2. Assuming you have started a new Scratch file, you’ll also need to start the GPIO server. The
following code will configure pin 4 as an input:
Chapter 7 - Physical Computing with Raspberry Pi 56

Configure Pin 2

1. Once you have built the code above, you need to click the green flag in order for it to run and
for your pin to be set up.
2. Next, you need to go to the Sensing menu in Scratch:

Sensing Menu

1. From here you need to find the block and click the triangle to
reveal a menu. Select gpio2 from the menu and click the tickbox to the left:

Select sensor

1. You should now see the current state of the pin in the stage area:
Chapter 7 - Physical Computing with Raspberry Pi 57

Button state

1. Now when you press your button, the state should change from 1 to 0.

Responding to a button press

1. Now that your button is all set up and working, you can make it do something. You can start
off by making it control a sprite.
2. Begin with a forever loop with an if block inside it. This will continually check the if
condition and perform some action if the condition is met. The action in the example below
will make the current sprite move forward:

Loop with condition


Chapter 7 - Physical Computing with Raspberry Pi 58

3. Finally, to make this work you need to add the condition, which is that we want the move
action to happen when the button value = 0:

Complete Code

If everything is correct, your button should make the sprite move.

Controlling an LED with a button push

To finish off, you can combine your two programs so that the button can turn the LED on and off.

1. Adapt your script and use an If Else block so that it looks like the example below:

Complete code
Chapter 7 - Physical Computing with Raspberry Pi 59

2. Now when you push the button, the LED should light up.

Project #2 - Santa Detector

Santa Detector by the Raspberry Pi Foundation is licensed under a Creative Commons Attribution
4.0 International Licence
You will build a detector that spots any movement and sets off an alarm. Along the way, you will
learn how to connect a passive infra-red (PIR) sensor to the Raspberry Pi, and how to control the
flow of your Scratch program by responding to the input from the sensor.

Connect the PIR motion sensor

Before booting your Raspberry Pi, connect the PIR module to the Raspberry Pi.
Using three female-to-female jumper cables, you’ll need to connect each of the PIR sensor’s
connectors to the appropriate pins on the Raspberry Pi.
Connect the top one labelled VCC on the PIR sensor to the 5V pin on the Raspberry Pi, connect the
middle one labelled OUT to GPIO pin 4, and connect the bottom one labelled GND to a ground pin also
marked GND. All shown in the following diagram:

Test the sensor

Because we are using the GPIO pins, we need to start the GPIO server in Scratch:

• On the desktop run Scratch using Menu -> Programming -> Scratch.
• Once Scratch is running choose Start GPIO Server from the Edit menu.
Chapter 7 - Physical Computing with Raspberry Pi 60

scratch GPIO server

Scratch uses the ‘Sensing’ blocks to check if there is any input on the GPIO pins. If there is an input,
the value of the pin changes from 0 to 1. As you connected the PIR sensor to GPIO pin 4 of the Pi,
we need to monitor that.
Firstly we need to tell Scratch that pin 4 will be used as an input by configuring it.

• Create a broadcast message as follows:

Sensor drop down

• Double click the broadcast block to run it. You only need to do this once.
• In the Sensing block palette click on the drop-down menu on the sensor value block and
choose gpio4.
• Tick the check-box to the left of the block to display the pin value on screen.

NOTE: If you do not see gpio4 on the list, make sure that the GPIO server is running and that you
have run the config broadcast.
Chapter 7 - Physical Computing with Raspberry Pi 61

Scratch sensing blocks

Test the PIR sensor by waving your hand in front of it. When it detects movement, the value on the
screen should change from 0 to 1.
If the value doesn’t change, check that the correct pins are connected.

Draw a sprite and add sound

Click on the ‘Costumes’ tab and draw (or use the one below) a Santa sprite This will be displayed
when the PIR senses movement.
Chapter 7 - Physical Computing with Raspberry Pi 62

Click on the ‘Sounds’ tab and import a sound from the ‘Electronic’ folder. I’ve used a siren called
‘Whoop’ here.

Program what happens when the detector spots movement

Now we have a sensor that reports when it is on or off, we can use this value to control the flow of
our program.
Build the following script:
Chapter 7 - Physical Computing with Raspberry Pi 63

Scratch script for santa detector

What is the the program doing?

The if statement continuously checks the pin 7 sensor value. When this changes to 1 it does the
following:

• shows the sprite


• makes the sprite bigger
• waits a bit
• plays a sound
• makes the sprite normal size

It keeps doing this as long as the sensor value is 1 i.e. when the PIR detects movement.
The else statement simply hides the sprite when the sensor value is 0.
Chapter 7 - Physical Computing with Raspberry Pi 64

santa sprite in Scratch

Set up the detector in your room!

• On Christmas Eve, set up your Pi with the sensor pointing at your bedroom door.
• Connect your Pi to a huge speaker.
• Make sure the sensor does not detect you in bed or you will get false positives; the alarm will
go off every time you move!
• Go to sleep.
• Wake up when Santa comes in and feed him mince pies and sherry.
Chapter 7 - Physical Computing with Raspberry Pi 65

Physical Computing w/ Python


Python is great for more advanced physical computing projects. Ben Nuttall has created a easy-
to-use application programming interface (API) for accessing the GPIO pins via Python called
GPIO Zero. GPIO Zero is a Python library which provides a simple interface to everyday GPIO
components. It comes installed by default in Raspbian.

An API is a set of rules that govern how one application can talk to other application via a
programming language. It is the feature that allows your Facebook account to connect to your
Pinterest account, to your email account, to your …. you name it! Without APIs, most internet
websites would not be able share information with each other and the Web would be a much less
interesting/useful tool.

Project #1 - LEDs and Buttons

Physical Computing With Python by the Raspberry Pi Foundation is licensed under a Creative
Commons Attribution 4.0 International Licence

GPIO pins

WARNING: If you follow the instructions, then playing about with the GPIO pins is safe and fun.
Randomly plugging wires and power sources into your Pi, however, may destroy it, especially if
using the 5V pins. Bad things can also happen if you try to connect things to your Pi that use a lot
of power; LEDs are fine, high-voltage motors are not. If you’re worried about this, then you might
want to consider using an add-on board such as the Explorer HAT until you’re confident enough to
use the GPIO directly.

Lighting an LED

LEDs are delicate little things. If you put too much current through them they will pop (sometimes
quite spectacularly). To limit the current going through the LED, you should always use a resistor
in series with it.
Try connecting an LED to the Pi’s 3V3 and GND pins with a resistor. Anything over about 50ç«‹
should do the trick:
Chapter 7 - Physical Computing with Raspberry Pi 66

The LED should light up. It will always be on, because it’s connected to a 3V3 pin, which is itself
always on.
Now try moving it from 3V3 to GPIO pin 17:
Chapter 7 - Physical Computing with Raspberry Pi 67

The LED should now turn off, but now it’s on a GPIO pin, and can therefore be controlled by code.

Switching an LED on and off

1. Open IDLE from the main menu (Menu>Programming>Python 3 (IDLE).


2. You can switch an LED on and off by typing commands directly into the Python interpreter
window (also known as the Python shell). Let’s do this by first importing the GPIO Zero
library. You also need to tell the Pi which GPIO pin you are using - in this case pin 17. Next
to the chevrons >>>, type:

1 from gpiozero import LED


2 led = LED(17)

Press Enter on the keyboard.


3. To make the LED switch on, type the following and press Enter:

1 led.on()

4. To make it switch off you can type:

1 led.off()

5. Your LED should switch on and then off again. But that’s not all you can do.
Chapter 7 - Physical Computing with Raspberry Pi 68

Flashing an LED

With the help of the time library and a little loop, you can make the LED flash.

1. Create a new file by clicking File > New file.


2. Save the new file by clicking File > Save. Save the file as gpio_led.py.
3. Enter the following code to get started:

1 from gpiozero import LED


2 from time import sleep
3
4 led = LED(17)
5
6 while True:
7 led.on()
8 sleep(1)
9 led.off()
10 sleep(1)

4. Save with Ctrl + S and run the code with F5.


5. The LED should be flashing on and off. To exit the program press Ctrl + C on your keyboard.

Using buttons to get input

Now you’re able to control an output component (an LED), let’s connect and control an input
component: a button.

1. Connect a button to another GND pin and GPIO pin 2. Your circuit should now look like this:
Chapter 7 - Physical Computing with Raspberry Pi 69

2. Create a new file by clicking File > New file.


3. Save the new file by clicking File > Save. Save the file as gpio_button.py.
4. This time you’ll need the Button class, and to tell it that the button is on pin 2. Write the
following code in your new file:

1 from gpiozero import Button


2 button = Button(2)

5. Now you can get your program to do something when the button is pushed. Add these lines:

1 button.wait_for_press()
2 print('You pushed me')

6. Save with Ctrl + S and run the code with F5.


7. Press the button and your text will appear.

Manually controlling the LED

You can now combine your two programs written so far to control the LED using the button.
Chapter 7 - Physical Computing with Raspberry Pi 70

1. Create a new file by clicking File > New file.


2. Save the new file by clicking File > Save. Save the file as gpio_control.py.
3. Now write the following code:

1 from gpiozero import LED, Button


2 from time import sleep
3
4 led = LED(17)
5 button = Button(2)
6
7 button.wait_for_press()
8 led.on()
9 sleep(3)
10 led.off()

4. Save and run your program. When you push the button the LED should come on for three
seconds.

Making a switch

With a switch, a single press and release on the button would turn the LED on, and another press
and release would turn it off again.

1. Modify your code so that it looks like this:

1 from gpiozero import LED, Button


2 from time import sleep
3
4 led = LED(17)
5 button = Button(2)
6
7 while True:
8 button.wait_for_press()
9 led.toggle()

led.toggle() switches the state of the LED from on to off, or off to on. Since this happens in
a loop the LED with turn on and off each time the button is pressed.
2. It would be great if you could make the LED switch on only when the button is being held
down. With GPIO Zero, that’s easy. There are two methods of the Button class called when_-
pressed and when_released. These don’t block the flow of the program, so if they are placed
in a loop, the program will continue to cycle indefinitely.
3. Modify your code to look like this:
Chapter 7 - Physical Computing with Raspberry Pi 71

1 from gpiozero import LED, Button


2 from signal import pause
3
4 led = LED(17)
5 button = Button(2)
6
7 button.when_pressed = led.on
8 button.when_released = led.off
9
10 pause()

4. Save and run the program. Now when the button is pressed, the LED will light up. It will turn
off again when the button is released.

Project #2 - Quick Reaction Game

Quick Reaction Game by the Raspberry Pi Foundation is licensed under a Creative Commons
Attribution 4.0 International Licence
In this project, you’re going to make a quick reaction game using a few electronic components and
a Python script.

Building the circuit

This is the circuit you are going to build, consisting of two push-to-make buttons and an LED.
Chapter 7 - Physical Computing with Raspberry Pi 72

1. Take one of your tactile buttons and push it into the holes on your breadboard, with one set
of legs on row H and one set of legs on row J.
2. Repeat the last step with the second button, placing it at the other end of the breadboard on
the same row.
3. Place an LED with the longer leg above the ridge in the breadboard in D16 and the shorter
leg in D15. The numbering will depend on your breadboard so make sure that you check the
diagram below.
4. Next push one leg of the resistor into the same column 15 as the short leg of the resistor and
the other leg into a hole along the blue strip.
Chapter 7 - Physical Computing with Raspberry Pi 73

5. Now it’s time to add the jumper wires. Start by taking two male-to-male jumper wires and
placing one end in a hole next to the outside leg of the left hand button, and the other end in
a hole along the blue strip. Repeat this step with the right hand button.
6. Then with a male-to-female jumper wire, connect GPIO14 to a hole on the breadboard in line
with the other leg of the left hand button. Repeat this step for the right hand button, only this
time connecting it to GPIO15.
7. Using another male-to-female jumper wire, connect GPIO4 to a hole on the breadboard in
line with the long leg of the LED.
8. Finally, connect a GND GPIO pin to the blue strip on the breadboard with the remaining
male-to-female jumper wire.

Controlling the light

When programming, it makes sense to tackle one problem at a time. This makes it easier to test your
project at various stages.

1. Click on the Menu>Programming>Python 3 (IDLE)


2. Create a new text editor file by clicking on File>New File
3. Save this file as reaction.py by clicking on File>Save As
4. First you will need to import the modules and libraries needed to control the GPIO pins on
the Raspberry Pi. Type:

1 from gpiozero import LED, Button


2 from time import sleep

5. As you are outputting to an LED, you need to set up the pin that the LED connects to on the
Raspberry Pi as an output. First use a variable to name the pin and then set the output:

1 led = LED(4)

6. Next add a line to turn the LED on:

1 led.on()

7. Now add a line to wait 5 seconds by typing:

1 sleep(5)

8. Then add a line to turn the LED off like this:

1 led.off()

9. Save the file by clicking on File>Save.


10. Finally, test that it works by click on Run>Run Module or by pressing F5 on the keyboard.

If the LED does not come on for five seconds, go back and see if you can work out what went wrong.
This is a very important skill in computing called debugging, which means finding and fixing errors
or bugs in your code.
Chapter 7 - Physical Computing with Raspberry Pi 74

Adding an element of surprise

The object of the game is to see who can press the button first when the light goes out, so it would
be better if the length of time it stayed on were random. You need to add and amend some lines of
code in your Python program to make this happen.

1. If the file reaction.py is not already open in IDLE3 then open it by clicking on File and Open.
2. Underneath from time import sleep add the following line:

1 from random import uniform

Here, uniform allows for the random selection of a decimal (floating point) number from a
range of numbers.
3. Then locate the line sleep(5) and amend it so that it reads:

1 sleep(uniform(5, 10))

4. Save your work by clicking on File and Save. Test that everything works by pressing F5 to
run your code.

Detecting the buttons

The LED is working; now you want to add functionality to your program so that when a button is
pressed it is detected. That way you can record the players’ scores to see who wins.
As with the last step, some code needs to be added to your current program.

1. With the file reaction.py open add the following variables underneath led = LED(4):

1 led = LED(4)
2 right_button = Button(15)
3 left_button = Button(14)

2. Then underneath led.off() you can add a function that will be called whenever a button is
pressed, which will tell you which pin the button was on:

1 def pressed(button):
2 print(button.pin.number + ' won the game')

3. To finish off, when either button is pressed, the function will be called. If the right_button is
pressed, then you can send the string 'right' to the pressed function. If the left_button is
pressed, then you can send the string 'left'.
Chapter 7 - Physical Computing with Raspberry Pi 75

1 right_button.when_pressed = pressed
2 left_button.when_pressed = pressed

Your completed code should now look like this

1 from gpiozero import LED, Button


2 from time import sleep
3 from random import uniform
4
5 led = LED(4)
6 right_button = Button(15)
7 left_button = Button(14)
8
9 led.on()
10 sleep(uniform(5, 10))
11 led.off()
12
13 def pressed(button):
14 print(button.pin.number + ' won the game')
15
16 right_button.when_pressed = pressed
17 left_button.when_pressed = pressed

Save your program and test it with a friend.

Get player names

Wouldn’t it be better if the program told you who has won instead of just which button was pressed?
For this, you need to find out the players’ names. In Python, you can use input for this.

1. To find out the names of the players you can use input to ask the players to type in their
names. Underneath the imported libraries and modules, type:

1 left_name = input('left player name is ')


2 right_name = input('right player name is ')

2. Now you can rewrite your pressed function, so that it can print out the name of the player
who won.
Chapter 7 - Physical Computing with Raspberry Pi 76

1 def pressed(button):
2 if button.pin.number == 14:
3 print(left_name + ' won the game')
4 else:
5 print(right_name + ' won the game')

3. Save reaction.py and test your game to see if it works.


4. You might notice that the game doesn’t quit when the button has been pushed. This can be
fixed by adding an exit into the pressed function. First, add the following line to your imports.

1 from sys import exit

5. Then you can call exit() within your pressed function, once the prints have been completed.

1 def pressed(button):
2 if button.pin.number == 14:
3 print(left_name + ' won the game')
4 else:
5 print(right_name + ' won the game')
6 exit()

Extend the project

• Can you put the game into a loop (you’ll need to remove the exit()), so that the LED comes
on again?
• Can you add scores for both players that accumulate over a number of rounds, and displays
the players’ total scores?
• How about adding in a timer, to work out how long it took the players to press the button
after the LED turned off?

Simple Electronics w/ GPIO Zero A great introduction to using the GPIO pins on the
Raspberry Pi and programming them with the GPIO Zero Python library. It unlocks a
whole new world of potential for your projects and it’s much easier to learn than you T>
might think! This is a great resource for you and your students to use to dive deeper into
physical computing and using the GPIO pins on the Raspberry Pi.
Chapter 8 - Minecraft: Pi Edition
“We are what we celebrate.”
–Dean Kamen

Minecraft is a popular sandbox open-world building game. A free version of Minecraft is available
for the Raspberry Pi; it also comes with a programming interface. This means you can write
commands and scripts in Python code to build things in the game automatically. It’s a great way to
learn Python!

Project # 1 - Getting Started with Minecraft Pi


Getting Started with Minecraft: Pi Edition by the Raspberry Pi Foundation is licensed under a Creative
Commons Attribution 4.0 International Licence

Minecraft Pi banner

Run Minecraft
To run Minecraft Pi, open it from the Desktop menu under Games.
When Minecraft Pi has loaded, click on Start Game, followed by Create new. You’ll notice that the
containing window is offset slightly. This means to drag the window around you have to grab the
title bar behind the Minecraft window.
Chapter 8 - Minecraft: Pi Edition 78

You are now in a game of Minecraft! Go walk around, hack things, and build things!
Use the mouse to look around and use the following keys on the keyboard:

Key Action
W Forward
A Left
S Backward
D Right
E Inventory
Space Jump
Double Space Fly / Fall
Esc Pause / Game menu
Tab Release mouse cursor

You can select an item from the quick draw panel with the mouse’s scroll wheel (or use the numbers
on your keyboard), or press E and select something from the inventory.
Chapter 8 - Minecraft: Pi Edition 79

You can also double tap the space bar to fly into the air. You’ll stop flying when you release the
space bar, and if you double tap it again you’ll fall back to the ground.

With the sword in your hand, you can click on blocks in front of you to remove them (or to dig).
Chapter 8 - Minecraft: Pi Edition 80

With a block in your hand, you can use right click to place that block in front of you, or left click to
remove a block.

Use the Python programming interface


With Minecraft running, and the world created, bring your focus away from the game by pressing
the Tab key, which will free your mouse. Open Python 3 from the application menu and move the
windows so they’re side-by-side.
You can either type commands directly into the Python window or create a file so you can save your
code and run it again another time.
If you want create a file, go to File > New window and File > Save. You’ll probably want to save
this in your home folder or a new project folder.
Start by importing the Minecraft library, creating a connection to the game and testing it by posting
the message “Hello world” to the screen:

1 from mcpi.minecraft import Minecraft


2
3 mc = Minecraft.create()
4
5 mc.postToChat("Hello world")

If you’re entering commands directly into the Python window, just hit Enter after each line. If it’s
a file, save with Ctrl + S and run with F5. When your code runs, you should see your message on
screen in the game.
Chapter 8 - Minecraft: Pi Edition 81

Find your location


To find your location, type:

1 pos = mc.player.getPos()

pos now contains your location; access each part of the set of coordinates with pos.x, pos.y and
pos.z.

Alternatively, a nice way to get the coordinates into separate variables is to use Python’s unpacking
technique:

1 x, y, z = mc.player.getPos()

Now x, y, and z contain each part of your position coordinates. x and z are the walking directions
(forward/back and left/right) and y is up/down.
Note that getPos() returns the location of the player at the time, and if you move position you have
to call the function again or use the stored location.

Teleport
As well as finding out your current location you can specify a particular location to teleport to.

1 x, y, z = mc.player.getPos()
2 mc.player.setPos(x, y+100, z)

This will transport your player to 100 spaces in the air. This will mean you’ll teleport to the middle
of the sky and fall straight back down to where you started.
Try teleporting to somewhere else!

Set block
You can place a single block at a given set of coordinates with mc.setBlock():

1 x, y, z = mc.player.getPos()
2 mc.setBlock(x+1, y, z, 1)
Chapter 8 - Minecraft: Pi Edition 82

Now a stone block should appear beside where you’re standing. If it’s not immediately in front of
you it may be beside or behind you. Return to the Minecraft window and use the mouse to spin
around on the spot until you see a grey block directly in front of you.

The arguments passed to set block are x, y, z and id. The (x, y, z) refers to the position in the
world (we specified one block away from where the player is standing with x + 1) and the id refers
to the type of block we’d like to place. 1 is stone.
Other blocks you can try:

1 Air: 0
2 Grass: 2
3 Dirt: 3

Now with the block in sight, try changing it to something else:

1 mc.setBlock(x+1, y, z, 2)

You should see the grey stone block change in front of your eyes!
Chapter 8 - Minecraft: Pi Edition 83

Block constants
You can use a inbuilt block constants to set your blocks, if you know their names. You’ll need another
import line first though.

1 from mcpi import block

Now you can write the following to place a block:

1 mc.setBlock(x+3, y, z, block.STONE.id)

Block ids are pretty easy to guess, just use ALL CAPS, but here are a few examples to get you used
to the way they are named.

1 WOOD_PLANKS
2 WATER_STATIONARY
3 GOLD_ORE
4 GOLD_BLOCK
5 DIAMOND_BLOCK
6 NETHER_REACTOR_CORE

### Block as variable


If you know the id of a block it can be useful to set it as a variable. You can use the name or the
integer id.
Chapter 8 - Minecraft: Pi Edition 84

1 dirt = 3
2 mc.setBlock(x, y, z, dirt)

or

1 dirt = block.DIRT.id
2 mc.setBlock(x, y, z, dirt)

### Special blocks


There are some blocks which have extra properties, such as Wool which has an extra setting you
can specify the colour. To set this use the optional fourth parameter in setBlock:

1 wool = 35
2 mc.setBlock(x, y, z, wool, 1)

Here the fourth parameter 1 sets the wool colour to orange. Without the fourth parameter it is set
to the default (0) which is white. Some more colours are:

1 2: Magenta
2 3: Light Blue
3 4: Yellow

Try some more numbers and watch the block change!


Other blocks which have extra properties are wood (17): oak, spruce, birch, etc; tall grass (31): shrub,
grass, fern; torch (50): pointing east, west, north, south; and more. See the API reference for full
details.

Set multiple blocks


As well as setting a single block with setBlock you can fill in a volume of space in one go with
setBlocks:

1 stone = 1
2 x, y, z = mc.player.getPos()
3 mc.setBlocks(x+1, y+1, z+1, x+11, y+11, z+11, stone)
Chapter 8 - Minecraft: Pi Edition 85

This will fill in a 10 x 10 x 10 cube of solid stone.

You can create bigger volumes with the setBlocks function but it may take longer to generate!

Dropping blocks as you walk


Now you know how to drop blocks, let’s use our moving location to drop blocks when you walk.
The following code will drop a flower behind you wherever you walk:

1 from mcpi.minecraft import Minecraft


2 from time import sleep
3
4 mc = Minecraft.create()
5
6 flower = 38
7
8 while True:
9 x, y, z = mc.player.getPos()
10 mc.setBlock(x, y, z, flower)
11 sleep(0.1)

Now walk forward for a while and turn around to see the flowers you have left behind you.
Chapter 8 - Minecraft: Pi Edition 86

Since we used a while True loop this will go on forever. To stop it, hit Ctrl + C in the Python
window.
Try flying through the air and see the flowers you leave in the sky:
Chapter 8 - Minecraft: Pi Edition 87

What if we only wanted to drop flowers when the player walks on grass? We can use getBlock to
find out what type a block is:

1 x, y, z = mc.player.getPos() # player position (x, y, z)


2 this_block = mc.getBlock(x, y, z) # block ID
3 print(this_block)

This tells you the location of the block you’re standing in (this will be 0 - an air block). We want
to know what type of block we’re standing on. For this we subtract 1 from the y value and use
getBlock() to determine what type of block we’re standing on:

1 x, y, z = mc.player.getPos() # player position (x, y, z)


2 block_beneath = mc.getBlock(x, y-1, z) # block ID
3 print(block_beneath)

This tells us the ID of the block the player is standing on.


Test this out by running a loop to print the block ID of whatever you’re currently standing on:

1 while True:
2 x, y, z = mc.player.getPos()
3 block_beneath = mc.getBlock(x, y-1, z)
4 print(block_beneath)

We can use an if statement to choose whether or not we plant a flower:


Chapter 8 - Minecraft: Pi Edition 88

1 grass = 2
2 flower = 38
3
4 while True:
5 x, y, z = mc.player.getPos() # player position (x, y, z)
6 block_beneath = mc.getBlock(x, y-1, z) # block ID
7
8 if block_beneath == grass:
9 mc.setBlock(x, y, z, flower)
10 sleep(0.1)

Perhaps next we could turn the tile we’re standing on into grass if it isn’t grass already:

1 if block_beneath == grass:
2 mc.setBlock(x, y, z, flower)
3 else:
4 mc.setBlock(x, y-1, z, grass)

Now we can walk forward and if we walk on grass, we’ll leave a flower behind. If the next block is
not grass, it turns into grass. When we turn around and walk back, we now leave a flower behind
us.
Chapter 8 - Minecraft: Pi Edition 89

Playing with TNT blocks


Another interesting block is TNT! To place a normal TNT block use:

1 tnt = 46
2 mc.setBlock(x, y, z, tnt)

However, this TNT block is fairly boring. Try applying data as 1:

1 tnt = 46
2 mc.setBlock(x, y, z, tnt, 1)

Now use your sword and left click the TNT block: it will be activated and will explode in a matter
of seconds!
Now try making a big cube of TNT blocks!

1 tnt = 46
2 mc.setBlocks(x+1, y+1, z+1, x+11, y+11, z+11, tnt, 1)
Chapter 8 - Minecraft: Pi Edition 90

Now you’ll see a big cube full of TNT blocks. Go and activate one of the blocks and then run away
to watch the show! It’ll be really slow to render the graphics as so many things are changing at once.
Chapter 8 - Minecraft: Pi Edition 91

Fun with flowing lava.


One block that’s a lot of fun to play with is flowing lava.

1 from mcpi.minecraft import Minecraft


2
3 mc = Minecraft.create()
4
5 x, y, z = mc.player.getPos()
6
7 lava = 10
8
9 mc.setBlock(x+3, y+3, z, lava)

Find the block you’ve just placed, and you should see lava flowing from the block to the ground.
The cool thing about lava is that when it cools down it becomes rock. Move to another location in
your world and try this:

1 from mcpi.minecraft import Minecraft


2 from time import sleep
3
4 mc = Minecraft.create()
5
6 x, y, z = mc.player.getPos()
7
8 lava = 10
9 water = 8
10 air = 0
11
12 mc.setBlock(x+3, y+3, z, lava)
13 sleep(20)
14 mc.setBlock(x+3,y+5, z, water)
15 sleep(4)
16 mc.setBlock(x+3, y+5, z, air)

You can adjust the sleep parameters to allow more or less lava to flow.
Chapter 8 - Minecraft: Pi Edition 92

lava

Project # 2 - Whac-a-Block Game


Create a “Whack-a-Block” Game with Minecraft: Pi Edition by the Raspberry Pi Foundation is
licensed under a Creative Commons Attribution 4.0 International Licence
The game you are going to create is called “Whac-a-Block”, inspired by the original arcade game
“Whac-a-Mole”. The objective of the game is to whack (or hit with a sword) the blocks that light
up as glowstone, and turn them back to stone. You will earn points for each block you turn back to
stone and the game is over when all the blocks have been turned into glowstone.
Chapter 8 - Minecraft: Pi Edition 93

Minecraft Whac-a-Block

This project is split into five parts.

1. Create the program: starting your Minecraft Python program and making sure everything is
working.
2. Build the game board: creating the code which will make game board appear in front of the
player.
3. Turn the blocks on: coding the functions to turn the blocks randomly into glowstone.
4. Whack blocks: turn the blocks back to stone when the player hits them.
5. Game over: how many points did you score?

Create the program


Boot you Raspberry Pi and from the menu select Python 3 (IDLE) from the Programming section.
When the Python shell appears, create a new program using File > New Window. You may also want
to save your program now using File > Save.
Import the Python libraries you are going to need for this program:
Chapter 8 - Minecraft: Pi Edition 94

1 import mcpi.minecraft as minecraft


2 import mcpi.block as block
3 import random
4 import time

• mcpi.minecraft is needed to interact with Minecraft: Pi Edition


• mcpi.block is needed to refer to blocks by name rather than ID
• random is used to create random numbers
• time is used to put delays into your program

Create a connection to Minecraft: Pi Edition and post a message to the chat window:

1 mc = minecraft.Minecraft.create()
2 mc.postToChat("Minecraft Whac-a-Block")

You can run the program now. It won’t do much, but if everything is set up correctly you should see
“Minecraft Whac-a-Block” displayed in the Minecraft chat window.

Message in Minecraft chat window

If you haven’t done so already, start up Minecraft and create/open a world. Run your program by
clicking Run > Run Module in IDLE or by pressing F5. Any errors will appear in red in the Python
shell window.
Chapter 8 - Minecraft: Pi Edition 95

Build the game board


The next step is to create the game board; this consists of 3x3 stone blocks, which will randomly
turn into glowstone and light up.
The game board will be created just in front of the player, so the first step is to get the player’s
position using player.getTilePos():

1 pos = mc.player.getTilePos()

The player’s position is then used with the setBlocks() function to create the game board out of
stone:

1 mc.setBlocks(pos.x - 1, pos.y, pos.z + 3,


2 pos.x + 1, pos.y + 2, pos.z + 3,
3 block.STONE.id)

Whac-a-block game board

To give the player a warning that the game is about to start, post a couple of messages to the chat
window and put a delay into the program using time.sleep(seconds):
Chapter 8 - Minecraft: Pi Edition 96

1 mc.postToChat("Get ready ...")


2 time.sleep(2)
3 mc.postToChat("Go")

Run the program again. You should see the game board appear directly in front of the player, and
the messages “Get ready …” and “Go”.

Turn the blocks on


Next, you are going to create the code which will turn the stone blocks to glowstone and light them
up. The blocks will turn on randomly; you will use the random.randint(start, end) function to
pick the random block on the game board.
Create a variable called blocksLit; this will hold the number of blocks which are currently lit (i.e.
turned into glowstone). Next, create a variable called points which will hold how many points the
player has scored. As it’s the start of the game, set them both to 0:

1 blocksLit = 0
2 points = 0

Your program will need to loop until the game is over, or in this case until all the blocks are lit.
Create a while loop which will continue until the blocksLit variable is 9 (i.e. all the blocks are
turned to glowstone). Next, put a small delay of 0.2 seconds into the program; otherwise it will run
so fast, you won’t be able to whack any blocks!

1 while blocksLit < 9:


2 time.sleep(0.2)

From now on, the code will be indented under this while loop.
The next step is to randomly turn a block into glowstone. This is more difficult than it sounds: what
happens if the block you randomly choose is already glowstone? Your code needs to be able to deal
with this.
The method you will use is a really simple one. The code creates a random position, checks to see if
that block is stone, and if it isn’t (i.e. it’s glowstone), it tries again and creates a new random position.
The code will continue to do this until it finds a block which is still unlit.
Create a variable called lightCreated then set it to False; next, create a while loop which will
continue until lightCreated is set to True. You should also increase the number of blocksLit by 1,
to show that another block will be lit:
Chapter 8 - Minecraft: Pi Edition 97

1 blocksLit = blocksLit + 1
2 lightCreated = False
3 while not lightCreated:

Once a block is successfully turned to glowstone, lightCreated will be set to True and the loop will
exit.
Inside this loop use random.randint(start, end) to create a random x (between -1 and 1) and y
(between 0 and 2) position on the game board:

1 xPos = pos.x + random.randint(-1,1)


2 yPos = pos.y + random.randint(0,2)
3 zPos = pos.z + 3

A random block lit up

Use getBlock(x,y,z) and an if statement to check if the block at the random position is STONE.
If it is, set it to glowstone using setBlock(x,y,z,blockId) and make lightCreated = True; if this
is not changed, the code will go back to the start of the loop and find another random position.

1 if mc.getBlock(xPos, yPos, zPos) == block.STONE.id:


2 mc.setBlock(xPos, yPos, zPos, block.GLOWSTONE_BLOCK.id)
3 lightCreated = True
Chapter 8 - Minecraft: Pi Edition 98

Note: Rather than using the ID numbers of blocks (e.g. stone = 1, glowstone = 89), you can use the
block module, which holds all the block IDs and their names (e.g. block.STONE.id).
Run the program by clicking Run > Run Module in IDLE or by pressing F5; you should see the game
board appear. The stone blocks should then, one by one, turn into glowstone and the program should
end when all nine are lit.

Whack blocks
The player will whack blocks by hitting them (right-clicking) while holding a sword. The Minecraft
API has functions which allow you to find out what blocks were hit; these are known as block
hit events. Using the function events.pollBlockHits() you can get a list of the events that have
occurred since it was last called, such as blocks which were hit.
You will use events to find out the position of the block which was hit, before using getBlock(x,y,z)
to see if the block hit was glowstone. If it was, you will then use setBlock(x,y,z,blockId) to turn
it back to stone, before reducing the number of blocks lit and increasing the player’s score.
Indented under the while blocksLit < 9 loop, create the following code to loop through the block
hit events list:

1 for hitBlock in mc.events.pollBlockHits():

Note: The hitBlock variable holds the event which has happened. It contains lots of information,
including which block was hit, what face was hit and who hit it. You can see this information in the
Python shell by using print hitBlock.
Use getBlock(x,y,z), the hitBlock event data and an if statement to see if the block hit was
glowstone. If it was, use setBlock(x,y,z,blockId) to set it back to stone before reducing the
blocksLit variable and adding 1 to the player’s points:

1 if mc.getBlock(hitBlock.pos.x, hitBlock.pos.y, hitBlock.pos.z) == block.\


2 GLOWSTONE_BLOCK.id:
3 mc.setBlock(hitBlock.pos.x, hitBlock.pos.y, hitBlock.pos.z, block.ST\
4 ONE.id)
5 blocksLit = blocksLit - 1
6 points = points + 1

Run the program. The game board should appear and this time when the blocks are lit, if you hit
them by right-clicking with a sword, they should turn off.

Game over
The last step in the game is to let the player know it’s “Game Over” and to tell them how many
points they scored. The very last line of the program should be:
Chapter 8 - Minecraft: Pi Edition 99

1 mc.postToChat("Game Over - points = " + str(points))

Game over

What next?
At the moment the gameplay is pretty simple, and there’s a lot you can do, now you have the basic
program set up, to make it your own. Here are some ideas to get you started:

1. The difficulty of the game is set by the how long the program waits before lighting another
block, currently time.sleep(0.2). By increasing this time you make the game easier, and
decreasing it will make the game harder. Experiment and see what works best for you.
2. What if the player gets things wrong and hits a stone block instead of a glowstone block? Can
you change the program so that if the player hits a stone block, it lights the block? This forces
the player to think more about what block they are hitting and increases the skill required.
3. It is common for video games to start easy and get harder. Can you make the game start easier
and the more points you score, the harder it gets?

API reference
For more extensive documentation of functions, and a full list of block IDs, see an API reference at
stuffaboutcode.com.
Chapter 9 - Curriculum Connections
“You cannot think about thinking, without thinking about thinking about something.”
–Seymour Papert

A Model for Maker Education


The projects you have seen in previous chapters could be thought as “one-offs”. Although you may
find ways to incorporate them into a project-based learning (PBL) unit, the intention was to show
some quick, engaging projects you and your students can use to get started straight away.
In the introduction I briefly discussed constructionism, its relationship to the maker movement, and
how the Raspberry Pi fits in accordingly. In this chapter, I would like to highlight how this model of
learning can be applied in your classroom using the Raspberry Pi computer. Building, thinking, and
creating projects with the Raspberry Pi is constructionism in action. To provide more context, let’s
briefly look at constructionism in a little more detail.

Constructionism
Constructionism is a theory of learning developed by Seymour Papert. Constructionism states
we “learn by doing”, actively creating knowledge from first hand experiences through the use of
play, experimentation, and exploration.¹⁹ Optimal learning takes place not when the instructor is
dictating the knowledge to the learner, i.e. lecture, rather when the learner actively develops content
knowledge as she completes a project or active task. Constructionism also emphasizes student choice
and self-determination. As educators we know this is how most students learn best. We know
students want to feel engaged and invested in their learning. If they feel they are simply doing the
work for someone else, namely their teacher, they tend to either just do it because they have to in
order to get the grade they ultimately desire, or they simply choose not to do it at all. Papert believed
learning takes place best in context, is relevant to the learner, and is optimally obtained when
working within a community of other learners engaged in the same mental and physical activities.
Papert believed technology can be used to facilitate this type of learning in the classroom.²⁰ When
students are building a project with the Raspberry Pi they are actively creating and thinking about
how to solve a problem, answer a question, or fill a need. In short, they are engaged in constructionist
learning.
¹⁹http://fablearn.stanford.edu/fellows/blog/constructionism-learning-theory-and-model-maker-education
²⁰http://en.wikipedia.org/wiki/Constructionism_(learning_theory)
Chapter 9 - Curriculum Connections 101

To learn more about Seymour Papert, constructionism, and his influence on educational
technology watch this I> TEDx talk by Dr. Gary Stager - Seymour Papert – Inventor of
everything

From Theory to Practice


When this context in mind, let’s explore some examples of where the Raspberry Pi can connect to
curriculum. The Raspberry Pi was designed as a cross-curricular instructional tool. The Raspberry
Pi really shines when students find ways to incorporate it into interdisciplinary projects. There
is tremendous value in having students use physical tools, like the Raspberry Pi, to discover
the interdependence of knowledge from various disciplines. Students begin to see the world as
something they can change and manipulate. Encourage your students to adopt a DIT (“Do-It-
Together”) work ethic when working with the Raspberry Pi - where one student becomes the
designer, one the engineer, one the programmer, one the project lead, and one the evaluator. The
Raspberry Pi provides a platform for this type of exploration, from science and engineering to the
humanities and creative expression. I think you will find connections between what you teach and
this tool once you put it in the hands of your students and let them build, think, and create. Most
importantly, do not be afraid to experiment with the Raspberry Pi and ask your students how they see
small-scale computers, like the Raspberry Pi, playing a role in their future lives. From smart phones
and smart cars to nanotechnology and the “quantified-self”, small-scale, embedded computing will
most likely play a significant role in many of their future careers - see Internet of Things (IoT)
projects in the next chapter for more on this.

Instructional Design Philosophy


When designing learning experiences for my students I try to keep these three broad instructional
design philosophies in mind:

• Provide students with tools and technologies to empower them to build and discover a digital
space of their own
• Provide students with curricular opportunities to use technology in meaningful and impactful
ways
• Push students to understand how technology works and how it (and more importantly will)
impact their lives

That said, the projects listed below may not fulfill all these requirements with your students. These
are simply examples of projects that I - or other educators - have found to be impactful with students.
Your experiences my vary. I encourage you to contribute to the Raspberry Pi Foundation Education
Forum with your own projects.
Chapter 9 - Curriculum Connections 102

Classroom Projects
Infrared Bird Box - Students build a bird box, setup a camera, and observe the nesting/breeding
habits of local bird population.
Students will learn:

• How to set up up a Raspberry Pi with an infrared camera module


• How to connect an infrared LED to a Raspberry Pi
• How to control the camera and LED to see what is happening inside the bird box
• Nesting habits of local bird population
• Light spectrum
• Basic electronics
• Computational thinking
• Technical and/or narrative writing through student-generated written (or video) tutorials

Raspberry Pi Weather Station - Students build a weather station, collect data using various simple
sensors, and analyze the data through the use of a spreadsheet application.
Students will learn:

• How to connect and use sensors with the Raspberry Pi


• Data collection
• Data analysis
• Spreadsheet skills
• Basic electronics
• Computational thinking
• Technical and/or narrative writing through student-generated written (or video) tutorials

Astro Pi Flight Analysis - Students explore data collected from two Raspberry Pis located on the
International Space Station.
Students will learn:

• Data analysis
• Data anomaly detection
• Computational thinking (abstraction, pattern recognition)
• Spreadsheet skills
• Technical and/or narrative writing through student-generated written (or video) tutorials
Chapter 9 - Curriculum Connections 103

Sensing Science - Students will investigate various concepts from Physics, Chemistry and Biology,
using a Raspberry Pi and a Sense HAT.
Students will learn:

• How to collect reaction times to calculate rates of reactions


• How concentration and temperature affect the rate of chemical reaction
• That heat can be transferred by hot objects emitting IR radiation
• That the transfer of heat can be stopped by an insulator
• What the products of aerobic respiration are
• That the stopping distance of a car is affected by both the thinking distance and braking
distance
• Technical and/or narrative writing through student-generated written (or video) tutorials
• … and much more!

Code with a Free Sense HAT in Your Browser - As mentioned previously, the Sense HAT is a must-
have for the classroom. When paired with the Raspberry Pi and an easy-to-use Python library, the
Sense HAT is a great way for students to learn about data collection, data analysis, and computer
programming. If you want to try the Sense HAT before you have purchased one, you can practice
using this online simulation thanks to the great folks at the Raspberry Pi Foundation and Trinket. A
variety of engaging projects are provided including “Rock, Paper, Pi” and “Flappy Pi”.
Even better, you can use a virtual Sense Hat on your actual Raspberry Pi. This Sense HAT emulator
is designed to run natively on your Raspberry Pi desktop, instead of inside a browser. Developed by
Dave Jones, it’s intended for people who own a Raspberry Pi but not a Sense HAT. In the picture
below, the sliders are used to change the values reported by the sensors while your code is running.
Learn more - http://www.raspberrypi.org/blog/desktop-sense-hat-emulator/
Chapter 9 - Curriculum Connections 104

Virtual Sense HAT

Students will learn:

• Computational thinking
• Computer programming
• Solving multi-step problems
• Technical and/or narrative writing through student-generated written (or video) tutorials

Mathematica - Mathematica is a computer program for doing mathematics, technical computing,


science and engineering. It is often used for instruction, homework, research, and academic writing.
Mathematica is extraordinary well-rounded. It is usually very expensive to purchase and hard to
install on many computers. The Raspberry Pi comes with a a free version of Mathematica pre-
installed! With Mathematica on the Raspberry Pi, students can upload and analyze sensor data for
a classroom project or use Mathematica like you would on a laptop. Students studying algebra,
calculus, statistics, or applied mathematics will find great value in Mathematica. If is widely used in
many institutions of higher learning. Students that learn Mathematica on the Raspberry Pi will be
well prepared for more advanced mathematics courses and/or more attractive to college admission
departments.
Students will learn:

• Computational thinking
Chapter 9 - Curriculum Connections 105

• Intermediate/advanced mathematics
• Statistical modeling and analysis
• Problem-solving and problem modeling

RACHEL-Pi - The RACHEL Project is an amazingly cool project to provide free copies of educational
websites for download without the use of the internet. This is a great project to provide rich, curated
educational content free of charge to areas of the world where internet access is not possible or
unstable.
RACHEL servers include copies of educational websites as they existed in the recent past. By storing
copies of websites directly on RACHEL devices, no internet is required and there are no monthly
subscription costs.
When a RACHEL server is turned on, a RACHEL server emits a wireless signal that only provides
access to the copies of websites stored directly on the RACHEL device. Any device with a web
browser (a laptop, desktop, tablet, or smartphone) can connect to RACHEL’s wireless signal.

To see what the interface looks like for the users of the RACHEL-Pi project visit RACHEL-
Pi Project Preview. Educational content providers include: TED, Project Gutenberg, Khan
Academy, Wikipedia, PhET Interactive Simulations, AfricanStorybook.org, and CK-12,
among many others.

Students will setup a Raspberry Pi with a SD-card preloaded with the educational content. They
learn how to implement a local area network (LAN) using a cheap, off-the-shelf router to broadcast
the content. Users then use a computer, tablet, or smartphone to access the free educational content
via a web-browser, without any internet access needed.
Students will learn:

• Computer system administration


• Computer networking
• Global cultural studies
• Civics and Economics
• Technical and/or narrative writing through student-generated written (or video) tutorials

Non-traditional uses
Integrating technology into the English/Language-arts classroom is a topic so vast it deserves a
separate book. One way to use the Raspberry Pi to encourage writing is through the use of student-
generated tutorials and/or instruction manuals. I will often have my students bring a technical guide
as part of their culminating activity for a project. The English Language Arts Common Core State
Standards place special emphasis on technical or non-fiction reading and writing across all grade
Chapter 9 - Curriculum Connections 106

levels. Often activities designed around these standards are simply not engaging for students. The
Raspberry Pi computer can be a tool you use to get your students excited about writing again!
I am particularly interested in how the Raspberry Pi can be used as part of digital storytelling or
non-linear storytelling. One educator who is engaged in interesting work with literature and the
Raspberry Pi is Sarah Roman.
Some sample projects in Sarah’s high school language arts classroom:
Creating book-based video games using the Raspberry Pi and Scratch
Zork Meets King Lear: A Classic 80s Shakespearean Text Adventure
Learn more about Sarah’s work on Twitter @A_BildungSROMAN or www.abildungsroman.com
Chapter 10 - Going Further
“Prepare for what is difficult when it is easy”
–Lao Tzu

Internet of Things (IoT) - Connect the Raspberry Pi to the


World!
The Internet of Things (IoT) is the idea of connecting any device with an on/off switch to another
device, or network of devices, in order to increase its utility. Many believe, myself included, IoT will
have a transforming effect on educational technology. An increasing number of students will be
engaged in learning outside of the classroom while remaining connected. Not only will students use
IoT devices, they will be making them! The Raspberry Pi is a great platform to start building simple
IoT systems with your students.

Fridge Monitor
This is a great beginner IoT project using the Raspberry Pi and the If This Then That (IFTTT) website.
Using a simple light sensor, or photoresistor, the Raspberry Pi is programmed to monitor the light
level of the refrigerator. When the open is opened (the light level is high), an email, text, tweet or
Facebook message will be sent (using IFTTT) to your phone telling you the time the fridge door was
opened. Brilliant and simple to make!

IFTTT is a free web-based service that allows users to create chains of simple conditional
statements, called “recipes”, which are triggered based on changes to other web services such as
Gmail, Facebook, Instagram, and Pinterest. IFTTT is an abbreviation of “If This Then That”. IFTTT
can also be set up to work with physical events, such as your fridge door opening.

Learn how –> Raspberry Pi Fridge Monitor

Make Your Own Amazon Echo


The Amazon Echo is a hands-free speaker you control with your voice. Echo connects to the Alexa
Voice Service to play music, provide information, news, sports scores, weather, and more. It is similar
Chapter 10 - Going Further 108

to Apple’s Siri, Google’s Now, or Microsoft’s Cortana technology. The retail version of the Amazon
Echo costs $179. You and your students can turn your Raspberry Pi into your own personal assistant
using the Amazon Echo Alexa voice service. This is a fun project but there are MANY steps. Be
patient, take your time, and learn lots along the way!
Tutorial from: The Raspberry Pi Guy

You will need the following:

• A Raspberry Pi (B+,A+,Pi 2,Pi 3,Pi Zero) connected to the internet - Note: You MUST have
an internet connection for this project.
• An SD Card with the Raspbian operating system
• An External Speaker with 3.5mm Jack
• A USB Microphone Note: Make sure the mic is “plug-and-play” for Linux. I used this
one.
• The Raspberry Pi SenseHat

Installation

1. Open the Terminal application


2. Find your Raspberry Pi IP address via the ifconfig terminal command
3. Download the code with the command: git clone https://github.com/the-raspberry-pi-
guy/Artificial-Intelligence-Pi
4. Change into the new directory: cd Artificial-Intelligence-Pi
5. In a web browser on a separate computer, go to developer.amazon.com and login with an
existing Amazon account or create a new one
6. Fill in basic information, accept the Terms and Conditions, and answer “No” to the two
questions about monetization.
7. Click “Alexa” at the top, then choose “Alexa Voice Service”
8. Click “Register a Product Type” and choose “Device”
9. Fill in “Device Type ID” and “Display Name” with “RaspberryPiAI” for both. Click “Next”.
10. Click “Select Security Profile”, then click “Create a new profile”
11. Fill in “Security Profile Name” and “Security Profile Description” with “RaspberryPiAI” for
both. Click “Next”.
12. Click “Web Settings”, then Click “Edit”
13. In the “Allowed Origins” field, type “http://localhost:5000”, Click “Add Another”, type “http://your-
ip-address:5000” (Note: your-ip-address should be the ip address you found when typing
the ifconfig command from Step 1)
14. In the “Allowed Return URLs” field, “http://localhost:5000/code”, Click “Add Another”, type
“http://your-ip-address:5000/code” (Note: your-ip-address should be the ip address you
found when typing the ifconfig command from Step 1)
15. Click “Next”
Chapter 10 - Going Further 109

16. More info!: Under “Category” choose “Other”, under “Description” type “RaspberryPiAI”, for
“..expected timeline for commericalization”, choose TBD, and for “…number of devices” type
“1”
17. Click “Next”
18. You should now see your registered “RaspberryPiAI” device listed. Click “Edit” under Actions
and on the left click “Security Profile”. You will need to copy/paste these settings next.
19. On the Raspberry Pi make sure the microphone and speaker are connected and you are at the
terminal.
20. Run the setup script: sudo ./setup.sh
21. Use the settings from Step 17 to complete the setup process.

Finally!

Run Alexa Voice service: sudo python main.py


Watch this excellent video - link here - to get a step-by-step video tutorial of the process.

Node-RED - IoT Made Easy


Node-RED is a tool for wiring together hardware devices, APIs and online services in new and
interesting ways. Node-Red in its simplest form is an open source visual editor for wiring the internet
of things produced by IBM. What does this mean? Basically, it allows you to have more time making
stuff “talk” to each other rather than worrying about all of the interfacing code you would otherwise
have to write.
Node-RED comes pre-installed on Raspbian.
Learn more - Node-RED

Thingbox

The ThingBox is a set of software already installed and configured for IoT projects on the Raspberry
Pi. The ThingBox allows anyone to graphically create new unlimited applications interacting with
connected objects from a simple web-browser.
Learn more - The Thingbox Project

Google Coder - A simple way to make “web stuff” on


Raspberry Pi
Coder is a free piece of software that turns a Raspberry Pi into a simple platform that educators can
use to teach the basics of building for the web. New coders can craft small projects in HTML, CSS,
and Javascript, right from the web browser. Coder requires a fresh (or be willing to erase our current)
Chapter 10 - Going Further 110

SD card. Basically, you have to download their version of the Raspberry Pi operating system. They
have customized it to run a web server and changed many settings to make it MUCH easier to setup
your Raspberry Pi as a web development device.
Learn more - googlecreativelab.github.io/coder/

PiNet - Centralized user accounts and file storage for the


classroom
PiNet is a simple, free and easy-to-use system for schools that allows teachers to manage their
Raspberry Pis more easily. The students user accounts are stored on the central PiNet server. This
means they can log in on any Raspberry Pi in the classroom and you do not have to figure out which
SD card belongs to which student. Additionally, PiNet has easy to setup shared folders for sharing
resources with students along with automated backups of student work to an external drive.
Learn more - PiNet.org.uk

Resources to Explore
Websites:

• Raspberry Pi Foundation
• Raspberry Pi Foundation - Educator Resources
• Raspberry Pi Foundation Education Forum
• Adafruit Industries

Books:

• Hello Raspberry Pi
• Adventures in Raspberry Pi
• Getting Started with Raspberry Pi
• Raspberry Pi Projects for Kids
• Instant Minecraft: Pi Edition Coding How-to

Free Guides:

• MagPi Educator’s Edition #1 *


• MagPi Educator’s Edition #2
• The Raspberry Pi Projects Book #1
Chapter 10 - Going Further 111

• The MagPi Magazine


• Experiment with the Sense Hat
• Make Games with Python
• Code Music with Sonic Pi
• Learn to Code with Scratch
• Hacking and Making in Minecraft
• Simple Electronics with GPIO Zero

Education Newsletter
Sign up to the Raspberry Pi Foundation Education email newsletter for updates on future profes-
sional development, new resources, and competition announcements:
Education Newsletter

Closing Thoughts
I hope you have found this book useful. The Raspberry Pi community is full of many helpful people
willing to share their projects, ideas, tips, tutorials, etc. My hope is that I have contributed to this
community in some small way. If you have success and find something that works for you and
your students, please share it in the Raspberry Pi Foundation Education Forum. Join the Raspberry
Pi community and become an active part of the maker community. I think you will find it to be a
valuable part of your professional learning network.
Thank for you reading and keep making!
Michael C. Renne
Appendix A - Headless Mode via SSH
and VNC
Headless Mode
Sometimes it is not convenient to work directly on the Raspberry Pi. You can work on it from
another computer by remote control in what is called “headless mode”. Operating your Raspberry
Pi in headless mode may be a good option for your classroom. Headless mode simply means
your Raspberry Pi will not have a monitor, keyboard, or mouse attached to it. You will use two
technologies - SSH and VNC - to connect to your Raspberry Pi via the network.

To use headless mode, you must be connected to a network, preferably via a “hard-
wired” (or ethernet/LAN) connection. Consult your school/district IT staff to connect your
Raspberry Pi to the school network. Be aware sometimes technologies such as SSH and
VNC may be “blocked” for security reasons.

SSH stands for Secure SHell. This technology allows you to securely connect to other devices via a
network. It sounds daunting, but the Raspberry Pi makes the process fairly straight forward.
VNC stands for Virtual Network Computing. This technology is a graphical desktop sharing system
that allows you to remotely control the desktop interface of one computer from another. It transmits
the keyboard and mouse events from the controller, and receives updates to the screen over the
network from the remote host. VNC is great because you will see the desktop of the Raspberry Pi
inside a window on your host computer - be it a Windows or Mac computer. You’ll be able to control
it as though you were working on the Raspberry Pi itself.

Turn on SSH
Type the command sudo raspi-config and navigate to the menus below. Save and reboot.
Appendix A - Headless Mode via SSH and VNC 113

Raspberry Pi Configuration
Appendix A - Headless Mode via SSH and VNC 114

Turn on SSH

After a reboot, type ifconfig in the terminal application to find your IP address. You will need this
to connect to your Raspberry Pi via SSH and VNC.

Downloading PuTTY
You will need a program on your Windows PC/laptop to connect to your Raspberry Pi via SSH.
We will use a program called PuTTY. It’s free and allows you to connect to your Pi through SSH.
Download PuTTY
Once you have downloaded PuTTY and installed it, type your IP address into PuTTY and click Open.
Appendix A - Headless Mode via SSH and VNC 115

Type IP address

Now type your login and password (default login is: pi and the default password is: raspberry).
Appendix A - Headless Mode via SSH and VNC 116

Type IP address

Congratulations! You have just connected to your Raspberry Pi from another computer via SSH!

Install VNC
• On your Pi (using a monitor or via SSH), install the TightVNC package:

1 sudo apt-get install tightvncserver

• Next, run TightVNC Server which will prompt you to enter a password and an optional view-
only password:

1 tightvncserver

• Start a VNC server from the terminal: This example starts a session on VNC display one (:1)
with full HD resolution:

1 vncserver :1 -geometry 1920x1080 -depth 24

Note that since by default an X session is started on display zero, you will get an error in case
you use :0.
• Since there are now two X sessions running, which would normally be a waste of resources,
it is suggested to stop the displaymanager running on :0 using
Appendix A - Headless Mode via SSH and VNC 117

1 service lightdm stop

• Now, on your computer, install and run the VNC client:


– On a Linux machine install the package xtightvncviewer:
1 sudo apt-get install xtightvncviewer

– Otherwise, TightVNC is downloadable from tightvnc.com

Start VNC
You can create a simple file with the command to run the VNC server on the Pi, to save having to
remember it:

• Create a file containing the following shell script:

1 #!/bin/sh
2 vncserver :1 -geometry 1920x1080 -depth 24 -dpi 96

• Save this as vnc.sh (for example)


• Make the file executable:

1 chmod +x vnc.sh

• Then you can run it at any time with:

1 ./vnc.sh

Connecting to a Pi over VNC using Windows


On Windows you’ll need to download and install a VNC client program. A commonly used one is
TightVNC which can be downloaded from tightvnc.com
Choose either the 32 or 64 bit download depending on which version of Windows you are using. If
you don’t know then check by looking at System in Control Panel. Download the installer file and
run it.
During installation you’ll be offered the choice of Typical, Custom or Complete. You only need the
VNC client and not the server, so choose Custom. Then select TightVNC Server and choose Entire
feature will be unavailable. Click Next. Uncheck the option about Windows Firewall and click
Next again, then Install.
Appendix A - Headless Mode via SSH and VNC 118

TightVNC Windows installation

Once the installation is complete you should find TightVNC Viewer under the start menu. When
you run it you’ll be presented with the dialog below. You will need to enter the IP address of the
Raspberry Pi followed by the screen number (:0 or :1). For example: 192.168.0.6:1
Appendix A - Headless Mode via SSH and VNC 119

TightVNC connection dialog

Click the Connect button and you will be prompted for the password that was specified when
configuring the VNC server on the Raspberry Pi earlier. You should then find yourself at the
Raspberry Pi desktop.
Appendix A - Headless Mode via SSH and VNC 120

Raspberry Pi desktop

This article uses content from the eLinux wiki page RPi VNC server, which is shared under the
Creative Commons Attribution-ShareAlike 3.0 Unported license
Glossary
abstraction - a technique for managing complexities in a given system; in computer science/engi-
neering it is used as a method of suppressing the more complex details below the current level the
user is working on; the operating system on a Raspberry Pi (Raspbian/Linux) abstracts the command
line interface from the user
application programming interface (API) - a set of rules that govern how one application can talk
to other application via a computer programming language.
cd - change directory Linux terminal command
command-line - another name for the terminal; an interface in which you can type and execute
text based commands
computational thinking - a problem solving approach that includes a number of characteristics
that can be used to support problem solving across all subject areas including math, language arts,
social studies, and science.
conditional - another name for an if statement
data validation - the process of ensuring that a program operates on clean, correct and useful data
debugging - finding and removing errors/mistakes in a computer program
Do-It-Together (DIT) - as opposed to Do-It-Yourself (DIY), this idea encourages people to work
together to solve problems
function - a named section of a computer program that performs a specific task
General-Purpose Input/Output (GPIO) - a generic pin on an integrated circuit whose behav-
ior—including whether it is an input or output pin—is controllable by the user at run time
graphical user interface (GUI) - a type of interface that allows users to interact with the Raspberry
Pi through graphical icons and visual indicators, as opposed to text-based interfaces, like the
command line
headless mode - a type of computer setup where you do not need a mouse, monitor, or keyboard
attached to the system
high-level language - a computer programming language that isn’t limited by the computer,
designed for a specific job, and is easier to understand. It is more like human language and less
like machine language. However, for a computer to understand and run a program created with a
high-level language, it must be compiled into machine language.
if/else statement - check to see if a conditional is “True” or “False”
ifconfig - terminal command to find your IP address
Glossary 122

import - Python statement to load a library


infinite loop - a loop that never stops
integrated development environment (IDE) - a software suite that consolidates the basic tools
developers need to write and test software
interactive interpreter/shell - allows the user to type and run Python code interactively
Internet of Things (IoT) - refers to the ever-growing network of physical objects that feature an
IP address for internet connectivity, and the communication that occurs between these objects and
other Internet-enabled devices and systems
len - a function in Python to determine the length of a string variable
Linux - an open-source operating system used by computer enthusiasts, equivalent to Microsoft
Windows 7 or 8 or 10, Apple Mac OS X, Apple iOS, or Google Android
list - a type of variable that can hold multiple values
loop - repeat something over and over
low-level language - a programming language that provides little or no abstraction from a
computer’s instruction set architecture; also called machine code or assembly code
module - a file containing Python definitions and statements
Python - a programming language on the Raspberry Pi
Python shell - another name for the interactive interpreter; allows user to type in code and interact
with in
randint - Python function get a random integer number
Raspbian - the version of Linux designed specifically for the Raspberry Pi computer
Scratch - a graphical programming language designed for new programmers/coders
sudo - Linux terminal command allows users to run programs with the security privileges of another
user, by default the superuser. The name is a contraction of “do as su” where “su” is an abbreviation
for “super user.”
syntax - the set of rules that define the combinations of symbols that are considered to be correctly
structured programs in that language
terminal - an interface in which you can type and execute text based commands
variable - a place in the computer’s memory to store data

You might also like