Raspberry Pi - Giving Life to Objectss - The Maker's Manual: A Practical Guide to the New Industrial Revolution 1st Edition (2015)

The Maker's Manual: A Practical Guide to the New Industrial Revolution 1st Edition (2015)

Part IV. Giving Life to Objects

Chapter 18. Raspberry Pi

Sometimes, an Arduino is not enough. There are projects that require flexibility and calculating power that the Arduino’s small chip can’t provide. If you wanted to, say, re-create an 80s-style game console, mine for whichever cryptocurrency is in fashion at the moment, or drive a high definition video display, the Arduino can’t really hack it. For cases like these, you’d turn instead to the Raspberry Pi.

Raspberry Pi is a small, inexpensive, full-fledged computer on a single circuit board, complete with operating system, keyboard and mouse support, and a graphical user interface (GUI) with windows and menus, With the quad-core processor powering the latest generation of Raspberry Pi, it is similar to a smartphone or tablet in terms of computational power. It can be connected to a monitor, a mouse, a keyboard--and many USB devices. Plus, it can connected to the Internet, and it is capable of executing programs written in languages such as C, Java, and Python.

By this measure, Arduino and Raspberry Pi are not really comparable. They both have a series of pins which can be connected to external circuits, yet each one of them specializes in carrying out different tasks. Arduino is, essentially, just a microprocessor with some additional hardware for handling various types of input and output. All it can do is to run the same small program over and over until the power gives out (or you put in a new program). On the other hand, because the Raspberry Pi is a full computer, it is not as reliable as Arduino in terms of interacting with the hardware in real time.

Component Check!

As soon as you open your Raspberry Pi box, you see a small printed circuit board, a little bigger than Arduino.

Let’s have a closer look at Raspberry Pi (Picture 18.3):

Alt Text

Figure 18-1. The most important parts of a Raspberry Pi.

1: GPIO (General Purpose Input & Output) header

These pins, shown in [Link to Come], can be used as digital inputs or outputs, similar to the pins on Arduino. The single-core Raspberry Pi Models A+ and B+ as well as the quad-core Raspberry Pi 2 Model B have forty pins, in two 20-pin rows. Unlike the Arduino, the Raspberry Pi only has digital pins, with no analog inputs. Its pins operate at a voltage of 3.3V, as opposed to Arduino’s 5V: keep that in mind when you connect hardware to the GPIO pins. Too much voltage can damage the pins or the entire Raspberry Pi.

2: USB ports

The Model B+ and Raspberry Pi 2 bave four USB 2.0 ports. Just about any class of USB device (e.g. mouse, keyboard, WiFi, Bluetooth, GPS, etc.) will work with the Raspberry Pi. When things don’t work, the chief culprit is probably power. With your Pi plugged into a strong enough (2 amps or more) USB power supply, the Raspberry Pi ports can provide a maximum of 500 mA to USB devices. If a USB device requires more than 500 mA, or if you’re powering your Pi with less than 2 amps, that USB device may not work reliably. For this reason, it is better to connect a USB device to a separately powered USB hub, in order to isolate the Raspberry Pi from the most demanding gadgets.

3: Ethernet connection

The Ethernet connector is only present on B type (B+, Raspberry Pi 2) boards. In today’s wireless world, it could be hard to find a wired network jack to connect Raspberry Pi to, so it would might be much easier to connect a compatible USB Wi-Fi dongle. To connect to a Wi-Fi network after you’ve connected a Wi-Fi module, start the gui (“The Graphical User Interface”) and click Menu→Preferences→WiFi Configuration, then click the Scan button to find a network to connect to.

4: Analog audio output

Beside the digital audio found on the HDMI output, there is a lower-quality analog audio source signal available on this 3.5 mm audio jack connector. You could also connect headphones, but the signal is better heard with a pair of amplified speakers.

5: CSI (Camera Serial Interface)

This is the connector for the Raspberry Pi camera accessory. There are two versions of the camera: the normal camera model and an infrared version (the Pi Noir Night Vision Camera Module).

6: HDMI output

With a simple HDMI cable, costing only a few dollars, you can use this connector to plug the Raspberry Pi into a monitor or a TV.

7: Power in

This is the micro USB port used to supply power to the Raspberry Pi. It is possible to use a smartphone charger to power the Pi, but be sure it puts out 5V and at least 700 mA. Make sure you use enough power. An underpowered Raspberry Pi tends to reset itself in the middle of the most critical operations, when the most electrical power is needed.

8: DSI (Display Serial Interface)

With this connector you can (eventually, when the official display panel is released) connect a display via a flat, flexible cable similar to the cable used to connect the camera.

9: Micro SD slot

On the underside of the Raspberry Pi, there is a housing for a Micro SD card, which is what the Raspberry Pi uses in place of a hard disk. Just as with the hard drive on a larger computer, the SD card contains the operating system for the Raspberry Pi. You must use a good quality card (at least class 4). SD Cards higher than class 8 are much faster, but some users have complained that they’re not as stable; try to stick to class 4 or class 6 cards.

10: Status LEDs

There are two status LEDs here, PWR (power) and ACT (activity). When the power LED is on and stable, Raspberry Pi is being properly supplied with power. The activity LED shows when the Micro SD card is being accessed.

Getting Started

Let’s get started with the Raspberry Pi. Connect a mouse and a keyboard to the USB ports. For the video, you can use an HDMI digital input TV or monitor and an HDMI cable.

As we’ve said, in place of a hard disk, the Raspberry Pi uses a Micro SD card on which you need to load the operating system. You’ll need to obtain a Micro SD card (8GB or larger suggested, but it will work with a 4GB card). Grab the NOOBS installer from the Raspberry Pi downloads page and unzip it onto your Micro SD card. Check out the NOOBS setup guide to help you with the installation.

To switch the Raspberry Pi on, connect a power supply. When it starts up, the NOOBS installer will ask you which operating system to install. Click the checkbox next to Raspbian and then click the Install icon. After the installation is complete, the Raspberry Pi will restart, and you’ll see a black screen scrolling with fast-moving white text, until the raspi-config configuration program screen appears, as shown in Figure 18-2.

Alt Text

Figure 18-2. When you first start the system, the raspi-config program will help you configure your Raspberry Pi.

The configuration operations are rather simple. Choose the “Internationalisation Options” with the arrow keys, and then press Enter or Return. You should set your Locale to one appropriate for where you are (for example in the US, you probably want “en_US.UTF-8 UTF-8”). Go back to the Internationalisation options again and set your timezone and keyboard layout.

The keyboard layout selection may involve a few steps. US users will probably need to choose either Generic 101-key PC or Generic 104-key PC, and if English (US) is not available, choose other, then choose English (US).

When you’re done configuring your Pi, press Tab until Finish is highlighted, then choose the option that reboots your Pi.

When the Raspberry Pi boots up next, it will start up to a black screen with a prompt labeled login: At the prompt, authenticate yourself by typing in pi for the username and raspberry for the password. You’ll be greeted by a shell prompt that indicates the shell (an interactive tool for running programs and sending commands to the Pi) is ready for you to type commands:

pi@raspberrypi ~ $

The prompt is made up of several parts:


This is your username


This indicates that your Raspberry Pi’s hostname is raspberrypi. Read together with the preceding part of the prompt, it indicates that you’re logged in as user “pi”, at (“@”) the host named “raspberrypi”.


This shows your current working directory. At the moment, you’re in the home directory (/home/pi), and ~ is shorthand for your home directory.


This is the shell prompt. When you see it, it means the shell is ready for you to send it commands.

But... why are you operating in a black-and-white text environment? Doesn’t the Raspberry Pi have a graphic environment? Yes, but it does not start automatically. But before launching it, it is worth having a look around the text environment and getting familiar with the use of the display and some of the Linux commands.

The Right Way to Turn Off

The Raspberry Pi does not have an on/off power switch or a reset button. As soon as you supply power to the board, the operating system loads. If you remove power from the board (by literally pulling the plug), the board switches off.

But it is never a good idea to switch off a computer this way, while the operating system (OS) is working. Nearly every OS performs operations in the background, such as writing data to the SD card, which we as users are not aware of. If you remove power suddenly, the OS might be caught in the middle of one of those background tasks, with the result that the SD card might become corrupted, and unbootable next time. The best way to switch Raspberry Pi off is to launch a specific command (sudo shutdown or sudo halt) from the shell.

One of the fundamental metaphors in the computer world is the concept of files and folders in which to organize the files. The folder metaphor imagines that your computer’s hard drive (or SD card, in Raspberry Pi’s case) is an old metallic filing cabinet with many drawers full of folders, containing many individual documents (files) or even smaller folder (subfolders). (Figure 18-3).

Alt Text

Figure 18-3. A physical archive with files and folders.

Another metaphor is the tree structure, used to define the hierarchy under which data are stored (Figure 18-4). To make your way through this hierarchy, you have to type commands which are interpreted by the shell, which is the program that starts running right after you log in.

Alt Text

Figure 18-4. An example of the folder hierarchy of Raspberry Pi.

Another term for folder is directory, and is more commonly used on Linux systems (Linux is the operating system that runs on the Raspberry Pi). The main directory, which contains all the others and is at the top of the hierarchy, is called root and is represented by the symbol / (slash).

Basic Shell Commands

To find out which branch (directory) of the tree you are in, type pwd followed by Enter or Return. The term pwd stands for print (name of) working directory, and displays the path from the root to the current directory.

pi@raspberrypi ~ $ pwd

When you see an example like the preceding one, don’t type the $ or the text leading up to it. The $ is the shell prompt, and you will need to type your commands after the prompt.

The system will reply:


How do you know what is contained in the directory you are in? You can list the current files by using the command ls, which stands for list:

pi@raspberrypi ~ $ ls

On a freshly-installed Raspberry Pi, the system will reply with the following (if you’ve created files or directories on your own, you’ll see something different):

Desktop python_games

You can get more information about the files by using the parameter -l, which stands for long.

pi@raspberrypi ~ $ ls -l

The system will respond with more details about the two directories:

total 8

drwxr-xr-x 2 pi pi 4096 Jan 31 16:26 Desktop

drwxrwxr-x 2 pi pi 4096 Dec 31 1969 python_games

To move your focus from one directory to another, you can use the cd command (which stands for change directory) followed by the name of the directory you want to access:

pi@raspberrypi ~ $ cd Documents

This tells you to move to the Documents directory. If you were to then run an ls command, you’d see the files in the Documents directory.

Directories can be nested. Inside the Documents directory might be a Projects subdirectory, for your project-related documents. To go there from the Documents directory, you can tell the OS cd Projects

On a freshly set-up Raspberry Pi, there won’t be a Documents directory. You could create it (and the Projects) subdirectory with this command: mkdir -p ~/Documents/Projects. You’ll see more about the mkdir command in “Operations on Files and Directories”.

To back out of a nested subdirectory into the directory that contains it, you can use a shortcut. The higher lever directory is represented by .. (two dots), while the current directory is represented by . (one dot).

So, to go one level back you’ll use cd .., as so:

pi@raspberrypi ~/Documents $ cd ..

If you are in the directory /home/pi and you use the cd .. command, you will go to the /home directory.

The shell remembers the last commands you have given it: if, at the prompt, you press the up arrow or down arrow keys, you can run through the list of commands you have used in the order you have input them. This is very useful when you need to repeat a command several times. Another helpful feature of the shell is the autocomplete function for the commands: you just need to type in the first letters of a command, then press the Tab key and the shell can complete it for you, saving you from typing the whole name. Of course, if there are multiple commands that start with the same letter, you might have to type enough of the command so that autocomplete knows which command you mean. You can also press Tab twice to see all the possible commands.

Operations on Files and Directories

Let’s start by creating a directory with the mkdir (make directory) command, followed by the name you want to give to the directory. We’re showing two commands here; the first one is to make sure you change back to your home directory before you try the rest of the exercise (if you type cd all by itself without any arguments, it changes to your home directory):

pi@raspberrypi ~ $ cd

pi@raspberrypi ~ $ mkdir test

Now, move into the directory and create an empty file with the touch command, then, with ls, check whether the system has actually created the file:

pi@raspberrypi~ $ cd test

pi@raspberrypi~/test $ touch hello.txt

pi@raspberrypi~/test $ ls


pi@raspberrypi~/test $ ls -l

total 0

-rw-r--r-- 1 pi pi 0 Feb 15 19:42 hello.txt

To copy a file, use the cp command, for copy, followed by the name of the file you want to copy and the destination you want to copy it to. Copy the hello.txt file to the home/pi directory:

pi@raspberrypi ~/test $ cp hello.txt /home/pi

Because the home directory is one level higher than the current one, you may also write:

pi@raspberrypi ~/test $ cp hello.txt ..

And because ~ can be used as a shortcut for your home directory, you could also write:

pi@raspberrypi ~/test $ cp hello.txt ~

The mv command, which means move, is used to rename or move files. To rename your hello.txt file to pi.txt, you’ll type:

pi@raspberrypi ~/test $ mv hello.txt pi.txt

pi@raspberrypi ~/test $ ls


To move it to the higher level directory:

pi@raspberrypi ~/test $ mv pi.txt ..

pi@raspberrypi ~/test $ ls

pi@raspberrypi ~/test $ ls ..

You can delete the file with the rm command, which means remove. When working from a shell, there is no trash directory where deleted files are moved to; moreover, Linux is a system which obeys and does everything it is asked, including completely deleting all data and the operating system itself, so you’d better pay great attention to what you do.

pi@raspberrypi ~/test $ rm ../pi.txt

From your shell, you can even modify a file. One of the simplest editors you have at your disposal in Linux is nano, shown in Figure 18-5.

Alt Text

Figure 18-5. The main screen of the nano editor.

In order to edit a file with nano, use the command nano, followed by the file name:

pi@raspberrypi ~/test $ nano pi.txt

One great thing about nano is that the file doesn’t already have to exist; nano will create the file if necessary. Type the phrase “Hello World!” into the file. After editing the file, type Control-O followed by Enter or Return to save the file. Type Control-X to exit the editor.

On Linux, it is possible to read a file’s content without using an editor; the command cat (for concatenate) prints the file contents to the console:

pi@raspberrypi ~/test $ cat pi.txt

Hello World!

If the file is very long, you will only see the last part that fits in the terminal window. To make reading easier, you can use a text viewer called less:

pi@raspberrypi ~ $ less pi.txt

With less, you can scan through lines and pages of the file, or jump to the beginning or to the end of the text. To move within the text, use the up and down arrow keys, space, and Enter (or Return). To exit less, press the q key. By pressing h, a short manual of the available commands is displayed.

The Raspberry Pi is always executing a number of programs in the background; to know what they are you can use the ps (process status) command. If the command is followed by some parameters, you can get more or less information about the ongoing processes; the -ef options will display a detailed list of processes in the whole system.

pi@raspberrypi ~ $ ps -ef

Generally, if you’re looking for any kind of information about the operating system, two programs are here to assist you: apropos and man (for manual). apropos will search for a string in the title of all manual pages, and man will show the given manual. Since most manuals are large than one screen, man automatically uses less.

The command man apropos will display the manual for how to use apropos. By using those programs with other commands, you will find lots of information about all aspects of the installed software.


On Unix-based systems, like Linux, each program is designed as a “black box” which receives input from a source (the default source is the keyboard), and produces output to a destination (the default destination is the shell output/computer screen, referred to as the standard output). These commands can be interconnected to create command chains which can perform even complex operations. To connect two commands, for example ls and less, you need to use a “pipe”, that is the | symbol. If a directory contains many files, the ls -l output will take up many screens, but if you move it through less, you’ll be able to easily read it:

pi@raspberrypi ~ $ ls -l | less

Instead of using the standard output, you can direct the output of a program elsewhere, for example to write the output to a file, use the symbol > (greater than).

pi@raspberrypi ~ $ ls -l > list.txt

You won’t see anything appearing on screen, which is fine, because you told the operating system to output ls -l, to the file list.txt. You can take your time and read the file later. Each time you repeat this command, the operating system overwrites the list.txt file. If you want to add the latest output to what is already in the file without overwriting it, you need to use the >> (double “greater than”) symbol.

pi@raspberrypi ~ $ ls -l >> list.txt

The command inputs also work in a similar way. To redirect an input, use the < (less than) sign. This causes the command to read from the file rather than the standard input (which more or less corresponds to your keyboard).

pi@raspberrypi ~ $ cat < list.txt

In this case, the cat command operates on the information found in the list.txt file, just as if you had typed every individual character manually.

Most Linux commands that can operate on a file with the < redirection operator can also work just fine without it, by supplying the file name as an argument, as in cat list.txt. You’ll find that in Linux, there’s often more than one way to do something.

The World of the Superuser

In Linux, every individual who uses the system can be given their own user account, such as the pi account you’ve been using all along. But there is also a “superuser” called root built into the system, capable of performing any operation without limits: root can delete protected files and directories, even the entire disk. Using that much power on a Raspberry Pi is not recommended, therefore you would normally operate as a common user, with limited power. This limits the damage if you typed a wrong command.

But sometimes you need to perform operations as the root user. To make your life simpler, the sudo system (superuser do) has been created: with this, a “regular” user can launch superuser commands, such as switching the system off. To perform superuser commands, you need to place the word sudo before the command. Depending on the specific setting of the operating system, using sudo might require your password before the command is executed. By default, it does not ask for a password on the Raspberry Pi.

The following command will shut down your Raspberry Pi:

pi@raspberrypi ~ $ sudo halt

Of course, the sudo trick is not valid all the times and for everyone: the superuser needs to first include you within the list of people allowed to use sudo (the so-called sudoers) and must specify what programs you can use in this mode. Luckily, on the typical Raspbian installation this has already been prepared, at least for the pre-configured pi user. On other Linux systems, such as the systems at work or school, you may not have the necessary privileges to use the sudo command.

Monitoring Hardware

Sometimes you need to check whether a peripheral device you have plugged in has been detected by Raspberry Pi. The easiest way to do that is to use the lsusb command (can you guess what the abbreviation stands for?), which shows all the detected USB peripherals. You can also check what the core of the system, called the kernel, has to say about the device. The kernel writes some kind of a log which you can read through the dmesg command, that is, display messages. Many messages will appear, which you can view in less:

pi@raspberrypi ~ $ dmesg | less

To find out what your CPU’s capabilities are, use the command:

pi@raspberrypi ~ $ cat /proc/cpuinfo

You’ll see a series of lines containing information about the processor(s). Look for the Revision entry at the end and check its value: Raspberry Pi model As should display 0002 or 0003, higher values (including characters, like with 000f) identify B models and beyond.

The Graphical User Interface

Now that we have completed a quick overview of the use of the terminal, you can move on to the graphical environment. To start the graphical environment, type the startx command. The graphical environment, or desktop environment, is made out of two parts: a graphics server (the standard is called X11) and a window manager. To put things simply, the graphics server provides all the libraries and components to create the environment on which the window manager relies; the window manager creates a nice-looking and usable interface. One of the good things about Linux is that it can work on low-performing machines, since its window manager uses up few resources. The default window manager that Raspberry Pi uses the is LXDEdesktop environment, shown in Figure 18-6.

Alt Text

Figure 18-6. The LXDE desktop of Raspberry Pi.

The desktop should look familiar, at least in the basic sense that it looks a lot like other desktops you’ve seen on Windows, Mac, and Linux. At the top of the screen there’s a menu with a number of icons, applets and widgets. Starting left, you first find the menu button: a small button with the Raspberry Pi logo and the word “Menu”. Then, you have shortcuts for a browser, file manager, Terminal (which lets you get to the shell even when you’re in the graphical environment), Mathematica, and the Wolfram language environment. To the right is an applet that shows the current CPU usage, followed by the current time.

There is one icon on the desktop, the Trash.

Raspbian has some very useful applications already installed, such as an editor, utilities, programming tools, Internet programs, games, and system utilities. You can have a look at the installed programs by opening the menu: just click the bottom left button. The Raspbian menu has a first level of main headings, under which you can see all the installed programs.

§ The Programming menu contains the development environments for the Python language, Scratch, Wolfram, and others.

§ The Internet menu contains the Pi Store (where you can find more software), a link to more Raspberry Pi resources, and the Web browser.

§ Under Games, you’ll find Minecraft Pi and some games written in Python.

§ Under Accessories there are many useful programs: a compressed file manager, the calculator, a file manager, an image and PDF viewer, your friend the terminal, a task manager to see what’s running on your Pi, and a Text Editor.

§ Preferences contains the programs that allow you to adjust the system settings. You can change elements of the graphic environment’s appearance, and desktop, mouse and keyboard behaviors. You can also configure your Wi-Fi connection here.

§ The Run menu lets you type any Linux command and run it.

§ To close the session or shut the system down, you would click Shutdown>... but not yet!


There’s a snake hiding in Raspberry Pi: a python!

Well, not a real snake. In fact, the computer language Python is based on nothing more dangerous than the passion that its inventor, Guido Van Rossum, has for Monty Python’s Flying Circus. Van Rossum created this language to embrace simplicity, readability, without sacrificing the ability to create complex programs. With Python, writing programs for Raspberry Pi is fast and simple; moreover, it can be easily expanded with libraries, making it easy to access the GPIO pins and to control external hardware.

Teaching you everything about Python is not one of the goals of this book, but we are going to briefly show how to use it and what you can do with this powerful language. You’ll see how different it is from other languages we have analyzed in this book, such as Processing or Arduino.

We have already said that the language you use with Arduino is a compiled language: you write the source code (or the sketch) in a more or less human-comprehensible language; after that, a program called a compiler turns it into machine code, a series of 0s and 1s that the computer processor can understand. Python, on the other hand, is an interpreted language, that is, a program called interpreter reads each single instruction in Python and runs it straight away, with no need to compile anything.

The Python interpreter is interactive: it behaves like a terminal where you can enter commands and get results right away. Launch the Python interpreter from the terminal, by typing python followed by hitting the enter key.

You’ll see some text lines appear, and a cursor waiting for your action. You can print “hello world” by typing:

print("hello world")

It wasn’t hard, was it? The interpreter also works as a calculator, so if you write 2 + 3 and hit the enter key, you get 5.

To exit the interpreter, type quit() or press Control-D.

The instructions which you use interactively can be saved in a script, i.e. a text file that you’ll get the interpreter to read (scripts are to Python as sketches are to Arduino). With the nano text editor, create a file named helloworld.py and write:

print("hello world!")

Save and close. Then, from the terminal, execute the script with:

python helloworld.py

There is your “hello world!” appearing on screen.

In the graphical environment, you can choose Menu→Programming→Python 3. This is the Python development environment and is much more than a simple editor: you can use it to write programs, execute them or debug them, i.e. follow their execution step by step and “peep” into variables and code, in order to see what happens at every moment of the program, so you can identify any problems.

As soon as you start it, the development environment displays the Python version number, and other information that you don’t need right now. Open a new window with the New Window command, found under the File menu. Now you can type:

print("hello python!")

Next, press F5, and when prompted, save the code somewhere in a file called hellopython.py. Your code will be executed and the words “hello python!” will appear in the main window.

There are some differences between Python and the other languages in this book:

§ In Python, there is no need to use a semicolon (;) after each statement;

§ To define code blocks, no brackets ({}) are used: in Python, the code is structured by formatting: by using spaces and tabulating everything neatly.

You need to be very tidy and precise: each block must have the same indent, that is, the same number of spaces, before each instruction. Here is some code with the wrong indent:

num = 11

if (num > 10):

print (num)

print ("is greater than 10"),


print (num),

print ("is less than or equal to 10")

The print instruction in the second line is not aligned with the instructions in its block and Python will display an error. 
The correct format is:

num = 11

if (num > 10):

print (num),

print ("is greater than 10")


print (num),

print ("is less than or equal to 10")

When you use the print statement without a , at the end, it displays a line break after whatever it prints. If we didn’t put , after print (num) the output of this script would be:

11 is greater than 10

You can create single-line comments by using the # character:

if (num > 10):

#print the num value

print (num),

Python has the same rules as other languages with regard to variable names: no exotic characters, spaces, punctuation, and must not start with a number.

For further information about Python there are many websites you can look up. The official documentation is at https://www.python.org/doc/.


Depending on which model you have, a Raspberry Pi has between seventeen (Model A and B) and twenty-eight (A+, B+, and Raspberry Pi 2) General Purpose Input-Output hardware ports, in a connector strip of two rows of thirteen or twenty. 
In addition to the GPIO pins, which you can use as digital inputs or outputs, you’ll also find some 3.3V and 5V power supplies and ground (GND) pins.

Raspberry Pi is way more delicate than Arduino, so you need to be very careful with the connections: its GPIO pins only work with 3.3V; if you tried to connect 5V, you could irreparably damage your Raspberry Pi.

Hello World

For this experiment, you are going to use an LED (choose one rated for 3.3 volts or more), a breadboard, and a few cables with male-female terminal connectors. Your goal is to try to switch the LED on and off by using some simple terminal commands.

Alt Text

Figure 18-7. A male-female terminal connector to connect Raspberry Pi to components.

With your Raspberry Pi switched off, mount the LED on a breadboard and connect it, as shown in Figure 18-8, to the GPIO25 pin and to the ground pin (GND). 
The GPIO25 port puts out 3.3V, and your LED uses 3.3 volts, so you can get away without using a resistor for this quick test. For long-running projects, you’re going to want a resistor between the power source and any LED you use.

Alt Text

Figure 18-8. Connect the LED to the GPIO25 pin of Raspberry Pi.

The Fritzing diagrams in this section show the Raspberry Pi A and B (26-pin) layout rather than the newer 40-pin layout. However, the first 26 pins of the 40-pin layout are identical to the original layout, so you can hook it up the same way on any model Pi.

Supply power to the Raspberry Pi and wait for it to boot up. Log in, but don’t bother starting the graphical environment. If you did start it (with startx or if you’ve used raspi-config to configure it to automatically boot to the desktop), open a Terminal window.

1. Change to a special directory created by the operating system to allow you to work on the GPIO pins directly:

2. pi@raspberrypi ~ $

cd /sys/class/gpio

3. As you saw earlier, you can inspect the directory contents with ls. Try that now.

4. In order to work with the GPIO pins, you need superuser privileges, so, before continuing, launch the sudo -s command:

5. pi@raspberrypi /sys/class/gpio $

sudo -s

This lets you run all your commands as the superuser. Be sure to type exit when you’re done with this example so you can exit superuser mode.

6. When you change into a superuser shell with sudo -s, your shell prompt will change appearance subtly. Instead of showing a $ at the end as it did in the preceding example, it will show a #, as in root@raspberrypi:/sys/class/gpio#. In the examples that follow, we’ll abbreviate the shell prompt to either $ (for normal user) or # (for superuser).

Now you can let your Raspberry Pi know that you need access to the GPIO25 pin by writing the pin number into the file named export. The echo command displays its arguments to standard output (your screen or the Terminal window). You’re using the redirection operator (>) to send that output into the file named export:

# echo 25 > export

7. In response to this command, the system will generate a gpio25 directory containing files that allow you to use the GPIO port. 
If needed, you can release the pin from use with the command (but don’t type this now):

# echo 25 > unexport

8. But keep it exported for now, and cd into the gpio25 directory, then show its contents with ls:

9. # cd gpio25

# ls

You’ll find some special files within the directory: active_low, direction, edge, power, subsystem, uevent, and value.

10.You need to create a file named direction to set the pin as either an input or output, which is similar to Arduino’s pinMode. To configure the pin as an output, write the word “out” to the file. To configure it as an input, you’d use “in”. For this, you’ll use echo again:

# echo out > direction

11.With Arduino, to switch an LED on and off you used the digitalWrite function with HIGH or LOW as a value; the equivalent on Raspberry Pi is writing the values 1 or 0 into a special file named value. So, to switch the LED on you’ll write:

# echo 1 > value

whereas to switch it off:

# echo 0 > value

When you’re done switching the LED on and off, unexport it and exit out of superuser mode:

# cd /sys/class/gpio

# echo 25 > unexport

# exit

$ cd


A Flashing Python!

Luckily for you, there is a library in Python that can manage the GPIO pins, which makes everything very easy. This library is called RPi and should be already installed; if not, you can install it with:

$ sudo apt-get update

$ sudo apt-get install python-rpi.gpio

The library author has provided two ways of identifying Raspberry Pi pins: the first convention is logical numbering and can be selected in your Python code with:


The second convention follows the physical numbering of the pins on the board and is activated with:


We’ll use BCM numbering because it’s what we were using in the preceding example when you blinked the pin, and it’s commonly used in Raspberry Pi accessories and documentation (such as the diagrams in this chapter). If you counted the pin that you connected the LED to earlier, you may have wondered why you couldn’t find a counting scheme that yielded the number 25. That’s because logical pin 25 is connected to physical pin 22 on the header, as shown in Figure 18-9.

Alt Text

Figure 18-9. Raspberry Pi pin numbers: physical (GPIO.BOARD) on top of the pins, logical (GPIO.BCM) on the labels below

Also in Python, you need to configure the GPIO ports before using them. Use the GPIO.setup function followed by the pin number and by the desired working mode (OUT for output and IN for input):

GPIO.setup(25, GPIO.OUT)

With pin 25 now set as an output, you are ready to switch the LED on or off with the GPIO.output(port, value) function. The GPIO library provides some constants for the port status: GPIO.HIGH and GPIO.LOW. So, you can switch the LED on with:

GPIO.output(25, GPIO.HIGH)

and switch it off with:

GPIO.output(25, GPIO.LOW)

Now you just need to create a loop which repeats these operations endlessly. Unlike Arduino, where you had the loop() function, here you need to create the loop yourself. You’ll use the while keyword, which executes instructions contained in the following code block until the condition you want to test no longer evaluates to true. If the condition simply consists of True, it will always be true and the cycle will never stop. Here is the start of your loop:

while True:

In Arduino you also had the delay() function, which you could use to create pauses of milliseconds. In Python, you can use the time library and its related sleep() function. While in Arduino delay times were measured in milliseconds, Python’s sleep function uses seconds. To stop the script execution for two seconds, write:


Remember that Raspberry Pi is not very precise in observing timing. This is because your program is being executed together with many others, so you have no guarantee that the operating system will observe the exact time you are setting.

Example 18-1 shows the complete listing of a blinking Hello World in Python.

Example 18-1. “blink” with Raspberry Pi.

# Hello World

import RPi.GPIO as GPIO

import time

pin = 25

# Use logical pin layout:



while True:





You can type this code into a file with the nano editor (nano helloworldblink.py) save it (Control-O, press Enter or Return, then quit with Control-X) and then execute it with superuser privileges (because you can’t access the GPIO pins as a regular user).

Before you run the nano editor, make sure you’re back in your home directory. You won’t be able to save this file to the anywhere under /sys.

$ sudo python helloworldblink.py

Is the LED blinking?

Since the while loop doesn’t really test for anything (True is always True, after all), this program would continue as long as the Raspberry Pi is powered. You have to forcefully stop it, by pressing the interrupt key combination Control-C.

Button, Button

Try now to connect a button switch to the GPIO and read its status. First, switch the Raspberry Pi off by typing this command:

$ sudo halt

Once the power is disconnected, take a button, a 220 ohm resistor and connect everything as in Figure 18-10. Check all connections before switching the Raspberry Pi on.

Alt Text

Figure 18-10. Connecting a button to the GPIO24 pin and an LED to the GPIO25 pin.

1. As you did before with the output pin, try and read the status of a pin by using the terminal only. Move to the special directory /sys/class/gpio and start a superuser shell:

2. $ cd /sys/class/gpio

3. $ sudo -s

4. #

5. Let your Raspberry Pi know that you are going to work with the GPIO24 pin:

6. # echo 24 > export

7. Next, change directory to the gpio24 directory. If you run the ls command here, you’ll now see the gpio24 directory. Enter it and see what it contains:

8. # cd gpio24

9. # ls

10.You’ll find the special files created by the Raspberry Pi. Next, create the direction file as shown to set the pin as an input:

11.# echo in > direction

12.You can detect whether the button is being pressed by reading the value file:

13.# cat value

The file contains 0 or 1, depending on whether the pin is pressed. Try holding down the button while you type that command.

14.When you’re done, unexport the pin, exit the root shell, and go back to your home directory:

15.# cd /sys/class/gpio

16.# echo 24 > unexport

17.# exit

18.$ cd


Let’s do the same in Python. To use pin 24 as an input, the code is:

GPIO.setup(24, GPIO.IN)

You can observe the pin status with the GPIO.input() function:


This will return True or False.

Example 18-2 shows the complete listing. Make sure you’re back in your home directory, then use nano to save it in a file as you did with the previous example (for example, nano button.py) and then run it as you did before (for example, sudo python button.py):

Example 18-2. Who pressed my button?

import RPi.GPIO as GPIO

import time

# Use logical pin layout:




GPIO.setup(led, GPIO.OUT)

GPIO.setup(button, GPIO.IN)

while True:

if (GPIO.input(button) == True):

GPIO.output(led, GPIO.HIGH)




GPIO.output(led, GPIO.LOW)

After importing the GPIO module and defining the convention to number the pins, you declare pin 25 as the output and pin 24 as the input. With while True , you have created an never-ending cycle; within the cycle, you check whether anyone has pressed the button (GPIO.input(24) == True) and, if so, switch the LED on (GPIO.output(25, GPIO.HIGH)) and write “Ouch!” to the screen. After one tenth of a second, the while loop resumes. If no one presses the button, the LED goes off.

If you look at the circuit, you will realize that the code is very similar to the one of the sketches you wrote for the Arduino.

Arduino and the Raspberry Pi

Now that you know how both the Arduino and the Raspberry Pi work, you can use the two boards together to get the best out of each one. With a Raspberry Pi, it is very easy to use peripherals such as a webcam, which an Arduino would hardly be able to access, or to connect to and interact with the Internet. On the other hand, you could use Arduino to acquire analog data, which you can’t do easily with the Raspberry Pi.

Even though you can install the development environment of Arduino on Raspberry Pi, you probably shouldn’t, because the Arduino editor and compiler require a lot of computing power. The best thing would be to program Arduino with your computer and then connect it to the Raspberry Pi with the sketch already loaded.

Let’s use an easy example of how to make the two boards communicate with each other: you’ll switch on an LED connected to the Arduino by pressing a button on the Raspberry Pi keyboard. Not exactly rocket science, but it is a starting point.

First, on the breadboard connect an LED to a 220Ohm resistor, then connect that to Arduino pin 13 and Arduino GND.

Connect the Arduino to a computer and load the sketch shown in Example 18-3.

Example 18-3. Switching the light on and off from the serial port (Arduino)

void setup()



pinMode(13, OUTPUT);


void loop()


int n = Serial.read();

if ((char)n == 'a')


digitalWrite(13, HIGH);


if ((char)n == 's')


digitalWrite(13, LOW);



It’s rather simple: in the setup section, you configure Arduino pin 13 as an output, and prepare the serial port. The loop section reads what comes from the serial port, and tries to understand what it has received by checking the characters against two expected values. If it has received an ‘a', it switches the LED on pin 13 on; if it gets an ’s', it switches the LED off.

Now, try to find out which serial port you need to use. Connect the Arduino to the Raspberry Pi with a USB cable just as you would connect the Arduino to a computer.

Right after you plug it in, type the command dmesg from the terminal; in the last lines of the output, you can see that your Arduino has been detected, and that its serial port is ttyACM0 (in which case, the filename will be /dev/ttyACM0:

[ 5307.783795] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 5307.783813] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[ 5307.783830] usb 1-1.4: SerialNumber: 74937303936351014261
[ 5307.826464] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device

If the port is anything other than /dev/ttyACM0, replace the port file name in line 2 of the following example with the correct port file name.

On the Raspberry Pi, you’ll write a program in Python to read what you type on the keyboard and send it over to Arduino, which will decide what to do with the characters it receives. In order to use the serial ports, you import the serial module, similar to Arduino’s Serial library. UseArduino = serial.Serial(port, 9600) to create an Arduino variable. Before working with the serial port, clean it with flushInput, in case there is some undesired character still in the queue. The while cycle keeps going until you type the letter q. In order to read from the keyboard, you use the raw_input function; each string is then printed onto the screen and sent to the Arduino with Arduino.write(str).

Example 18-5 shows the complete listing in Python. Save it in a file as you did for the other Python examples, and run it with python filename. Because you’re not accessing the GPIO pins, you don’t need to use sudo to run this program.

Example 18-5. Switching the light on and off from the serial port (Raspberry Pi)

import serial

port = "/dev/ttyACM0"

Arduino = serial.Serial(port, 9600)


while True:

str = raw_input(">:")

if (str == "q"):


print str


If there’s anything that doesn’t work, it might be because the serial module has not been installed. To check that, open a terminal and, in the Python interpreter, write:

import serial

If any error comes up, it is possible that the module hasn’t been installed. To install it, go to the Raspberry Pi terminal and type:

$ sudo apt-get install python-serial python3-serial

Let’s close this chapter with an exercise:

§ Modify the preceding Raspberry Pi and Arduino code to have the LED on Arduino flashing at increasing or decreasing speed upon pressing the < (less than) and > (greater than) keys.