Chapter 1

Introducing Raspberry Pi

IN THIS CHAPTER

check Finding out what a Raspberry Pi is

check Looking at various Raspberry Pi versions

check Connecting all the parts to make your Raspberry Pi work

check Installing the Raspbian operating system

check Getting used to Raspbian

check 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.

Introducing the Raspberry Pi

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:

  • CPU: A quad-core 64-bit ARM Corex-A53 microprocessor running at 1.2GHz.
  • RAM: 1GB.
  • USB ports: Four standard-size USB 2.0 ports mounted on the board. These ports can be used to connect any USB device, including a keyboard, a mouse, or a flash drive.
  • Video: A built-in graphics processor that can support 1080p resolution (1920 x 1080).
  • HDMI: A full-size HDMI connector is mounted on the board to connect a video monitor.
  • Display serial interface (DSI): A display interface designed to connect to small LCDs via a 15-pin ribbon cable.
  • MicroSDHC card: The MicroSDHC card acts as the computer’s disk drive. The operating system (Linux) is installed on the MicroSD card, along with any other software you want to use.
  • Ethernet networking: A built-in RJ-45 connector for networking.
  • 802.11n wireless network: A built-in wireless network connection. The antenna is actually built into the board itself, so no external antenna is needed.
  • Bluetooth: Built-in Bluetooth networking for wireless devices such as a keyboard, a mouse, and headphones.
  • Camera serial interface (CSI): A special interface designed to connect to a camera device via a 15-pin ribbon cable.
  • Audio: A 3.5mm audio jack for sound applications.
  • Power: The Raspberry Pi is powered by a 5 V supply connected to the board via a micro-USB connection, the same type used by most smartphone rechargers.
  • 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.

    warning 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.

image

FIGURE 1-1: A Raspberry Pi 3.

Considering Raspberry Pi Versions

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.

tip One of the main differences between the Model A+ and Model B+ is that the Model A+ does not have built-in networking. Because connecting to a network greatly simplifies the task of configuring your Raspberry Pi, I recommend you avoid the Model A+ until you’ve gained some experience working with the more powerful Raspberry Pi models.

Note that versions 2 and 3 of the Raspberry Pi are not available in A or B models.

technicalstuff The original Raspberry Pi 1 models (both A and B) had fewer GPIO pins than the newer versions. The original versions provided a 26-pin header block that provided access to 17 GPIO ports. On the newer versions, including the Raspberry Pi 2 and 3 models, a 40-pin header provides access to 26 GPIO ports.

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.

Setting Up a Raspberry Pi

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 Raspberry Pi 2 or 3.
  • A suitable power supply: The Raspberry Pi requires a 5 V power supply connected via a micro-USB connection on the card. The Pi itself will draw about 800 mA, so be sure to use a power supply that can handle at least that much current draw.
  • A monitor: You don’t need a large monitor, but I suggest at least 17 inches.
  • An HDMI cable: If your monitor has an HDMI connection, you’ll need a cable with HDMI connectors on both ends. If your monitor has some other type of connection, such as DVI or VGA, you’ll need an adapter to connect your monitor to the Pi’s HDMI connector.
  • A USB keyboard: Any keyboard with a USB connector will do.
  • A USB mouse: Any mouse with a USB connector will do.
  • 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.

  • A network connection: A network connection is essential to download several of the support packages you’ll need for the projects in this book. You can connect your Pi to a network in one of two ways:
    • If you have a Raspberry Pi 3, you can use the built-in Wi-Fi to connect to a wireless network.
    • You can use a standard Ethernet cable to plug a Raspberry Pi 2 or 3 into a wired network, provided you have a nearby router or switch with an available network port.

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.

Installing the Raspbian Operating System

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.

image

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:

  • Expand Filesystem: Depending on how Raspbian was installed, it may not have access to all the space that’s available on the SD card. Choosing this option will remedy that problem. Note that this option is not necessary if you used NOOBS to install Raspbian; NOOBS automatically allocates all the available space on the SD disk, so expanding the file system is not necessary.
  • 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.

    warning 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.

  • Enable Boot to Desktop/Scratch: By default, Raspbian boots to a command prompt. If you want the graphical user interface (which looks more like Windows or macOS), use this option. (If you don’t set this option, you can still use the graphical user interface. I explain how in the next section.)
  • Internationalization Options: This option displays a list of location options. The only one I suggest you change is the time zone.
  • Enable Camera: If you’ve installed a Raspberry Pi camera module on your Pi, you can use this option to enable the camera. If you haven’t installed the camera, leave this option disabled.
  • Add to Rastrack: Rastrack is a website that tracks the location of Raspberry Pis around the world. If you enable this option, your Pi will be added to the list. You can visit http://rastrack.co.uk for more information.
  • Overclock: This option allows you to increase the speed of your Raspberry Pi by running the processor faster than it’s designed to run. Doing so may cause your Pi to work erratically, so I suggest you leave this option disabled.
  • Advanced Options: Selecting this option takes you to a list of advanced options you can set for your Pi. For now, I suggest you leave these options alone.

When you’re finished with raspi-config, press the right-arrow key twice to select Finish, and then press Enter.

Logging In to Raspberry Pi

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).

image

FIGURE 1-3: The Raspberry Pi desktop.

Understanding the File System

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

Fixing the Keyboard

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:

  1. image 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.

  2. 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.

    technicalstuff 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.

  3. In the editor, choose File ⇒  Open.

    The Open dialog box, shown in Figure 1-6, appears.

  4. 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.

  5. Double-click the etc directory.

    The etc directory is where the most important Linux system configuration files are stored.

  6. 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.

  7. Double-click the keyboard file.

    This opens the keyboard file for editing, as shown in Figure 1-8.

  8. Change the keyboard layout from gb to us.

    Find the following line:

    XKBLAYOUT="gb"

    Change it to:

    XKBLAYOUT="us"

  9. Choose File ⇒  Save to save the file.
  10. Close the Leafpad window by clicking the Close box (in the upper-right corner of the window).
  11. 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.

  12. 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.

image

FIGURE 1-4: A terminal window.

image

FIGURE 1-5: The Leafpad text editor.

image

FIGURE 1-6: The Open dialog box.

image

FIGURE 1-7: Navigating the Linux file system.

image

FIGURE 1-8: Editing the keyboard configuration.

image

FIGURE 1-9: The End Session dialog box.

Congratulations! You’re well on your way to becoming a Raspberry Pi guru.

Writing Your First Raspberry Pi Program

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:

  • Mathematica: A mathematical programming tool that is used for complex mathematical programming.
  • Python 2: Version 2 of the Python programming language, which is the language I use for all the programming examples in this book.
  • Python 3: A newer version of Python. Python 3 includes some nice features, but unfortunately not all the ancillary programming packages used in Python programming are available for Python 3 programs. That’s why I’m sticking with Python 2 for this book.
  • Scratch: A visual programming environment used mostly to create arcade-style games.
  • Sonic Pi: An interesting programming tool used to create music.

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.

image

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:

  1. In Idle, choose File ⇒  New Window.

    A new, empty window appears.

  2. Type the text print “Hello, World!”.
  3. 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.

  4. 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.

  5. 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.

  6. You’re done!

    Congratulate yourself! You have successfully written your first Python program.

image

FIGURE 1-11: The hello.py program.

image

FIGURE 1-12: Hello, World!

Examining GPIO Ports

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 (images) 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.

image

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.)

warning The GPIO ports on a Raspberry Pi are rated for about 16 mA of current flow each, with a total of 40 mA across all GPIO ports combined. When designing circuits that interface with the GPIO ports, keep this limit in mind. Make sure you provide adequate current-limiting resistors to avoid damaging your Pi.

Connecting an LED to a GPIO Port

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 images 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.

image

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).”

Flashing an LED in Python

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.

Configuring IDLE for Root Privileges

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:

  1. Click Menu at the upper-left corner of the Raspbian desktop, and then choose Applications.

    A submenu of programming tools appears.

  2. 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.

  3. Click the LXTerminal icon in the menu bar at the top of the screen.

    This opens a terminal window.

  4. Enter the command sudo leafpad.

    This brings up the Leafpad text editor with administrator privileges. (Administrator privileges are required to edit a shortcut file.)

  5. In Leafpad, choose File ⇒  Open.

    An Open dialog box appears.

  6. 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.

  7. Double-click idle.desktop.

    This opens the desktop shortcut file, as shown in Figure 1-15.

  8. 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

  9. Choose File ⇒  Save.

    The file is saved.

  10. 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.

image

FIGURE 1-15: Editing the Python 2 desktop shortcut.

Building a Raspberry Pi LED Flasher

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.

image

FIGURE 1-16: The Raspberry Pi LED Flasher (Project 55).

Project 55: Blinking an LED with a Raspberry Pi

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.

image
image
image

Parts

  • One Raspberry Pi 2 or 3 with Raspbian installed, connected to a monitor, keyboard, and power
  • One small solderless breadboard (RadioShack 2760003)
  • One 5mm red LED (RadioShack 2760209)
  • One images resistor (orange-orange-brown)
  • Two jumper wires (M/F)

Steps

  1. Insert resistor R1.

    images: A3 to ground bus

  2. Insert LED1.

    Cathode (short lead): D5

    Anode (long lead): D3

  3. 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.

  4. Connect pin 3 on the Raspberry Pi A5 on the breadboard.
  5. Open the Python 2 IDLE Editor with root privileges.
  6. Create and save the sketch shown in Listing 1-1, using the filename LedBlink.
  7. 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.