Chapter 3. Raspberry Pi

This chapter will help you get started with your Raspberry Pi. If you are already familiar with the Raspberry Pi and have tried a little Python programming on the Raspberry Pi, then you might like to jump ahead to Chapter 4.

What Is a Raspberry Pi?

A Raspberry Pi is a single-board computer, complete with Linux operating system, USB connections for keyboard and mouse, and an HDMI connector for attaching a monitor.

There are actually a few variations on the Raspberry Pi, some historic and no longer manufactured. All of the Raspberry Pi models are broadly compatible, and you should not encounter any problems with the examples in this book, even if you have an old Raspberry Pi.

Figure 3-1 shows a Raspberry Pi 2 model B. On the righthand side of the board you will find four USB ports. These are useful for attaching a keyboard and mouse, as well as other peripherals, such as printers, scanners, and Flash drives.

Below the USB ports, you will find an RJ45 Ethernet socket that allows you to connect your Raspberry Pi to your home router via cable. You will need to get your Raspberry Pi connected to your network so that you can access the Internet and install software onto the Raspberrry Pi. It can be more convienent to cut out the cable and use a USB WiFi adapter. Such an adapter only costs a few dollars and can be plugged into a USB port. You do need to pick an adapter that is compatible, though. You can find a list of compatible devices at http://elinux.org/RPi_VerifiedPeripherals.

Figure 3-1. A Raspberry Pi 2 Model B

Working our way clockwise around the Raspberry Pi, we come to the stereo audio and composite video connector. This socket will mostly have headphones or an aux lead connected to powered speakers plugged into it, but the connector does also include an extra connection to allow you to connect composite video monitors using a special lead. Generally, the HDMI video connector is more likely to be used to connect a monitor or TV as it is much better quality than composite video. Between the HDMI and audio sockets is a flat cable connector to which a camera specially designed for the Raspberry Pi can be attached.

Next to the HDMI socket is a microUSB connector. This is only used to supply power to the Raspberry Pi using a 5V adapter.

Above the microUSB connector, on the underside of the board, is a slot that takes a microSD card. The Raspberry Pi does not have a conventional hard disk; instead, the operating system and all the files will be contained on a microSD card. 

On the top side of the board, you will find a set of header pins. These are called the general-purpose input/output (GPIO) pins; they can be used to connect the Raspberry Pi to various electronic circuits to allow it to control things.

Before the Raspberry Pi B+ was released, Raspberry Pis only had 26 pins on the GPIO connector rather than the 40 shown in Figure 3-1. All the projects in this book use just the 26 original pins that were kept on the new models, so even if you have an old Raspberry Pi, all the projects should still work.

Setting Up Your Raspberry Pi

You’ll need to connect a keyboard, mouse, and monitor to your Raspberry Pi in order to set it up. Once set up, you can unplug the keyboard, mouse, and monitor, and instead connect to your Raspberry Pi using Secure Socket Shell (SSH) from another computer. However, until you get to that stage, you will need to keep those things connected to set up your Raspberry Pi.

To set up your Raspberry Pi, you need the following items:

  • A USB keyboard and mouse (standard PC peripherals are just fine)
  • A monitor or TV with an HDMI input and an HDMI cable
  • A 5V microUSB power supply (at least 1 Amp) 
  • An Ethernet cable to reach to your router, or a USB to WiFi adapter
  • A microSD card (4GB OK but 8GB will give you more room for your own files and any programs that you download; choose a microSD card described as class 10, as this will help with performance)
  • A second computer and microSD card adapter to set up the SD card (alternatively, you can buy a microSD card with NOOBS—that is, New Out Of the Box Software—preinstalled)

Figure 3-2 shows a typical Raspberry Pi setup.

At least while you are installing the operating system, you should set up your Raspberry Pi where you can connect it directly to your router so that it has an Internet connection. Once the operating system is installed, you can configure a USB WiFi adapter and switch over to wireless if you prefer.

Figure 3-2. Typical Raspberry Pi setup

Preparing a MicroSD Card with NOOBS

When the Raspberry Pi was first launched, you had to use special image writing software to set up an SD card. However, NOOBS changed all that—it’s as easy to install as copying files onto the SD card and no special formatting is required.

You will find the latest, up-to-date instructions on using NOOBS to set up your microSD card here: https://www.raspberrypi.org/help/noobs-setup/.

When your Raspberry Pi boots up into NOOBS it will offer you a choice of operating system (Figure 2-3). Make sure that you select the recommended option Raspbian. 

After a lot of file copying and a reboot, your Raspberry Pi will be ready to use. At this point, if you have a USB WiFi adapter, you can configure it and join your wireless network using the WiFi Config utility that you will find under the Preferences section of the desktop menu.

Figure 3-3. NOOBS offering a selection of operating systems to install

Setting Up SSH

For many of the projects and experiments in this book, having a keyboard, mouse, and monitor attached to your Raspberry Pi is more of a hindrance than a help. SSH gives you command-line access to your Raspberry Pi over your network from a second computer. 

This means that, once you have finished setting it up, the only things that need to be plugged into your Raspberry Pi are a power lead and either a network cable or USB WiFi adapter. 

Click the LXTerminal icon at the top of your Raspberry Pi desktop (Figure 3-4). In the LXTerminal window that opens, type the following command (don’t include the $—that’s the command-line prompt):

$ sudo raspi-config
Figure 3-4. Starting LXTerminal

This will open the rasp-config tool for setting up your Raspberry Pi. Use the arrow keys to move down to the Advanced menu option and press Enter. Then use the arrow keys again to select SSH (Figure 3-5).

Figure 3-5. Enabling SSH using raspi-config

Click Enable, then select the Finish menu option.

Now that your Raspberry Pi is enabled for SSH remote access, it’s time to connect from your computer.

If you have a Mac or Linux computer, it will have its own terminal program that you can use to connect to the Raspberry Pi, so skip ahead to “SSH on Mac or Linux”. 

SSH on a Windows Computer

If you use Microsoft Windows, you should download and install Putty.

The installation looks a little odd, but actually, you just download putty.exe, which is the program itself. You can just save it somewhere (say on your desktop) and run it by double-clicking it. This will open the PuTTY Configuration window (Figure 3-6).

Figure 3-6. The PuTTY Configuration window

Enter the IP address of your Raspberry Pi in the “Host Name (or IP address)” field (see “Finding the IP Address of a Raspberry Pi”), and click Open. You will then be prompted to log in to your Pi (Figure 3-7). Enter a username of pi and a password of raspberry and that’s it, you are in. You can now type commands into PuTTY on your main computer, and they will be executed on your Raspberry Pi.

Figure 3-7. Remote control of your Raspberry Pi with SSH

SSH on Mac or Linux

If you use a Mac or a Linux computer, the software you need to connect to your Raspberry Pi is already on your computer. Open a terminal session and type the following command, substituting the IP address of your Raspberry Pi in place of the IP address of my Raspberry Pi  (192.168.1.23):

$ ssh 192.168.1.23 -l pi

The first time you do this, you will see the following message:

The authenticity of host '192.168.1.23 (192.168.1.23)' can't be established.
RSA key fingerprint is 48:8f:c3:07:c2:04:9e:8b:59:ed:53:2b:0b:d0:aa:e5.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.23' (RSA) to the list of known hosts.
[email protected]'s password:

You can go ahead and confirm the authenticity of the computer you are connecting to by typing yes. From now on, any commands that you type are actually happening on the Raspberry Pi rather than your other computer.

The Linux Command Line

If you are a Microsoft Windows or Mac user, you may never have needed to use the command line to interact with your computer. Linux, which runs on the Raspberry Pi, does, however, need you to type commands into a command line when installing software, copying and renaming files, running programs, or editing files.

You have already used the Raspberry Pi command line with the LXTerminal to set up SSH on your Raspberry Pi; now you can execute commands on the Raspberry Pi over SSH or directly using LXTerminal.

You may have noticed that whenever LXTerminal or your SSH session is ready for you to type a command, the last character on the line is the $ character. This is called the dollar prompt and is Linux’s way of telling you that it’s ready for the next command.

The Linux command line has the concept of the current directory. This is the directory that you are currently working in. So, if you want to run a Python program that is in a certain directory, you will normally need to set your directory to the directory containing the program before you run it. The command to do this is called cd (change directory).

When you first start an LXTerminal session the current directory is /home/pi. This is called your home directory. If your home directory contains a directory called make_action, then you can change to that directory by typing the following (which is changing directory relative to your current directory):

$ cd make_action

You can also type the whole path for the directory like this:

$ cd /home/pi/make_action

The Raspberry Pi code in this book is all written in the Python programming language. To run a Python program called test.py you would use this command:

$ python test.py

Another command that you will encounter quite often is sudo (subsititute user do). This is used to run the command that follows it as if you were a superuser. This is necessary because Linux tries to protect you from accidentally trashing your own system; superuser access is required to delete important files and to perform other important actions. Superuser access is also required to access the GPIO pins, which you will need to do a lot in this book.

For example, if test.py uses the GPIO pins, you would need the following command to run it:

$ sudo python test.py

Although all the Python code for this book is available as a download (see “The Book Code”), there will be times when you want to modify a program or other file. You can do this using the nano editor, which will also work just fine over SSH. To edit a file, just enter the command nano followed by the file you want to edit (if no file of that name exists, then nano will create it when you save the edit):

$ nano test.py

Figure 3-8 shows the nano editor in action.

Figure 3-8. The nano editor

Because nano is designed to work in a command-line environment such as the LXTerminal or over SSH, you need to use the cursor keys to move around the file rather than the mouse. When you are ready to save the file, press Ctrl-X and then Y followed by Enter to confirm the save.

The Book Code

The Raspberry Pi does not use a separate programming computer, so you just need to get all the program files used in the book onto the Raspberry Pi itself.

Although you can fetch the files down as a ZIP archive, as you would for the Arduino code (described in Chapter 2) a better way is to use Git, which is a tool for managing program code. 

Git keeps track of changes made to the code and will even merge together code from different programmers. The popular public source code repository GitHub uses Git. Git is preinstalled on Raspbian, so all you need to do on your Raspberry Pi to fetch all the code is to open an LXTerminal session, and run the following command:

$ git clone https://github.com/simonmonk/make_action.git

This will create a directory called make_action. In here you will find a python directory that contains two subdirectories named experiments and projects.

The advantage of using Git to fetch the program code is that any time you want to see if there are minor fixes or improvements to the book’s code, you can get these changes just by running:

$ git pull

Programming Guide

The best way to learn how to program is to start by modifying some existing simple programs and gradually understand how things work. All the programs that you need for this book are available for download, so programming expertise is not essential. However, it’s nice to have a basic idea of how things work.

Hello, World

Traditionally, when you’re working with a new language, the  first program you learn to write just prints out the words “Hello, World” on the screen. To try this out, fire up nano using the following command:

$ nano hello.py

The .py file extension identifies the program file as being Python. Next, type the following text into the nano editor and then save the file:

print('Hello, World')

Then run the program:

$ python hello.py
Hello, World

Tabs and Indents

Programmers have a style of laying out their code to make it easier to understand. In Arduino C, blocks of code inside a function or if statement are indented so you can see which lines of code belong to which command or function. In Python, this is not a matter of personal preference—Python insists upon it.

In Python, there are no { or } to show the start and end of a block of code—you have to use indentation to show which lines belong together.

For example, take a look at this fragment of code:

 while True :      
    GPIO.output(control_pin, False)
    time.sleep(5)
    GPIO.output(control_pin, True)
    time.sleep(2)
 print("Finished")

This is a while loop (just like while in Arduino C, as described in “Loops”). In this case, the condition is True. The value True is always True, the loop will continue forever. At the end of the first line, there is a colon (:). The colon indicates that what follows will be a block of code. So the colon in Python is just like the { in Arduino C, but there is no closing marker.

The lines inside the block must be tabbed in from the line above. As long as you are consistent, it does not matter how many spaces (or tabs) you indent the code. Most programmers tend to use four space characters for each level of indentation.

At the end of the block, there is no marker, but instead you just stop indenting the code. So in the preceding example, the final print command is outside of the loop. Because the while loop continues forever, this last line will never actually get run.

Variables

Variables in Python are like Arduino C, but differ because when you first use a variable, you do not have to specify whether it’s an int or a float or something else. You just assign it a value and there is nothing (apart from good sense) to stop you assigning the same variable to be an integer value one minute and a string the next. For example, the following code is perfectly legal, but not very sensible:

a = 123.45
a = "message"

Incidentally, when using strings, you can either use double quotes (as in the preceding example) or single quotes.

if, while, etc.

Python has an if and else structure just like Arduino C, but it uses a colon and indentation to indicate the blocks of code inside the if statement:

if x > 10 :
    print("x is big!")
else:
    print("x is small")

As you work your way through the book, you will learn more about loops and other programming structures. 

The RPi.GPIO Library

Like Arduino C, Python supports libraries—you just need to import them before you can use them in a program.   

This book is going to be doing a lot with the GPIO connector on the Raspberry Pi. The most popular Python library to control GPIO pins and the one used in this book is RPi.GPIO. 

This library is preinstalled with Raspbian, so you do not need to install anything; you can just import it into your program and start using it.

Confusingly, there are two naming conventions for the pins on a Raspberry Pi’s GPIO connector: one uses the positions of the pins on the connector (1, 2, 3, 4, etc.) and the other uses the functions of the pins. In the early days of Raspberry Pi, both were used fairly frequently. These days, pretty much everyone refers to pins based on their function. The RPi.GPIO library will work with both ways of pin naming, but you have to tell it which to use, so you will see the following code near the top of every Python program in this book:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

The first line imports the RPi.GPIO library and the second specifies the Broadcom (BMC), which is the name of the chip at the center of the Raspberry Pi.

Unlike the Arduino, the Raspberry Pi does not have analog inputs. The RPi.GPIO library does, however, support PWM analog outputs.

The GPIO Header

Figure 3-9 shows the connections available on the GPIO header. If you have an older Raspberry Pi, with only 26 pins, then the pins below the dotted line will not be present on your board. The projects in this book can be completed on all Raspberry Pi models, so only those 26 pins will be used.

This diagram is repeated at the end of the book in Appendix B as a handy reference. Unlike the Arduino, a Raspberry Pi does not have the pin names printed on the printed circuit board (PCB), making it difficult to tell which pin is which. You can make this easier by buying or making a template to fit over the pins, such as the Raspberry Leaf.

Notice how some pins have a number (say, 2) but also a second function listed next to them (say, SDA). When using the GPIO pins in your code, you always refer to them just by number.

Figure 3-9. The GPIO header

Digital Outputs

This example shows how you would set GPIO pin 18 (as indicated in Figure 3-9) to be a digital output and then set the output high:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, True)

When setting an output using GPIO.output, you can set it high using a value of True or 1, or low using False or 0.

Digital Inputs

Digital inputs on a Raspberry Pi work in much the same way as digital inputs on an Arduino:

GPIO.setup(18, GPIO.IN)
value = GPIO.input(18)
print(value)

You can also specify that the input has a pull-up resistor on it (see “Digital Inputs”) like this: 

GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Analog Outputs

Using analog outputs on a Raspberry Pi is a two-stage process. You first have to set up the pin to be an output, and then you have to define a PWM channel that uses that output.

You will find a fully explained example that uses this in “Experiment: Mixing Colors”.

Summary

In this chapter, you have learned how to set up your Raspberry Pi and get to grips with the Linux command line, and learned some of the basics of Python language that you will need to control things using the GPIO pins.

Now it’s time to get started with some practical experience. Chapter 4 will get you started using your Arduino and Raspberry Pi for real.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181