Chapter 1
IN THIS CHAPTER
Finding out what a Raspberry Pi is
Looking at various Raspberry Pi versions
Connecting all the parts to make your Raspberry Pi work
Installing the Raspbian operating system
Getting used to Raspbian
Writing your first Python program
In Books 6 and 7, you learn how to work with two popular types of microcontrollers: Arduino and BASIC Stamp. In this minibook, you learn how to work with Raspberry Pi, a popular alternative to Arduino, BASIC Stamp, and other types of microcontrollers.
Physically, a Raspberry Pi resembles an Arduino or a BASIC Stamp. However, the Raspberry Pi is much more than a microcontroller; it is a full-blown computer system, implemented on a single small card. In fact, a Raspberry Pi has most of the features commonly found on a desktop or laptop computer. Yet besides its small size, a Raspberry Pi has other features not commonly found on a desktop, such as the ability to directly control digital I/O pins. Thus, you can use a Raspberry Pi with external devices such as LEDs, push buttons, potentiometers, various types of sensors, and servo or stepper motors.
In short, Raspberry Pi is the ideal computer for people who love to make their own gadgets.
In this chapter, you learn exactly what a Raspberry Pi is, how to get one, how to hook it up, and how to get it running. Then, in the next few chapters, you learn how to write programs for the Raspberry Pi and how to add external components to it.
A Raspberry Pi (sometimes just called a Pi for short) is a very small computer. It contains most of the components found in a traditional desktop computer, but all squeezed onto a small board about the size of a deck of playing cards. The newest version of the Raspberry Pi, called the Raspberry Pi 3, is pictured in Figure 1-1. This version of the Raspberry Pi includes all of the following packed onto the board:
GPIO header: The most interesting thing about the Raspberry Pi from an electronic enthusiast’s perspective is the 40-pin GPIO header, which provides access to a variety of features, including 26 general-purpose input-output (GPIO) pins. These pins work the same as the digital I/O pins found on Arduino and BASIC Stamp microprocessors, and can be accessed via programs that you write for the Raspberry Pi. You can use these GPIO pins as output pins to connect to devices such as LEDs, servo or stepper motors, and so on. Or, you can use them as input pins to read input from external switches, potentiometers, or other types of sensors.
Unlike the digital I/O pins found on Arduino or BASIC Stamp microprocessors, the Raspberry Pi GPIO pins work at a voltage level of 3.3 V rather than 5 V to indicate HIGH signals. You’ll need to adjust your circuits accordingly to deal with the smaller input and output voltage levels. In particular, if you apply a 5 V input to GPIO input pin, you run the risk of damaging your Raspberry Pi.
FIGURE 1-1: A Raspberry Pi 3.
Since the introduction of the original Raspberry Pi back in 2012, an almost dizzying array of versions has been released. The Raspberry Pi has been through three generations, known as 1, 2, and 3. Each new generation has incorporated new features.
The Raspberry Pi 2 was introduced in 2015. It improved upon the Raspberry Pi 1 by using a more powerful processor and additional RAM, while holding the price the same. Importantly, the Raspberry Pi 2 also increased the number of GPIO ports from 17 to 26. Unfortunately, in doing so the GPIO pin configuration was changed, which means that projects created for the Raspberry Pi 1 are not compatible with projects created for the Raspberry Pi 2.
In 2016, the Raspberry Pi 3 was introduced. It improved upon the Raspberry Pi 2 by adding a more powerful processor, faster RAM, and built-in wireless networking. (Wireless networking with a wireless Raspberry Pi 2 was usually done using a wireless adapter inserted into one of the USB ports.)
The price of all three versions of the Raspberry Pi has been $35. All the projects in this book use the Raspberry Pi 3, but they’ll also work on a Raspberry Pi 2.
The first-generation Raspberry Pi 1 was available in two models: Model A and Model B. The Model A version was a slimmed-down version of the Model B, with less memory and fewer I/O options but consuming less power. In 2014, these two models were replaced with the Model A+ and Model B+, which added additional capabilities.
Note that versions 2 and 3 of the Raspberry Pi are not available in A or B models.
All the projects shown in this book will work with either a Raspberry Pi 2 or 3. If you don’t yet own a Raspberry Pi, I suggest you purchase a Raspberry Pi 3 as part of a kit that includes the materials you’ll need to get started. These simple kits include a power supply to power your Raspberry Pi, a microSD card already loaded with the operating system software, and a small book to get you started. Some kits include additional goodies, such as an HDMI cable to connect your Raspberry Pi to a monitor and perhaps additional components such as LEDs, resistors, jumper cables, and a breadboard.
Before you can fire up your Raspberry Pi and start building projects, you need to do some basic setup work. Start by setting up the hardware. You’ll need the following to set up your Pi so that you can program it for the projects presented in this book:
A microSD card with NOOBS: The Raspberry Pi uses a microSD card instead of a disk drive. Ideally, you should purchase a microSD card that already has a special program called NOOBS installed on it. (NOOBS stands for New Out Of the Box Software.) This program will allow you to install an operating system so that your Pi can run.
If you prefer, you can format your own microSD card for your Pi. You can do that by downloading NOOBS from www.raspberrypi.org
on your computer and then copying the NOOBS software to the microSD card.
That’s all you need to get started. Plug the monitor, mouse, and keyboard into your Pi’s HDMI and USB ports, insert the microSD card into the microSD slot, and then plug in the power connector. Your Pi will start right up.
Raspbian is a special version of Linux that is designed especially for the Raspberry Pi. Although you can run other operating systems on your Pi, Raspbian is the most common choice, and it’s the operating system I use for all the examples in this book.
When you start up your Pi for the first time with a microSD disk containing NOOBS, the NOOBS program displays a list of operating system choices that you can install. Simply click the box next to Raspbian (the first choice listed), and then click Install in the toolbar. NOOBS will install the Raspbian operating system and then reboot the Pi.
When your Pi reboots, you’ll see a bunch of text messages fly past the screen. After a few moments, the text messages will stop and a program called raspi-config will appear, as shown in Figure 1-2. This program allows you to configure your installation of Raspbian.
FIGURE 1-2: Raspi-config lets you configure Raspbian for your Pi.
You can use the raspi-config program to configure various options that affect how your Pi behaves. Use the up and down arrows on your keyboard to highlight an option, then press the Enter key to select the option. Here’s more on each of the available options:
Change User Password: The username for the default account for Raspbian is pi, and the default password is raspberry. If you want to change the password, you can use this option to do so.
Don’t lose the password if you decide to change it! Raspbian doesn’t offer any way to recover a lost password, so if you lose the password for the pi account, you’ll have to reinstall the operating system and start over.
http://rastrack.co.uk
for more information.When you’re finished with raspi-config, press the right-arrow key twice to select Finish, and then press Enter.
Once raspi-config has finished, you’ll see a Linux login prompt:
Raspbian GNU/Linux 7 raspberrypi tty1
Raspberrypi login:
Type the username pi and press Enter. You’ll be prompted for the password:
Password:
Enter the password raspberry and press Enter. (If you changed the password in raspi-config, enter the password you specified.)
After you’ve logged in, you’ll see the command prompt:
pi@raspberrypi - $
Your Pi is officially up and running, awaiting your command.
At the command prompt, you can enter any Linux command you want. To get to a graphical user interface that resembles Windows or the macOS, enter the following command:
startx
This fires up the graphical user interface, which displays a desktop screen complete with icons on the desktop, a menu bar at the top, and the Raspberry Pi desktop wallpaper (see Figure 1-3).
FIGURE 1-3: The Raspberry Pi desktop.
If you’ve never worked with Linux before, you may find yourself a bit confused about Raspbian’s filing system. All Linux operating systems, including Raspbian, organize files and directories a bit differently from the Windows file system you’re probably used to. Three of the most obvious differences are actually superficial, but they can trip you up if you’re not mindful of them:
Apart from these superficial differences, the big difference between the Linux and Windows file system is that Linux treats everything in the entire system as a file, and it organizes everything into one gigantic tree of directories that begins at a single root directory.
When I say, “Everything is treated as a file,” I mean that hardware devices such as floppy drives, serial ports, Ethernet adapters, even the GPIO pins on a Raspberry Pi are treated as files.
The root of the entire Linux file system is the top-level directory of the microSD card from which the Raspberry Pi boots. If you insert a USB flash drive or a USB disk drive into one of the Raspberry Pi’s USB ports, that drive will be grafted into the tree as a directory called mount points. Thus, a directory in the Linux file system may actually be a device.
The root-level directories in a Linux filing system are listed in Table 1-1. If you open the File Manager by clicking the file cabinet icon at the top of the screen, these are the directories you’ll see.
TABLE 1-1 Root-Level Directories in a Linux File System
Directory |
Description |
/bin |
Essential command binaries |
/boot |
Static files of the boot loader |
/dev |
Devices |
/etc |
Configuration files for the local computer |
/home |
Home directories for users |
/lib |
Shared libraries and kernel modules |
/media |
Mount point for removable media such as USB flash drives |
/mnt |
Mount point for nonremovable file systems |
/proc |
Important kernel and process files |
/opt |
Add-on applications and packages |
/root |
Home directory for the root user |
/sbin |
Essential system binaries |
/srv |
Server data such as web pages, FTP files, and so on |
/tmp |
Temporary files |
/usr |
Read-only, shared files such as binaries for user commands and libraries |
/var |
Variable data files |
If you live in the United States, one of the first things you’ll want to do on your Raspberry Pi is change the keyboard to match the layout of U.S. keyboards. Raspberry Pi was developed in Great Britain, so it uses the British keyboard layout, which is a bit different than the U.S. one. The differences are important for programming, because some of the characters that you use to write programs for the Pi are on different keys.
To change the keyboard, follow these steps in the graphical user interface:
Click the LXTerminal icon in the menu bar at the top of the screen.
This opens a terminal window, as shown in Figure 1-4.
Type the command sudo leafpad in the terminal window.
The sudo prefix is often used in Linux commands. It tells Linux to execute a command using administrative privileges. In Linux, the administrative privileges you need are sometimes called root privileges or superuser privileges. The word sudo is short for superuser do.
Any Linux command prefixed by the word sudo will run with root privileges — in this case, Leafpad, an easy-to-use text editor program, shown in Figure 1-5.
The reason you must use sudo in this step is that you’re going to use Leafpad to edit one of Raspbian’s many configuration files, which are simple text files that specify various configuration settings for Linux. You must use root privileges to modify these configuration files.
In the editor, choose File ⇒ Open.
The Open dialog box, shown in Figure 1-6, appears.
Choose File System in the list of places on the left side of the Open dialog box.
This displays the Linux file system, which allows you to access the files stored on the microSD that you booted your Pi from. As you can see in Figure 1-7, Linux organizes files into folders much as Windows and macOS do. However, in Linux, these folders are properly referred to as directories.
Double-click the etc directory.
The etc directory is where the most important Linux system configuration files are stored.
Double-click the default directory.
In this directory, you find a number of configuration files that specify default configurations for various Linux features, among them the default keyboard layout, which is stored in the keyboard file.
Double-click the keyboard file.
This opens the keyboard file for editing, as shown in Figure 1-8.
Change the keyboard layout from gb to us.
Find the following line:
XKBLAYOUT="gb"
Change it to:
XKBLAYOUT="us"
Restart your Pi by choosing Menu ⇒ Shutdown from the menu bar at the top of the screen.
The End Session dialog box, shown in Figure 1-9, appears.
Choose the Reboot option, and then click OK.
Your Pi reboots. When it starts back up, the keyboard will be configured correctly for U.S. users.
FIGURE 1-4: A terminal window.
FIGURE 1-5: The Leafpad text editor.
FIGURE 1-6: The Open dialog box.
FIGURE 1-7: Navigating the Linux file system.
FIGURE 1-8: Editing the keyboard configuration.
FIGURE 1-9: The End Session dialog box.
Congratulations! You’re well on your way to becoming a Raspberry Pi guru.
Raspbian comes with several programming languages built in. You can find them by clicking the Menu button at the top left of the screen, and then clicking Programming. Doing so reveals a menu that lists six popular programming languages for creating programs on the Pi:
Because Python 2 is the programming language of choice for this book, start by choosing File ⇒ Programming ⇒ Python 2. This opens a program called Idle, which is the programming development environment for creating and running Python programs. Figure 1-10 shows the opening screen of Idle, which is called the Python Shell.
FIGURE 1-10: The Python Shell
You can run Python statements directly within the Python Shell without creating a program; when you type a Python statement in the Shell and press the Enter key, the statement is executed immediately, and any results it generates are shown in the Shell.
For example, type print “Hello, World!” and press the Enter key. The text Hello, World! appears on the next line in the Python shell.
To actually create a Python program that displays the message Hello, World!, follow these steps:
In Idle, choose File ⇒ New Window.
A new, empty window appears.
Choose File ⇒ Save As.
A Save As dialog box appears. By default, the Save As dialog box opens in the home directory for the current user (/home/pi). You can navigate to a different folder if you want, but there’s no reason to not just save the program in the pi user’s home directory.
Type hello as the filename, and then click Save.
The file is saved using the name hello. Figure 1-11 shows how the hello.py program appears after it has been saved.
Choose Run ⇒ Run Module (or press F5).
This action runs the hello.py program. The output from the program (that is, the message Hello, World! appears in the Python Shell window, as shown in Figure 1-12.
You’re done!
Congratulate yourself! You have successfully written your first Python program.
FIGURE 1-11: The hello.py program.
FIGURE 1-12: Hello, World!
General-purpose input/output (GPIO) ports make Raspberry Pi much more than just a very small computer. GPIO ports allow you to control your own electronic circuits directly from the Pi. The 40-pin GPIO header on the Raspberry Pi 2 and 3 provides access to a total of 17 GPIO ports that can be controlled from programs you write in Python or other languages.
To use a GPIO port, you must first configure the port for input or output. When configured for output, a GPIO port can be set to a HIGH () or LOW (0 V) condition by your programs. When configured for input, a program can easily determine the current state (HIGH or LOW).
Figure 1-13 lists the function of each pin on the Raspberry Pi 2 and 3 40-pin header block.
FIGURE 1-13: Raspberry Pi 2 and 3 header pins.
Unfortunately, the pins on the header block are not labeled in any way on the Raspberry Pi board. If you orient the board so that the header block is on the right edge of the board, just above the USB ports, pins 1 and 2 are at the top of the header block. The odd numbered pins are on the left side of the header block; even numbered pins are on the right side.
You’ve probably already noticed that the pins on the header block don’t appear to be laid out in any particular logical order. The GPIO ports are scattered about the header haphazardly, interspersed with 3.3 V, 5 V, and Ground pins at seemingly random locations.
To avoid confusion when programming Raspberry Pi projects, people common number the GPIO ports using their header pin numbers rather than the GPIO port numbers. For example, GPIO port 19 can be referred to as pin 10 in a Python program. When you write your programs in this way, you can completely ignore the GPIO port number, instead referring to the GPIO port using its pin number. The only trick when you do this is to remember that not all the pins on the 40-pin header are used for GPIO ports; only those pin numbers designated as GPIO ports in Figure 1-13 should be used as GPIO ports. (You’ll see an example of this numbering in an actual program later in this chapter.)
If you configure a GPIO port as an output port, you can use the port to drive an LED. You’ll need an LED and an appropriate current-limiting resistor. Figure 1-14 shows a typical schematic. In this case, the LED is connected to pin 3 on the Pi, which corresponds to GPIO port 2. A resistor is used to limit the current flowing through the LED, and the LED’s cathode is connected to any of the various ground pins on the Pi.
FIGURE 1-14: Connecting an LED to a GPIO port.
One detail you should be aware of is that the header block on the Raspberry Pi uses male pins rather than female sockets as are found on Arduino and BASIC Stamp microcontrollers. As a result, to connect a breadboard circuit to pins on the Raspberry Pi, you’ll need jumper wires that have male pins on one end (to plug into a breadboard hole) and female sockets on the other end (to plug into the male pins on the Raspberry Pi header). You can purchase these jumper wires from many Internet sources; just search the web for Raspberry Pi jumper wires and you’ll find what you need. The wires you want will typically be called something like “female/male extension jumper wires” or “jumper wires (M/F).”
Now that you know how to connect an LED to a Raspberry Pi GPIO port, let’s examine how you can use Python to turn the LED on and off. In Chapter 2 of this minibook, I give you many more details about the Python programming language. For now, let’s just take a quick look at a Python program that flashes an LED connected to pin 3 of a Raspberry Pi. The LED will turn on and off alternately at half-second intervals. The complete program is shown in Listing 1-1.
LISTING 1-1 An LED Flasher Program in Python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
while True:
GPIO.output(3, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(3, GPIO.LOW)
time.sleep(0.5)
Let’s take a look at this program, one line at a time:
Program Line |
What It Does |
import RPi.GPIO as GPIO |
Tells Python that the program requires a package of functions called RPi.GPIO and that the program will refer to functions in that package using the shorthand GPIO. The RPi.GPIO package contains functions for working with GPIO ports. |
import time |
Tells Python that the program requires a package of functions called time. This package is required so that the program can control the timing of the flashing LED. |
GPIO.setmode(GPIO.BOARD) |
Indicates that the program will refer to GPIO ports using the pin numbers on the Raspberry Pi board rather than using the internal GPIO port numbers. |
GPIO.setup(3, GPIO.OUT) |
Indicates that the program will use the GPIO port on pin 3 as an output port. |
while True: |
Sets up a loop that never ends. All the indented statements after this line are executed in sequence over and over again, until the program is stopped by the user. |
GPIO.output(3, GPIO.HIGH) |
Sets the status of the port on pin 3 to HIGH. This statement turns on the LED. |
time.sleep(0.5) |
Pauses the execution of the program for half a second. This allows the LED to stay on for half a second. |
GPIO.output(3, GPIO.LOW) |
Sets the status of the port on pin 3 to LOW. This turns the LED off. |
time.sleep(0.5) |
Pauses the execution of the program for half a second. This allows the LED to stay off for half a second. |
For as long as the program is allowed to run, the four statements indented beneath the while statement will be executed over and over again, in the sequence list. First, the LED turns on for half a second; then the LED turns off for half a second. The flashing continues until the user stops the program.
For the program shown in Listing 1-1 to work, it must run with root privileges. That’s because the Raspberry Pi denies access to the GPIO ports to any program not run with root privileges. Earlier in this chapter, you learn that you can run any Linux command with root privileges by prefixing the command with the word sudo. You can use the same technique to run a program that accesses the GPIO ports.
The easiest way to provide the correct access permissions for the projects presented in this book is to run the IDLE development environment under the sudo command. You can accomplish this by first creating a desktop shortcut for IDLE, and then editing the shortcut itself so that it runs IDLE under sudo. Follow these steps to pull off this nifty trick:
Click Menu at the upper-left corner of the Raspbian desktop, and then choose Applications.
A submenu of programming tools appears.
Right-click Python 2, and choose Add to Desktop.
This creates a shortcut icon on the desktop.
The desktop shortcut is actually a text file that lives in the folder /home/pi/desktop. This text file contains a command that runs the IDLE program; all you need to do is modify this file so that it runs IDLE under sudo. The remaining steps show you how to do that.
Click the LXTerminal icon in the menu bar at the top of the screen.
This opens a terminal window.
Enter the command sudo leafpad.
This brings up the Leafpad text editor with administrator privileges. (Administrator privileges are required to edit a shortcut file.)
In Leafpad, choose File ⇒ Open.
An Open dialog box appears.
Click File System, then navigate to the folder /home/pi/desktop.
You’ll see a file named idle.desktop; this is the Python 2 desktop shortcut file.
Double-click idle.desktop.
This opens the desktop shortcut file, as shown in Figure 1-15.
Edit the file to run idle under sudo.
Find the following line in the idle.desktop file:
Exec=/usr/bin/idle
Modify this line to read:
Exec=sudo /usr/bin/idle
Choose File ⇒ Save.
The file is saved.
Close Leafpad.
You’re done! If you start IDLE using the desktop shortcut, IDLE will run under sudo, so any Python program you run from IDLE will have access to the GPIO ports.
FIGURE 1-15: Editing the Python 2 desktop shortcut.
Project 55 shows how to build a simple breadboard circuit that connects an LED to a Raspberry Pi via the GPIO port on pin 3 of the header. Figure 1-16 shows the completed project.
FIGURE 1-16: The Raspberry Pi LED Flasher (Project 55).
In this project, you connect an external LED to a Raspberry Pi, and then use a simple sketch to turn the LED on and off at 0.5-second intervals.
Insert resistor R1.
: A3 to ground bus
Insert LED1.
Cathode (short lead): D5
Anode (long lead): D3
Connect the ground bus to the Raspberry Pi header pin 2.
Use a jumper to connect any hole in the ground bus on the breadboard.
Run the LedBlink program by choosing Run ⇒ Run Module (or press F5).
The LED on the breadboard will flash on and off at half-second intervals.