Home IoT & Hardware Wearable-Tech Projects with the Raspberry Pi Zero

Wearable-Tech Projects with the Raspberry Pi Zero

By Jon Witts
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    About the Raspberry Pi
About this book
With Wearable-Tech Projects with the Raspberry Pi Zero, you will begin with learning how to install the required software for your upcoming projects. You will also learn how to control electronic devices with the GPIOZero Python library. Next, you will be creating some stylish wearable-tech projects such as a motion-reactive LED cap and a Tweet-activated LED T-shirt. Toward the end of the book, you will be creating some useful health and fitness wearable-tech projects; these will help you monitor your heart rate, track your movements with GPS, and count your footsteps with your own pedometer. By the end of the book, you will have created a range of wearable-tech projects and learned enough about your Raspberry Pi Zero that you should be able to adapt these projects further or come up with your own creations!
Publication date:
July 2017
Publisher
Packt
Pages
184
ISBN
9781786468819

 

About the Raspberry Pi

Throughout this book, we will be making use of the Raspberry Pi Zero computer to create our wearable-tech projects. However, before we jump straight into our first project, we should first some time getting to know the Raspberry Pi Zero computer and performing a few basic tasks, which will be useful across all of our projects. We will first look at the history of this tiny computer, and then learn how to get our software up and running, along with connecting to the GPIO headers on our computer. We will then spend some time looking at the different ways we can access our computer when it is not connected to a keyboard, mouse, or monitor and also perform some basic electronics experiments to get to know how we can use the GPIO pins in our upcoming projects.

So, let's get started!

 

What we will cover

In this chapter, we will cover the following topics:

  • The history of the Raspberry Pi Zero
  • The parts we will need to complete this chapter
  • Installing our operating system onto our Pi Zero
  • Different ways of connecting to our GPIO headers on our PI Zero
  • Accessing our Pi Zero in headless mode
  • Creating a very basic electronics project to familiarize ourselves with using GPIO pins on our Pi
 

A little history

Raspberry Pi Foundation launched the Raspberry Pi Zero on 26th November 2015, taking the IT world by surprise by releasing it secretly at a price of just $5, along with including a free Raspberry Pi Zero for those who were lucky enough to get a copy of that month's MagPie magazine. Needless to say, these tiny computers sold out quickly and, to this day, customers are still limited to purchasing just one device per order from the suppliers who stock them.

In April 2016, a new version of the Pi Zero was launched; a camera port was added to this model, enabling enthusiasts to build super small camera projects and hacks using their Raspberry Pi Zero computers.

The newest and latest version of Raspberry Pi Zero is Pi Zero W. It adds to the second generation of Pi Zero by now including the same Wi-Fi and Bluetooth on-board chip, which was introduced on Pi 3. This makes Pi Zero W a great choice of computer for our projects in this book; it has enough power to deliver what we want, and GPIO pins allow us to connect to and control all manner of devices (as we will see!); and we now have a means to connect to this computer, while it is hidden away in a piece of clothing!

With this in mind, I will be making use of Pi Zero W for all of the projects in this book. If you cannot get your hands on one, don't worry; all these projects will work fine with any Raspberry Pi computer from the model B+ upwards.

 

The bill of parts

We will make use of the following things in this project:

  • A Pi Zero W computer
  • A micro SD card (8 GB minimum)
  • A GPIO header set (optional)
  • Another computer or a laptop with an SD card writer
  • Internet access
  • A soldering iron and solder
  • Some Blu-Tack (or similar substance)
  • One red and one green 5 mm LED
  • Two 330 Ω resistors
  • A push type button
  • Some red and black sheathed cable
 

Installing our software

Throughout all the projects of this book, we are going to make use of the Raspbian operating system. More specifically, we will be using the Jessie Lite version of this operating system. Raspbian is the foundation's officially supported operating system and the one for which there is most community support for. It is derived from the Debian Linux operating system; so if you have used that or any of its derivatives (like Ubuntu) before, you should feel at home with Raspbian. I have decided to go with the Jessie Lite version of Raspbian for a couple of reasons:

  1. All of our projects will run headless (without a monitor, keyboard, or mouse), so why have a display manager use up our resources?
  2. The lower footprint of this operating system, in terms of memory and storage usage, will give us access to more of the computer's resources to use for our projects.

So, head over to https://www.raspberrypi.org/downloads/raspbian/ and download the latest version of the Jessie Lite operating system. Once this ZIP archive is downloaded on your computer, you will need to copy it onto your micro SD card.

Using Etcher to copy our image

Until recently, there was a different way to copy an image file to an SD card in every different operating system; the open source piece of software, Etcher, sets out to solve this problem. Etcher is freely available for pretty much all operating systems, so we only need to document one process for all operating systems rather than detailing a different method for each OS. Etcher will run on any operating system that can run Electron. You can check the full list of supported operating systems for Electron on their website at http://electron.atom.io/docs/tutorial/supported-platforms/.

Etcher is only supported in macOS version 10.9 and higher, so if you are running a lower version of macOS, you can find other ways to install the image file on your SD card over on the Raspberry Pi site at https://www.raspberrypi.org/documentation/installation/installing-images/mac.md ; you should also probably consider getting your version of macOS upgraded too!

So, to get started with Etcher, head over to their website at https://etcher.io and download the latest version for your operating system. Run the installer as per the standard method for your operating system.

Once you have Etcher installed, open it and you should be presented with a screen like the following screenshot:

Click on the blue Select image button and browse to the Jessie Lite ZIP archive you just downloaded; there is no need to extract the ZIP archive with Etcher. You will then be presented with a screen like this:

At this point, you should insert your SD card into your computer's SD card reader. Etcher should automatically detect your SD card and progress onto the third section of the process. Click on the blue Flash! button to begin the copying process, and Etcher should display something similar to this:

If you are prompted to provide administrative credentials for Etcher to flash your SD card, then enter the required credentials and allow Etcher to complete.

You will be shown a completion estimate, the percentage copied, and the transfer rate in the Etcher window. Allow Etcher to complete this; then exit the program; and remove your SD card from your computer (no need to safely remove or eject it, Etcher has done it for you!).

You have now copied Raspbian Jessie Lite to your SD card, and you're ready to move on to our next section, Connecting to the GPIO headers.

 

Connecting to GPIO headers

For many of our projects, as we will be trying to make them as small as possible, we will probably not make use of the standard GPIO headers, which you most likely received with your Pi Zero W computer. Instead, we will be soldering our cables directly into our Pi Zero W. If you prefer to just test these projects out and would like to reuse your Pi Zero W for other projects, then it will probably make sense to sacrifice a bit of space and attach the GPIO headers to your Pi Zero W. Until recently, you only had one option to do this; solder the headers to your computer! This involves a steady hand, a keen eye, and some patience. I will talk you through this, as we are going to need to solder for many of the projects in this book; so it is a valuable skill to have even if you don't use it to attach headers to your Pi Zero. If the idea of soldering 40 very closely spaced pins onto your Pi Zero fills you with dread, you now have another option; many of the online stores stocking Raspberry Pi components now stock what are known as hammer headers. These allow you t attach the 40 small pins to the GPIO pins of your Pi Zero using only a hammer; no soldering required!

Hammer headers

You can purchase new hammer headers from a number of different retailers. Both Pimoroni (https://shop.pimoroni.com) and Pi Hut (https://thepihut.com) have them listed, and both companies ship to a wide range of countries.

If you choose to use the hammer headers, please ensure that you follow all of the instructions from the supplier or you risk irreparably damaging your Raspberry Pi computer!

Solder headers

The more traditional method of attaching your GPIO headers, and the one I have always used, is to solder them to the board. As I mentioned earlier, for most of the projects, I will not attach the header blocks in this manner and will just solder directly to the board; however, this is a skill worth learning, and some of the add-on cards or hats we will be using will require us to attach the headers before we can use them.

I include this section more for completeness about setting up a Raspberry Pi Zero, but as you will see in the projects in this book, I will be soldering our components directly to the Pi Zero and not making use of header pins. If you choose to solder the headers to your Pi Zero, then you will be able to follow the projects in the book by soldering to your header pins rather than directly doing so to the Pi.

Getting your equipment ready

You will need a soldering iron, some solder, and a blob of fixative such as Blu-Tack for this. I tend to always use leaded solder, as I find that it melts quicker and gives a better solder joint than unleaded solder, but the choice is yours.

Plug your iron in and allow it to come up to temperature. Once your iron is hot enough, apply a little solder to the tip. This is known as tinning your tip, and it fills any imperfections in your iron's tip with solder. This gives a better transfer of heat between the tip of your iron and the components your are soldering.

Now, insert the header into the Pi Zero and turn it upside down so that it is resting on the header pins evenly across the length of the Pi Zero. Then, place a blob of Blu-Tack under the side of the Pi Zero opposite the header pins, just enough to hold it flat while you begin to solder the pins, as shown here:

Now, we can begin to solder the pins to the Pi Zero; we are aiming for a nice, conical solder joint that just covers the brass ring around the hole in the Pi Zero board and comes to a point at the top of the pin. Place the tip of your soldering iron so that it touches both the brass ring on the board and the metal of the pin you are soldering, but nothing else, as shown next. Leave it for a few seconds to heat both brass ring and pin, and then apply the solder to the joint. The solder should melt, and you should see it flow into the hole and cover the brass and the pin. After a few seconds, remove the solder, and then remove your iron. Leave the joint to cool for a few seconds, and then move on to the next.

I tend to work my way down one side of the header and then rotate the Pi and solder the other side. The following picture shows what a finished soldered header should look like:

 

Headless access

For all of the projects in this book, we will not be connecting directly to our Pi, as it will be installed into various different objects and will need to run without a keyboard, mouse, or monitor attached. This is known as running a computer headless. To effectively do this, we need a method to connect to our Pi remotely so that we can perform the programming we need to do without having to attach bulky devices to it. This is where Pi Zero W really comes into its own; the integrated Wi-Fi means that we can connect to the Pi over a Wi-Fi network without having to add any additional hardware.

If you are using a Raspberry Pi other than Pi Zero W or Pi 3, then you will need to add a Wi-Fi dongle to your Pi to be able to connect to it remotely. If it is a Pi Zero 1.1 or 1.3 that you are using, then you will also need a USB micro shim as shown here. You can pick these up for a few pounds from many online retailers:

There are a couple of things we will need to do to get our Raspberry Pi SD card ready for remote access; fortunately the Raspberry Pi Foundation has tried to make these as straightforward as possible for us.

Enabling SSH access

We are going to use Secure Shell (SSH) to remotely connect to our Pi. As the default password of the Raspberry Pi Raspbian OS is well known, and as more and more Internet of Things devices are being made with the Raspberry Pi computers, the decision was made by the Raspberry Pi Foundation that SSH should be disabled by default, requiring a user to select to turn it on before its first use. If you are running your Pi connected to a keyboard and monitor, then this is easily done by making use of the raspi-config utility. The Foundation has also given us a way to enable SSH for those running their Raspberry Pi computers in headless mode.

To turn on SSH for a Pi that you are going to run headless, all you need to do is create an empty file (with no file extension) named SSH on the boot partition of your Pi's SD card. When you first boot your Raspberry Pi, SSH will then be enabled and the file removed from the boot partition of the SD card. As the boot partition is a FAT32 formatted partition, it can be read from and written to by any operating system. More details can be found on the official Raspberry Pi documentation: https://www.raspberrypi.org/documentation/remote-access/ssh/

Setting up your Wi-Fi network

To be able to connect to our Raspberry Pi Zero, we are going to need a working network connection. We will be using the Pi Zero W's Wi-Fi network for this. If you are using a Pi without built-in Wi-Fi, then these instructions will still work, you will just need to connect a USB Wi-Fi dongle to your Pi first.

We have been given a straightforward method of configuring our Wi-Fi connection when using our Pi in headless mode too. If we create a file called wpa_supplicant.conf in the boot partition of our Pi's SD card, upon first boot, this file is copied into the /etc/wpa_supplicant/ directory and used to configure the Wi-Fi settings for the Pi. However, this file must contain a valid set of configuration details, or your Pi will not connect to your Wi-Fi.

Here is an example of a wpa_supplicant.conf file setup to connect to the Wi-Fi network called mywifinetwork with a connection password of mypassword. You should obviously change these to match the details of your Wi-Fi network when writing your file. You can read more about the different configurations you can add to this file over at the Raspberry Pi's official documentation pages at https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md:

network={
ssid="mywifinetwork"
psk="mypassword"
}

It is worth double checking the format and details entered here, as any mistakes in this file will stop your Pi Zero from joining your wireless network.

Connecting to your Pi

Now that we have set up SSH access and our Wi-Fi network, we can start up our Pi Zero and connect to it from another computer remotely. As we are using the Jessie Lite version of Raspbian; there is no X-server to provide a desktop, therefore VNC connections are not an option. How you connect to your Pi using SSH will depend upon which operating system you are using for your computer or laptop. Once you have established a SSH connection, the steps for each future project are the same regardless of the operating system your computer is running.

Insert your SD card you previously prepared into your Pi Zero and then connect a micro USB power supply to the port labelled PWR, as shown in the following picture. All being well, you should see the green activity LED flashing as your Pi Zero boots up for the first time.

However, before we can begin to connect, you will need to discover the IP address that your Wi-Fi network has assigned to your Pi. There are a number of different ways of doing this, and the way which works for you will largely depend upon your network. The method that I usually use at home, is to connect to my home router's web interface and view the Attached Devices page. This will be different for each router and may or may not exist! My router page looks like the next picture. By default, your Raspberry Pi will show up with the host-name of RASPBERRYPI. You can change this once you get the remote access to the Pi. If you can not find out DHCP address leases from your router in this manner, then the Raspberry Pi documentation has some other methods that you can use to find the IP address of your headless Pi at https://www.raspberrypi.org/documentation/remote-access/ip-address.md:

You can see that on my router, my Pi Zero has been assigned an IP address of 192.168.1.61. Now, we know the IP address of our Pi, we can access it from our other computer or laptop.

When connecting to a host via SSH for the first time, it is normal to be warned that the authenticity of the host can not be established. If you get this warning after you have connected to a device previously, this could indicate that your SSH connection is being intercepted, or someone has changed the SSH keys on your Pi!

SSH from Windows

To connect to your Pi Zero using SSH from the a Windows operating system, you will need to download a small tool called PuTTY. This is freely available at http://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html. Download either the 32 bit or 64 bit installer, whichever is appropriate to your Windows system, and then run the installer.

Once installed, run PuTTY and enter the IP address of your Raspberry Pi into the Host Name field and click on Open, as shown in the following screenshot:

As this is your first time connecting to your Pi Zero over SSH with this PuTTY install, you will be presented with a PuTTY Security Alert window about the server's host key not being cached. This is normal, so just click on Yes. A terminal window will then open and ask you to log in. Enter pi for the username and raspberry for the password. You will then be logged in to your Pi remotely. You can now move on to the Final setup section.

Highlighting any text with your mouse in the PuTTY terminal window copies it to your Windows clipboard, and right-clicking on the PuTTY terminal window pastes the contents of your Windows clipboard into PuTTY.

SSH from macOS

To connect to your Pi Zero using SSH from the macOS operating system, you will need to use the Terminal application. You can locate this by opening finder and going to Applications and then opening the Utilities folder. Once you have located the Terminal application, double-click on it to open it. Enter the following command to connect to your Pi Zero via SSH:

ssh pi@192.168.1.61

You need to change the IP address in this code to match the IP your Pi has been assigned. You will then be presented with a warning, The authenticity of host '192.168.1.61' can't be established...—this is normal when you connect to a host for the first time over SSH, and you can safely type yes to continue connecting.

You will now be prompted to enter the password; type raspberry and press Enter. You are now connected to your Pi Zero via SSH and can move on to the Final setup section of this chapter.

SSH from Linux

To connect to your Pi Zero using SSH from a Linux operating system, you will need to use your system Terminal. Type the following command:

ssh pi@192.168.1.61

You should obviously replace the IP address with the IP address that your Pi has been assigned. As this is the first time you are connecting to your Pi over SSH from your computer, you will be asked whether you want to accept the ECDSA key fingerprint. This is normal on a first connection and nothing to worry about. Type yes and press Enter to continue connecting. You will then be prompted to enter the password for your Pi. Enter the default password of raspberry and press Enter.

When you type your password, you will not be shown any asterisks to indicate how many characters you have typed; type carefully!

You are now logged into your Pi Zero via SSH, move on to the Final Set up section of this chapter, to get your Pi ready to be used to start making our wearable-tech projects!

Final setup

Now that we have a remote connection to our Pi Zero, there are a few final setup steps to carry out so we are ready to start looking at our projects. The first thing we are going to do is to change our password to access our Pi. The default password is well known, and it is not a good idea to leave any password set as its default. Secondly, we will change the hostname of our Pi so that it is easily recognizable on our network as our Pi for these projects. Finally, we will install some of the basic software packages we are going to need for the projects in this book and also ensure that the other software already installed on the Pi is up-to-date.

Changing your password

To change your password, enter the following command into your SSH connection:

passwd

You will be asked to enter your current password (raspberry) and then asked to enter a new password twice. All being well, you should see a message like the one in the next screenshot. After changing a password over an SSH connection, I always open another SSH connection to my Pi and check whether I can successfully connect using my new password before I close the connection:

Changing the hour hostname

To change the hostname of our Pi Zero, we are going to make use of the raspi-config tool. Type the following command into your SSH connection:

sudo raspi-config

This will bring up the following menu:

Select option 2 using your cursor keys and press Enter to select it. Read and take note of the rules for allowed hostnames, and press Enter to select your new hostname. I am calling mine wearablepi. Once you have entered your new hostname, press Enter to save it. Press your Tab key twice to select <Finish> on the raspi-config menu and press Enter to close raspi-config. You will be prompted to reboot your Pi Zero. Press Enter with <Yes> selected, and your Pi Zero will reboot.

When your Pi Zero reboots, it should now show on your router's Attached Devices list, with its new hostname.

Reconnect to your Pi Zero via SSH and move onto the next section.

Downloading the example code

Detailed steps to download the code bundle are mentioned in the Preface of this book. The code bundle for the book is also hosted on GitHub at: https://github.com/PacktPublishing/Wearable-Tech-Projects-with-the-Raspberry-Pi-Zero. We also have other code bundles from our rich catalog of books and videos available at: https://github.com/PacktPublishing/. Check them out!

Installing basic software

We now need to update our existing software and install a few more bits of software ready for our projects. To update our existing software, type the following command into your Pi Zero:

sudo apt-get update

You should see multiple lines of information appear across your SSH connection, as your Pi Zero updates its information about what software packages are available to it:

To upgrade your existing software packages, type the following command:

sudo apt-get dist-upgrade

This command will make your Pi Zero check to see whether there are any updated software packages available for you to install. If there are, it will ask you to confirm. If prompted to, press Y to install your updates and wait for the process to complete.

We are now going to install a couple of new pieces of software, which do not come as standard on the Jessie Lite image, but this we will need for our projects. Type the following code to install the required software:

sudo apt-get install python3 python3-gpiozero python3-pip

Your Pi Zero will then calculate all the other packages it needs to install to get these three pieces of software working. Enter Y and press Enter to begin the installation process. Installing new software and updates on a Pi Zero can take some time, but be patient and it will finish soon enough!

Once this completes, we now have the basic software we need to start on our projects.

 

Basic electronics

In this section, we will wire up a simple push button, LEDs, resistors to our Pi Zero, and then write some simple Python code that will respond to a user pushing the button and making our LEDs flash.

Wiring up the electronics

We need to wire up our electronic parts, as shown in the following image:

Make sure that your Pi Zero is switched off when you are soldering the cables to the Pi or the header pins! You will also need to take care when wiring your LEDs, as we must get the correct legs attached to the positive and negative wires in our circuit, or they will not work. The positive leg of an LED is usually longer, and there is often a flat edge on the LED to indicate which is the negative leg. We are also going to introduce a 330 Ω resistor between the LED and the ground of the Pi; this is done to stop the LED drawing too much current from the Pi and damaging it.

You may want to introduce a little electrical insulating tape around one leg of each LED to ensure that they do not short circuit by touching the other leg. Once you have soldered your components together, give them a final check over to make sure they are in the correct GPIO holes on the Pi and that you have a good connection at each joint.

Now that we have completed the wiring of our electronics, we can move on to writing the code to control it all. Plug in your Pi and establish a SSH connection to it.

Writing the Python program

We will make use of the Nano text editor to write our Python files. First, we will create a directory to save all of our programs into. Type the following two commands:

mkdir ~/WearableTech
cd ~/WearableTech

We should now be inside our new WearableTech directory. Type the following command to open Nano, and create a new file called ledflash.py:

nano ledflash.py

We are now in the Nano text editor. Type in the following code to create a simple program, which will make the LEDs flash on and off when you press the button, and then stop the LEDs flashing when you press the button again:

#!/usr/bin/python3
from gpiozero import LED, Button

btn = Button(25)
green = LED(23)
red = LED(14)

while True:
btn.wait_for_press()
green.blink(0.5,0.5)
red.blink(0.25,0.25)
btn.wait_for_press()
green.off()
red.off()

Save the file by pressing Ctrl and O together, followed by the Enter key, and then exit Nano by pressing Ctrl and X together. We are now going to make the file executable by typing the following command:

sudo chmod +x ./ledflash.py

We can now run the file by typing this:

./ledflash.py

All being well, you should now be able to press the button wired up to your Pi and LEDs should start blinking at different rates. Press the button again (you may need to hold it for half a second) and your LEDs should switch off! If it doesn't work, check your program and double check your wiring.

If you want to stop your program from running, press Ctrl and C together.

Breaking down the program

The first line of the program is what is known as a shebang. The hash symbol followed by an exclamation mark (#!) tells the computer that what follows the exclamation mark is the details of what the program or interpreter should be used to run the rest of the program. In our case, this is python3, which is located inside the /usr/bin directories. Next, we import two things from the gpiozero library, Button and LED.

The next section of the code deals with setting up our devices. We create a variable, called btn, and tell Python that it is a gpiozero library's Button attached to GPIO pin number 25. We then create a variable for each LED and tell Python that they are gpiozero LEDs attached to pins 23 and 14.

Now, we enter the main part of the program. We start a while loop and just pass True as our condition to the loop; this will mean that this loop never ends (unless you close the program by pressing Ctrl and C together).

Now, we instruct Python to wait until it detects a press of the button. When it detects a press, we move on to the next line of the program. Here, we set each LED to blink on and off at different rates. The blink class of the gpiozero LED defaults to running the blink as a background thread; this means that the blink starts, and then we move onto the next line of code with the blink still running. So, with both LEDs blinking away, we wait again for a button press. When this is detected, we turn off each LED, and then return to the beginning of the loop.

Play around with the program and have a read of what else you can do using the gpiozero library on the documentation pages at https://gpiozero.readthedocs.io/en/stable/.

In the next chapter, we will get straight into a wearable-tech project using many of the things we have done in this chapter. At this point, you can shut down your Pi and desolder the six cables from it if you like; we will be using some different hardware for the next project!

 

Summary

In this chapter, you have learned a little bit about the history of Raspberry Pi Zero as well as how to set up Pi Zero from the scratch, including installing the operating system on our SD card and setting up remote access to it for our network.

We then spent some time creating a simple electronic project to get comfortable with some electronics we will be using, along with some of the Python libraries we will be using to control them.

About the Author
  • Jon Witts

    Jon Witts has been working within the IT industry since 2002 and specifically within Educational IT since 2004. He was introduced to Linux back in 2001 through his collaboration with two German artists who were visiting the arts organisation he was then working with. Having studied Fine Arts and Educational Technology and sought to innovate with open and accessible digital technologies within his creative practice, Jon is happiest when deconstructing technology and finding its limits. Jon has embedded within his school the use of Raspberry Pi computers, as an integral part of the delivery of the school's Computer Science curriculum as well as to run various school clubs and projects. Jon is a Raspberry Pi Certified Educator and also helps to organise and run the Hull Raspberry Jam events. I would like to thank my wife, Sally and our three daughters for putting up with all the cables and compoents around the house, and not least for being so tolerant of the need to dodge the robots racing round the kitchen floor!

    Browse publications by this author
Latest Reviews (3 reviews total)
Well done! Appropriate topics clearly presented.
I have read part of the ebook and know it's going to be a very useful text.
I'm really enjoying working through this book and making an item described in it. I have completed to the end of Chapter 3 so far. The explanations are clear.
Wearable-Tech Projects with the Raspberry Pi Zero
Unlock this book and the full library FREE for 7 days
Start now