Download PDF Parts List View on YouTube Download Code

When we need to interface with sensors, motors, and displays we generally think about using an Arduino, however, there are a lot of advantages in using a Raspberry Pi instead. Today we will see how easy it is to interface devices using the Raspberry Pi GPIO.

Introduction

The Raspberry Pi GPIO (General Purpose Input/Output) bus is a connector found on every model of Raspberry Pi.  Original models used a 26-pin bus but all modern Raspberry Pi boards have a 40-pin GPIO.

The GPIO allows you to expand your Raspberry Pi using expansion boards called HATs, an acronym for Hardware Attached on Top.  The bus provides access to power (5v and 3.3v), communications and general-purpose digital I/O signals. There are no analog pins.

The GPIO is also ideal for experimenters and makers who want to interface their Raspberry Pi with the outside world.  Pretty well any digital I/O sensor or device that you can interface to an Arduino can be attached to a Raspberry Pi using the GPIO, allowing your designs to benefit from the increased speed, storage, and power the Pi provides.

The Raspberry Pi 40-pin GPIO has been unofficially adopted by many SBC (Small Board Computer) manufacturers, allowing designs and code for the Raspberry Pi to be ported onto other platforms.  So it’s a good thing to learn about, even if you plan on using another board.

Pi vs Arduino

There is a tendency to want to compare the Raspberry Pi with the Arduino, which is not really a proper comparison as they aren’t even the same category of device. Each has its own strengths and weaknesses, which need to be taken into consideration when choosing a device to base your design upon.

The Raspberry Pi is a microcomputer, literally a small computer. It runs an operating system and has the equivalent of a hard drive, the latter in the form of a microSD card. It interfaces to a video monitor (or two), to a keyboard, mouse and other USB devices. It also communicates using Bluetooth, Wifi, and RJ-45, although the networking capabilities vary between models.

The Arduino, on the other hand, is a microcontroller. Not a computer, a small controller, whose purpose in life is to (what else?) control things! It accepts inputs from analog and digital sources and provides digital outputs. It is capable of precision timing and it is built around inexpensive components.

The Arduino is an open-source design, which is why there are so many Arduino “clones” and Arduino variations.  The Raspberry Pi is a commercial product that is licensed for manufacture at a limited number of factories worldwide and distributed through licensed vendors.

Arduino’s are based upon popular AVR chips and designs based upon Arduino’s can be easily reworked using these chips. This makes it easy to incorporate an Arduino within your commercial product.

The Raspberry Pi Compute Module allows you to integrate an entire Raspberry Pi into your commercial product. It’s a small (67.6mm × 31mm) board that fits into a standard DDR2 SODIMM connector, just like a memory chip.

Strengths and Weaknesses

A quick, and by no means exhaustive,  comparison of the two platforms looks like this:

Raspberry Pi Strengths:

  • Larger CPU power.
  • Native Internet and Bluetooth connectivity (some models)
  • More storage space.
  • Multitasking capabilities.
  • Integrated Camera and Display interfaces.
  • USB and HDMI interfaces.
  • Audio outputs.
  • Runs Rasbian (Linux) OS and Linux applications.

Raspberry Pi Weaknesses

 Higher cost (in most cases).

  • Not an Open Source design.
  • Requires monitor, keyboard, and mouse for development (can also use SSH instead).
  • Requires an additional microSD card.
  • No Analog inputs.
  • Software timing is not as accurate.
  • Higher power consumption (in most cases).
  • May require a heatsink and/or ventilation.
  • Longer boot-up and reset time.

Arduino Strengths:

  • Inexpensive.
  • Open-source design based upon popular AVR microcontroller chip.
  • Digital and Analog I/O ports.
  • Quick boot-up and reset times.
  • Accurate software timing
  • Lower power consumption (in most cases).
  • No heatsink or ventilation required.

Arduino Weaknesses:

  • Slow MCU.
  • Limited storage space.
  • No native Internet or Bluetooth.
  • No audio outputs.
  • No display outputs.
  • No multitasking.

Choosing between the Raspberry Pi and Arduino

Deciding which platform to use in your design involves weighing their individual strengths and weaknesses against each other.  You’ll also want to consider future enhancement plans when making your decision.

Essentially the Raspberry Pi is the thinker while the Arduino is the worker. This is perhaps a broad generalization, but it does hold true in most cases.

  • If your application requires precision software timing then choose an Arduino.  Microcomputers are just too busy doing other things to worry about precise software timing.
  • If you need Internet connectivity then a Raspberry Pi makes sense. You can add this capability to the Arduino using shields, but it’s built-in on most Raspberry Pi models.
  • If you need a video display then choose a Raspberry Pi.
  • If you want a camera then you’ll want a Raspberry Pi.

And remember – in an advanced design you may well choose to use BOTH boards, as they can be interfaced using I2C or SPI. 

Today we’ll be choosing a Raspberry Pi. But there are many different Raspberry Pi boards. Which one is a good choice?

Raspberry Pi Family

The Raspberry Pi has been around since 2012, and the original Model 1 board has made way for a number of successors.

The original Raspberry Pi boards used a 26-pin GPIO, while more modern boards use a 40-pin connector. We will be using the 40-pin devices.

That still leaves a lot of boards to choose from! Here is a peek at some of the ones from my parts drawers:

Here are some of the more prominent family members:

Raspberry Pi 2B

The Model 2B was the second-generation Raspberry Pi. It was released in February 2015.

The board has a 900MHz quad-core ARM Cortex-A7 CPU and 1GB of RAM.  It also has 4 USB2 ports and a 100 MBps RJ45 Ethernet connector.

It has both HDMI and composite video as well as audio outputs, a CSI camera interface, and a DSI display interface.

According to the Obsolescence Statement, the Raspberry Pi 2 Model B will remain in production until at least January 2026.

Raspberry Pi 3A

The Raspberry Pi 3A was released in 2018 and is a third-generation device. It has the same form factor as the original Model 1.

The board is powered by a Broadcom BCM2837B0 and has 512 Mb of RAM. It has both 2.4GHz and 5GHz wireless LAN and Bluetooth 4.2/BLE. 

The 3A has a full-sized HDMI port, an audio output, the CSI camera connector, and a DSI display interface. It only has one USB2 port and does not have an Ethernet RJ45 connector.

Raspberry Pi 3B and 3B+

The Model 3B was the first third-generation Raspberry Pi and also the first one to have both Ethernet and wireless networking, as well as Bluetooth.

It has the same form-factor as the model 2B and sports the same connections, including the 100Mb Ethernet RJ45 jack. 

The 3B has a Quad-Core 1.2GHz Broadcom BCM2837 64bit CPU and 1GB of RAM. 

The Raspberry Pi 3B+ is an updated version of the #B, with a 1.4GHz 64-bit quad-core processor, dual-band wireless LAN, Bluetooth 4.2/BLE, faster Ethernet, and Power-over-Ethernet support.

Raspberry Pi 4B

As of this writing, the Raspberry Pi 4B is the latest model of the Pi.

The Pi 4B is powered by a 1.5GHz Broadcom BCM2711 Quad-core processor. It is available in three models with 1GB, 2GB or 4GB of RAM.

Significant improvements include Gigabit Ethernet connections and two Micro HDMI connectors, each capable of supporting 4kp60 video.

It has four USB connectors, two of them are USB3. It also requires a USB-C power supply.

Raspberry Pi Zero and Zero W (and Zero WH)

The Raspberry Pi Zero made history by becoming the first computer given away in a copy of a magazine.  The MagPi, the official Raspberry Pi magazine, included a Pi Zero 1.0 with each copy of its Issue number 40 in December 2015.  The Pi Zero was encased in plastic on the front cover.

The current Raspberry Pi Zero is model 1.1, which has a small CSI camera port that model 1.0 did not have. It is the most inexpensive Raspberry Pi, costing all of 5 dollars US.

All of the Raspberry Pi Zero family members have a 1GHz single-core CPU and 512MB of RAM.  They also have a mini HDMI output, as well as a micro USB port. A second micro USB connector is used to power the device.

The basic model Zero has no built-in network connectivity. The Zero W adds both Wifi and Bluetooth capabilities and has a price tag of 10 US dollars.

The Model Zero WH is identical to the Model Zero W, with the addition of a pre-soldered 40-pin GPIO connector.  The other Raspberry Pi Zero models have no GPIO pins, you will need to solder one in yourself.

What PI for these Experiments?

The answer to that is simple, ANY of the above boards will work properly for these experiments and future experiments in this series.

To prove that I’m going to use the Raspberry Pi Zero W. It has more than enough power to run all of the experiments, and its built-in WiFi will come in handy.

To facilitate working with the Pi Zero I’m soldering a male header (20 x 2) onto the boards GPIO pads. 

If you want a tip on how to do the soldering and align the pins correctly check out this video that I made a long time ago!

Raspberry Pi GPIO

The General Purpose Input/Output bus permits your Raspberry Pi to communicate with sensors, displays and a wide variety of peripherals.  And, of course, it’s the subject of today’s article and video!

GPIO Pins

The GPIO is a 40-pin bus that uses a 2-row (20×2) male header. Raspberry Pi Zero and Zero W models do not have the male header pins installed.

Older (pre-2014) models of the Raspberry Pi used a 26-pin GPIO. The first 26 pins of the modern GPIO connector are identical to the original one for backward compatibility.

Here are the GPIO pinouts:

The above image is from splitbrain.org and is called a Raspberry Pi B+ Pinout Leaf. You can download as a scale PDF document and print them to slip over the GPIO pins to make them easier to identify the pin functions.

You’ll note that there are two sets of power pins, 5-volts and 3.3-volts. These are voltage outputs to power HATs and other devices attached to the GPIO.

The 5-volt pins can also be used as inputs, although on earlier models that would bypass a fusible link which offered the Raspberry Pi some protection.

GPIO Pin Numbering Schemes

You may have noticed that some of the numbers on the pis in the previous diagram didn’t seem to make sense, as they don’t correspond to the pin numbers. 

This is because there are several methods of naming individual GPIO connections. Here are a few you’ll run into:

  • BCM – The Broadcom pin numbers, often just called “GPIO” numbers. This is the most common method of naming the GPIO pins.
  • WiringPi – These were the pin numbers used in the WiringPi library, one of the first popular libraries for working with the GPIO.
  • Physical – The actual pin numbers on the 40-pin connector.
  • Revision 1 Numbers – These are BCM numbers from the original 26-pin GPIO.

I’ll be using the BCM numbering scheme in this article and referring to them as “GPIO pin numbers”.

GPIO Voltage Restrictions

The Raspberry Pi GPIO uses 3.3-volt logic for inputs and outputs. These connections are NOT 5-volt tolerant, and connecting them to 5-volt logic or power could destroy your microcomputer.

It’s not an issue for today’s experiments, but definitely something to keep in mind when you are wiring devices to the GPIO.

GPIO Libraries

The easiest way to work with the Raspberry Pi GPIO is to use a library.  There are several to choose from.

  • WiringPi – This was one of the earliest GPIO libraries written for the Raspberry Pi.
  • RPIO – A pretty advanced GPIO library.
  • Pigpio – A Python module to interface with the GPIO. Also supported on other platforms.
  • RPi.GPIO – A very popular GPIO library
  • gpiozero –  A GPIO library that simplifies working with the GPIO.

We will be using the gpiozero library for our experiments, and we’ll get our Python code directly from the gpiozero documentation “Basic Recipes” section.

Hooking up to the GPIO

No matter which model of the Raspberry Pi you have selected to perform the experiments upon, you’ll need to figure out how to hook up your components to the GPIO.

If you’re using the Raspberry Pi Zero W, as I am, you also have the option of soldering directly to the GPIO pads on the printed circuit board, but I really don’t recommend that.  Best bet is to solder a male header onto the Pi Zero and use the GPIO the same way the other models do.

Raspberry Pi Hookup Accessories

There are several different ways you can connect to the GPIO.  I brought a few of them out onto my workbench to illustrate the point.

One of the most common methods of prototyping with the GPIO is to use a T-adapter, often called a T-cobbler.  This adapter connects to a solderless breadboard and comes with a 40-pin ribbon cable that you attach to the Raspberry Pi GPIO connector.

You can also purchase prototyping HATs to work with the GPIO. These allow you to build your project as a HAT that can be easily used with any Raspberry Pi. There are also prototyping HATs that have small solderless breadboards on them.

One of the easiest, and least expensive, methods of connecting to the GPIO is to simply use male to female Dupont wires. The female end fits onto the individual pins of the GPIO.

You’ll also likely need a few other adapters for your Raspberry Pi, especially if you are using a Pi Zero model. These will allow you to adapt the mini HDMI connector to a standard cable, and to convert the micro USB ports to a full-sized USB connector.

Pi 4 users will likely need a video cable with a micro HDMI connector at one end.

Raspberry Pi Setup

I am going to assume that you already have the latest version of Raspbian installed on your Raspberry Pi. If you don’t, here is a quick rundown of what you need to do:

  • Download Raspbian as a ZIP file from the Raspberry Pi website.
  • Use Etcher or a similar program to burn a microSD card with the Raspbian image.
  • Connect your Raspberry Pi to the appropriate monitor, keyboard, and mouse.
  • Insert the microSD card that contains the Raspbian image.
  • Power on. It will reboot the first time after it resizes the partition on the microSD card.
  • After a while, you’ll get a Raspbian desktop.
  • Walk through the steps for setting your admin password, your locale, and screen information.
  • After rebooting again you are ready to start the experiments.

If you already have a Pi running Raspbian make sure you are at the latest version.

You should also go into the Raspberry Pi Configuration and enable your Camera, as we wil be using it in two of our experiments.

Start Experimenting

OK, so finally we are getting started!

We are going to experiment with very simple I/O devices so that we can learn how to code for the GPIO. This will allow us to move onto other more sophisticated I/O devices later.

We’ll be using some pushbutton switches and an LED in our experiments. To make things more interesting we will also be using the Raspberry Pi camera module, so have one on hand for the final experiments.

Raspberry PI LED & Button Hookup

Hooking up the components for our first set of experiments is very simple, as illustrated here:

There are many ways you can wire this, I used a small solderless breadboard to hold the switch, LED and dropping resistor and I made my connections using male to female DuPont wires.

Arduino Blink

Wait a moment, aren’t we working with the Raspberry Pi today?

Yes, we certainly are, but the first demo we are going to do is simply blink the LED we attached to our Raspberry PI GPIO. So I thought it would be a good idea to revisit Blink, the “Hello World” of Arduino sketches to see how it’s accomplished there.

In Blink, we setup our LED as an Output and then enter the Loop. In the Loop, we simply turn the LED on, wait for a delay period, turn it off, wait for another delay period and then repeat the whole thing over again.

The result is that the LED flashes at a rate determined by the two time delays.

Now let’s see how to do the same thing on a Raspberry Pi using Python.

Raspberry Pi Blink

Our first Python code example is shown here:

Looking at it you should be able to see similarities between this and the Blink sketch for Arduino.

The LED Class of the gpiozero library is used, as well as the Sleep Class from the time library.  We run the code in a While loop that always evaluates as TRUE so it keeps running. 

In the While loop, we do exactly the same thing we did with Blink – we turn the LED on, wait for a second, turn it off, wait for another second and then repeat. 

There is a second example that makes blinking an LED even easier:

In this example, we use a function of the LED Class to just blink the LED. By default, it will blink once per second, but the blink function accepts parameters to change the on and off time, as well as the fade-in and fade-out of the LED.

The pause function imported from the signal Class waits for an asynchronous system event to occur, at which point it would pause the program. This is a common technique to use in programs dealing with the GPIO.

As you can see the gpiozero library has made the task of flashing an LED very simple!

LED and Button Experiments

We can use the classes within the gpiozero library to have more fun with LEDs.

LED code with PWM

The PWMLED CLass allows you to manipulate the LED brightness using PWM, similar to using the digitalWrite command on an Arduino.

The first example uses this function to vary the LED brightness. The LED value parameter can be adjusted from 0 (off) to 1 (full brightness).  We use this to cycle the LED betwern off, half brightness and full brightness.

Here is another use of the PWMLED Class. 

In this example, we are using the pulse function to pulse the LED with varying brightness. The pulse function accepts parameters to control the fade in, fade out, number of pulses and the name of a callback function that is called after the number of pulses has elapsed.

LED and Button

Our next bit of Python code will let us control the LED using the pushbutton:

We will import both the LED and Button Classes from the gpiozero library for this program.

The code simply looks at two events generated by the pushbutton. The when_pressed event is used to turn the LED on, and the when_released event is used to turn it off.

Here is a second snippet of code that accomplishes the same thing:

This code is even simpler, the controlling source for the LED is pointed to the Button.

More Button Code

This piece of code waits for the button to be pressed before it continues:

When the button is pressed the wait_for_press function will then print the text in the Shell area of the Python editor.

This code runs once then exits after the job is completed.

This code sample shows how both the when_pressed and when_released functions can be used. Unlike the previous code sample, this one will run continuously.

Controlling the Camera

The examples we have seen so far show how simple it is to code for the GPIO. And admittedly they were very simplistic examples.

The Raspberry Pi has a multitude of other libraries that can be used to control the I/O devices connected to it. One of those libraries is for using the camera attached to the CSI connector.

We will finish our experiments by using a couple of pushbuttons to control the camera.

Camera Hookup

For these experiments we will use the following hookup:

As with the initial experiments, this is a very simple hookup.

You’ll also need to attach the camera to the connector on your Raspberry Pi. If you are using a Raspberry Pi Zero (or W or WH) then you’ll need a special camera cable, as these models use a smaller version of the CSI connector.

Taking a Raspberry Pi Selfie

This program simply uses a push button to take a picture. I used it to allow the Raspberry Pi to take a selfie.

The capture function is the heart of this program. It uses the datetime to format a string with the current date and time and uses that string as the name of the image it is capturing.

The picamera library takes care of all of the interaction with the camera.

We use the when_presed event to cal the capture function. This leaves a picture in the home directory.

My Raspberry Pi worked well in this application, but it isn’t a very good photographer!

Adding a Preview Button

For our final experiment, we will be using both buttons.

  • One button will be a preview button. Holding it down will give us a full-screen preview of what the camera is looking at. The preview will stay on the screen until the button is released.
  • The other button will be used to take a picture.

Here is the code:

We are using the same function to take pictures as we did in the earlier example.

The Button when_presed event triggers the camera start_preview function.

The Button when_released event triggers the camera end_preview function.

It’s a pretty simple program, yet it essentially creates a basic digital camera! 

Conclusion

The Raspberry Pi GPIO allows you to connect a variety of digital I/O devices to your Pi. Libraries like gpiozero make it easy to work with the GPIO.

This is the first of several articles and videos I’ll be doing about using the Raspberry Pi GPIO. In future installments, you’ll learn how to interface more advanced I/O devices to the GPIO.

 

Parts List

Here are some components that you might need to complete the experiments in this article. Please note that some of these links may be affiliate links, and the DroneBot Workshop may receive a commission on your purchases. This does not increase the cost to you and is a method of supporting this ad-free website.

COMING SOON!

 

Resources

gpiozero Library Docs – Basic Recipes – Documentation for gpiozero, with all of the experiments we did today (and a lot more).

Code for the article – Code taken for the examples and placed into separate python files, all put together in a handy ZIP file.

goiozero Library Classes – Documentation to show you how to use all of the Classes in the gpiozero library.

Raspberry Pi Blog – The official blog of the Raspberry Pi Foundation.

 

The Raspberry Pi GPIO – Getting Started with gpiozero
Summary
The Raspberry Pi GPIO - Getting Started with gpiozero
Article Name
The Raspberry Pi GPIO - Getting Started with gpiozero
Description
The Raspberry Pi GPIO is a 40-pin connector that lets you connect your Pi to the outside world. Learn to use the GPIO and the gpiozero library to control some simple I/O devices.
Author
Publisher Name
DroneBot Workshop
Publisher Logo
Subscribe
Notify of

9 Comments
Oldest
Newest
Inline Feedbacks
View all comments
4 years ago

Thanks Bill, as always, a great Video. And useful!

verl
3 years ago

Arduino needs a computer —- Raspberry Pi has its own computer.

Really got a lot from that bit of advice!
I had only saw it, the Pi , as a small computer only. Even though the header pins were there, i had not parsed it that way.

Bob
3 years ago

What a wealth of information!!! I’m a newbie but the way you explain things, I actually get it!

I will be checking out every single page of this website and your vids. 😉

Bob

David Martens
3 years ago

Thank you for all the hard work you put into very logical and well laid out presentations. Very impressive work!

Jason Cartwright
3 years ago

Hey I like your little camera program, when button is pressed… how would you modify it to work with motion sensitivity? Id like to make that change and if motion detected, take the image, possibly with a very short sleep.

2 years ago

Very nice article. I’ve used Arduino for years, was always intimidated by the Raspberry Pi and Python, but am gonna give it a try. Thanks for the write-up !

Ihor
2 years ago

i was given a raspberry pi c 2011 as a gift, is it usable

PhillyTechClub
2 years ago

Absolutely Great Video ! Im now learning Python for the Raspberry Pi 😀

Michael
2 years ago

Im very appreciative and greatful for the tremendous amount of meticulous work you put into these. What a terrific resource. Thank you so much! ~Michael from TN, USA