CHAPTER 1

Introduction to the Raspberry Pi

THIS BOOK WILL INTRODUCE you to the Raspberry Pi and provide 12 projects that will lead you through some simple, fundamental operations up to some fairly complex ones. The Raspberry Pi, despite its small size, is a fully functional computer capable of running a full-fledged Linux operating system. It is also the most inexpensive computer with this level of functionality that is presently available to the public.

The Raspberry Pi is a small board measuring 56 by 85 mm, about the size of a standard credit card. Nonetheless, it contains some very impressive functionality, as you will discover later in this chapter. This new board is shown in Fig. 1–1.

Image

Figure 1–1 The Raspberry Pi, a small Linux computer.

A look at a bit of history regarding the Raspberry Pi (or RasPi as I will now refer to it) and its originally intended market may help you understand the constraints and limitations that subsequently ensued. The RasPi concept began around 2006 with Dr. Eben Upton and his colleagues at the University of Cambridge’s Computer Laboratory in Cambridge, England. They were concerned about the decline in knowledge and skill levels of incoming computer science students as compared with those of earlier students. Dr. Upton decided to create an inexpensive computer, reasoning that it was likely that parents were not allowing their children to experiment with modern and relatively expensive PCs. This idea ultimately led to the development of the very inexpensive RasPi. This computer would provide an excellent opportunity for children to learn and experiment with programming, while not being a concern to parents if something should go horribly wrong and the board be destroyed.

Dr. Upton teamed with several other individuals to form the Raspberry Pi Foundation, a registered United Kingdom charity that promotes computer literacy and enthusiasm, especially among young children using the RasPi as their initial platform. They seem to be achieving these highly laudable goals, since they have greatly exceeded the initial estimate of selling 10,000 RasPi’s, and at the time of this writing, the total sales are approaching one million units. The foundation’s website is www.raspberrypi.org, where you will find all sorts of information about the board, current news, forums, FAQs, and so on.

A key design decision that kept costs low was to incorporate a SoC type chip on the board. SoC is short for System on a Chip—a technology that physically places the memory, microprocessor, and graphics processer in a type of silicon “sandwich” that in turn minimizes the printed circuit board (PCB) space and the accompanying PCB interconnecting board traces. The foundation eventually partnered with Broadcom to use its designs for both the microprocessor and graphics processors in the SoC. The SoC and some other key components and connections that you should know about are identified in Fig. 1–2.

Image

Figure 1–2 The SoC and other key components.

Although it is not critical to understand the Broadcom microprocessor in order to use the RasPi, it is still helpful to discuss it for a bit so that you will know why the RasPi is slower than your PC and why the low voltage of 3.3 V is used for interfacing the RasPi to the outside world. I will first cover the hardware aspects of the RasPi, followed by the software aspect.

Hardware

Broadcom 2835 Microprocessor/Graphics Processing Unit

The SoC uses the Broadcom BCM2835 as its microprocessor and graphics processing unit or GPU. The Broadcom company is what is known as a fabless supplier in that they provide the designs for their product in the form of Intellectual Property (IP) and other companies actually create the real silicon chips. Broadcom specializes in mobile-application-type processors including the type used in smartphones. The BCM2835 portion of the SoC itself is made up of an ARM1176JZF-S microprocessor running at 700 MHz and a Broadcom VideoCore® IV GPU.

The BCM2835 is designed for mobile applications, and hence, it needs to operate with minimal power so as to extend battery life. A fairly low microprocessor clock speed helps lower power consumption, and this is the reason the BCM2835 operates at 700 MHz, which is typically a quarter of the speed of a modern PC. Lower clock speed also means the processor can operate at a low voltage, thus decreasing the overall heat generated and extending chip life. The BCM2835 can be speeded up—also known as overclocking—to improve performance, but this is generally not recommended because the microprocessor can become operationally unstable and its life shortened. Be assured that the RasPi is sufficiently fast for all the projects in this book.

Broadcom has also graciously provided software drivers to allow the BCM2835 input and output pins to be connected to external peripherals. This software is in the form of a Python library that I will discuss later.

The Broadcom VideoCore IV GPU handles all the video and audio processing for the SoC. This GPU directly supports the OpenGL ES 2.0 standard that is essentially an Application Program Interface (API) capable of running on embedded hardware, which, in this case, is the Broadcom 2835. Loosely translated, this means the 2835 can easily display three-dimensional 3D graphics using all the requisite shaders and texture filters normally required for modern games and high-definition (HD) video. This chip implements in hardware a 1080p, 30 frames/sec, H.264 codec required for HD. That is an impressive performance.

I will not pursue this discussion any further other than to state that the BCM2835 is more than adequate to display all the graphics and output all the audio streams required for all the projects in this book.

Memory

There are two memory types used in the RasPi: dynamic random access memory (DRAM) and Secure Digital (SD) flash. The original version, model A, of the RasPi had 256 MB of RAM installed, while the latest, Model B, has 512 MB. The 512-MB chip is easily seen on the board as the top layer of the SoC sandwich. The SoC chip shown in Fig. 1–2 has top DRAM marked as supplied by Samsung with a part number K4P4G324EB ACC1, which translates to a lowpower 4-Gbit (512-MB) DRAM designed for mobile applications. This means that it too uses low voltage while maintaining reasonable clock speed. Having 512 MB of DRAM means the operating system will function very efficiently and programs should also run smoothly provided they are properly created.

The SD flash memory is used to store the operating system, all programs, and all other data that need persistence. In other words, nothing will be destroyed when the power is shut off. The RasPi uses SD flash memory in the same manner that a PC uses a hard drive to permanently store data and programs. You have a choice in selecting the memory size of a SD memory card that simply slides into a holder that is located on the underside of the RasPi, as shown in Fig. 1–3.

Image

Figure 1–3 Back side of the Raspberry Pi.

If you purchased your RasPi as part of a starter kit, you will have received a 4-GB SD card with a Linux OS distribution already installed on the card. A picture of this preprogrammed SD card is shown in Fig. 1–4.

Image

Figure 1–4 Preprogrammed SD card.

I will explain later on in this chapter how to create your own memory card so you do not have to purchase a preprogrammed SD card. Note that most SD cards also have a class designation on the label. The one shown in Fig. 1–3 does not, as it has had a customized label attached. The class designation relates to the minimum data-transfer speed the SD card can handle. Remember, the SD card is taking the place of a hard drive, so the faster, the better. Class 4 is very typical of the consumer grade SD cards that are available in most office supply stores. Class designations and their associated minimum transfer speeds are shown in Table 1–1.

Table 1–1 SD Card Class Designations

Image

What you should take away from this SD class discussion is that the higher the class number of the SD card used in the RasPi, the better it will perform. The only downside is that SD cards with high class numbers are more expensive than ones with lower numbers, sometimes more than twice the cost for the same storage capacity. My only suggestion is to purchase a class 4 or higher; anything less and you will be disappointed in your RasPi’s slow response.

RasPi Connectors

The RasPi has nine connectors: power, High-Definition Multimedia Interface (HDMI), analog composite video, audio, ethernet, Universal Serial Bus (USB), two future expansion connectors, and the General Purpose Input/Output (GPIO) interface. Each connector has specific functions that I will discuss in the following sections, except for the expansion connectors, which are not yet used, although I will tell you what I know about them as of this writing. There is no particular order to this discussion although I have left the GPIO connector for last because it is by far the most complex and, hence, requires the most explanation.

Power Connector

The power connector shown in Fig. 1–5 is a micro USB socket that is wired to pass the 5-volt (V) direct current (DC) lines from a micro USB plug, also shown in the figure. (Since all voltage in this project is DC, I will use just the notation V for V DC.) No data connections are wired to this socket. You can use almost any available smartphone charger that has a micro USB connector or use the power supply that came with the RasPi kit, if that’s what you purchased.

Image

Figure 1–5 Micro USB power connector.

Figure 1–6 shows a RasPi kit power supply that is rated to supply 5 V at 1000 milliamperes (mA) or 1 ampere (A). The regulatory compliance document supplied with this RasPi states the following:

Image

Figure 1–6 External power supply.

This product shall only be connected to an external power supply rated at 5 V, and a minimum current of 500–700 mA for model A and 700–1200 mA for model B.

I will have a bit more to say regarding current consumption when I discuss the USB connector.

HDMI Connector

The RasPi provides video and audio using a fully compliant HDMI, which is modern by most standards The board socket and sample cable plug are shown in Fig. 1–7.

Image

Figure 1–7 HDMI connector and cable.

I have previously discussed the Broadcom GPU chip that controls the HDMI output. To keep things simple, the book projects will use only the “standard” type of audio/video output and will not take advantage of the true potential of the RasPi’s multimedia capabilities. Trust a fellow Evil Genius that you will be working hard to complete the book projects without getting involved with HDMI development tasks.

One real problem that you will likely encounter is the lack of an HDMI input port for your computer monitor. This leaves you with three choices for observing the RasPi video:

1. Use the composite video output with a compatible analog monitor

2. Use an adapter to convert from HDMI to Video Graphic Array (VGA) or Digital Video Interface (DVI)

3. Take over the family’s flat panel digital TV

The first option is really not a very good choice, since the quality is diminished as compared to what is displayed by a high-quality computer monitor. The second option is the preferred method, as it yields the best results using your existing computer resources. Choosing the third and final option will likely result in family discord and upheaval for which I will take no responsibility!

The choice of an HDMI to VGA or HDMI to DVI adapter will, of course, depend upon what type of monitor input you have. Most monitors have a VGA input, and an adapter for that type of input is shown in Fig. 1–8. The HDMI to DVI adapter is similar, and the cost for each is also similar.

Image

Figure 1–8 HDMI to VGA adapter.

The HDMI connection also contains a very interesting surprise. The RasPi can act as a very sophisticated remote control for HDMI-CEC compliant devices. The CEC suffix is short for Consumer Electronics Control, which is a one-wire, bidirectional serial bus link protocol used for the control of audio and video devices. HDMI-CEC has been implemented by many A/V manufacturers including Sony with its Bravialink, LG with its Simplink, Sharp with its Aquos Link, Samsung with its Anynet+, and so on. The bad news is that there is currently no RasPi software support available for HDMI-CEC remote control functions. The good news is to simply wait for a short time because new software apps are constantly being created, free of charge. By the time you are reading this, the RasPi should be able to turn your digital flat-panel TV on and off as well as control your A/V receiver, DVD player, Blu-Ray player, etc. The RasPi will become the ultimate remote control. For more information, go to http://elinux.org/CEC_(Consumer_Electronics_Control)_over_HDMI.

Analog Composite Video Connector

The RasPi also produces an analog video output from the RCA socket, as shown in Fig. 1–9.

Image

Figure 1–9 Analog video connector and cable.

This analog video functionality was deliberately included in the RasPi design to accommodate all those situations where only analog monitors or analog TVs are available, especially in developing countries. There is, however, an upside to the composite output. To monitor project parameters in real time, you can use small analog monitors. These monitors are fairly inexpensive and can often be battery powered, which is not a realistic option with larger computer monitors. I have included the use of a small, battery-powered analog monitor in one of the book projects. This monitor is shown in Fig. 1–10.

Image

Figure 1–10 Small analog video monitor.

Audio Connector

The RasPi is also capable of creating an analog audio output in full stereo. The output is from a standard 3.5-mm stereo jack as shown in Fig. 1–11.

Image

Figure 1–11 Analog audio connector and cable.

This audio would normally be the analog equivalent of the digital audio outputted from the HDMI connector. There is a book project that uses this analog output to play MP3 songs. You will need an audio amplifier to hear the music, as the RasPi does not generate a powerful enough signal to drive an unamplified speaker. However, a good quality set of headphones will work.

Ethernet and USB Connectors

Both the Ethernet and USB connectors are shown in Fig. 1–12. I will discuss the Ethernet connector first, followed by the USB connectors.

Image

Figure 1–12 Ethernet and USB connectors with cables.

The Ethernet connector shown on the left in the figure is a standard RJ45 connector. You would simply plug your standard Ethernet patch cable into the socket and connect the other end to either your router or switch, if that is the way you have setup your home network. The RasPi will then automatically “negotiate” with your router to gain an Internet Protocol (IP) address in a process known as Dynamic Host Configuration Protocol (DHCP). There are five light-emitting diodes (LEDs) to the left side of this socket as you look at it head on. The LED furthest away from the socket is labeled “100.” If it is shining with a yellow light, this means that a 100-megabits-per-second (Mb/s) connection was made. The next two LEDs, just to the right of the 100 LED, are labeled “LNK” and “FDX”. These LEDs shine with green lights to indicate that the Ethernet is alive and operating. Checking these LEDs is a quick way to determine if your Ethernet connection is working or if something, somewhere, has gone down.

There is a stack of two USB connectors shown on the right-hand side of the figure. These are normal USB connectors in the sense that USB peripherals will be recognized when plugged into the sockets. The only issue with these is that the RasPi cannot supply the standard amount of current according to the USB specification, which is 500 mA per socket. Remember that I mentioned earlier in Fig. 1–6 that the power supply in the RasPi kit provides up to 1000 mA. If peripherals plugged into these sockets took 500 mA each, there would be none left for the poor RasPi! Obviously, this situation should not be allowed to happen, and there is a good and relatively cheap solution. I use a powered USB hub, as shown in Fig. 1–13, that can easily provide all the current that typical unpowered USB peripherals require.

Image

Figure 1–13 Self-powered USB hub.

There is one USB cable that connects between the hub and the RasPi. That leaves one available USB socket on the RasPi for a low-power peripheral, such as a thumb drive. The number of USB ports provided by the hub varies with the manufacturer; however, four or five ports are fairly common. The power supply shown in the figure is rated for 2100 mA, which precisely matches the USB specification for four ports and a little left over for the hub internal electronics.

Future Expansion Connectors

Two connectors prominently populated on the RasPi are not currently used. Referred to as “future expansion” connectors, they reflect the dynamic nature of the RasPi project. Fig. 1–14 is a close photo of one of the connectors, labeled “S2.” This connector is a 15-way, flat-flex connector designated for use with the Camera Serial Interface (CSI-2). A prototype digital serial camera was just introduced at an international electronics show at the time of this writing. The other flat-flex connector labeled “S5” and located just behind the Ethernet RJ45 connector is designated as a Display Serial Interface (DSI) that will eventually drive a Sony Low Voltage Differential Signaling (LVDS) serial display. You should check the RasPi website for the latest news regarding the RasPi.

Image

Figure 1–14 Expansion connectors.

GPIO Pin Interface Connector

The General Purpose Input Output (GPIO) connector has 26 pins positioned in two rows of 13 pins each. Fig. 1–15 shows this connector with pins 0, 1, 25, and 26 pointed out.

Image

Figure 1–15 GPIO connector.

Table 1–2 details pin assignments with both the RasPi pin designations and the BMC2835 pin designations. Using two different sets of pin designations is confusing, but unfortunately, that is the situation with this board. I will try to use the RasPi pin designations whenever possible; however, there will be situations where the software will require the use of the BMC2835 pin designations. I will try to be as clear as possible regarding the exact pin that is being used and for what purpose.

Table 1–2 GPIO Pin Descriptions

Image

The Universal Asynchronous Receiver/Transmitter (UART), Serial Peripheral Interface (SPI), and Inter-Integrated Circuit (I2C) functional pins listed in the table may all be reconfigured as GPIO pins. These are shown with an asterisk in Table 1–2. This means that up to 17 GPIO pins (8 existing GPIO + 9 reconfigurable) are available for hardware interfacing, provided that the functions mentioned before are not needed.

Figure 1–16 shows all the GPIO connector pins with the BCM2835 pin designations. You should always crosscheck your connections with this figure anytime that you are directly wiring to this connector.

Image

Figure 1–16 GPIO connector pins with the BCM2835 pin designations.

CAUTION All GPIO voltage levels are 3.3 V, not 5 V tolerant. There is no overvoltage protection incorporated on the RasPi; and if you inadvertently subject a GPIO pin to 5 V, you will wreck your RasPi. I will not take any responsibility for such foolish actions, as you have been warned!

I have incorporated hardware buffers into projects where 5-V sensors interface to the RasPi, thus avoiding any chance of damaging the RasPi due to an input voltage overload. You must always pay careful attention to how the projects are wired because it is easy to damage the RasPi through an inadvertent construction mistake.

Digital Signal Voltage Level

The RasPi operates at a positive power-supply voltage (Vdd) of 3.3 V with the digital logic levels, shown in Table 1–3. This means that any GPIO input voltage greater than 2.7 V will be detected as a logical one or HIGH. Any voltage input that is less than 0.7 V will be detected as a logical zero or LOW. However, the input voltage can never exceed 3.3 V, or it will destroy the GPIO pin circuit.

Table 1–3 Digital Signal Voltage Levels

Image

It turns out that standard 5-V logic accepts 3.3 V as a logical one or HIGH and anything less than 0.7 V as a logical zero or LOW. This is exactly the reason that a RasPi can output to a 5-V logical device. The difficulty happens if a 5-V device inputs into a GPIO pin. The 5-V logical device has the logic HIGH voltage range of approximately 4.4- to 5-V that will immediately burn out the GPIO pin input circuitry.

Current Limits

There are also some current draw limitations for both the 3.3-V and 5-V power pins. The limitations are dependent upon the RasPi model, as shown in Table 1–4.

Table 1–4 Raspberry Pi Current Consumption vs Model

Image

Every GPIO pin can sink or source a limited amount of current ranging from 2 mA up to 16 mA. This means that you must be very careful about the current demands put on the RasPi as well as how much current it will accept without causing problems.

GPIO Pin Expansion

Recently, the Raspberry Pi Foundation made a revision to the Model B that added access to some additional GPIO pins that were not available in the earlier production run. This latest board is designated rev 2, while the earlier version is designated rev 1. The additional pins are plated PCB holes, as shown in Fig. 1–17, and are located next to the GPIO connector.

Image

Figure 1–17 Additional GPIO pins available for expansion.

Table 1–5 shows all the additional pins with their RasPi and BMC designations. Pin 1 is the square plated hole located in the upper left corner of P5. You will need to install a 12 pin connector to access the pins. The connector is supposed to be installed on the board’s underside per Note 3 on the rev 2.0 board’s schematic, which is available at http://www.raspberrypi.org/wp-content/uploads/2012/10/Raspberry-Pi-R2.0-Schematics-Issue2.2_027.pdf. A suggested connector is shown in Fig. 1–18. You will not need any of these additional pins from P5 to build any of the projects in this book.

Table 1–5 Additional GPIO Expansion Pins

Image

Image

Figure 1–18 GPIO pin expansion connector.

Interrupts

Each GPIO pin can also accommodate what are known as interrupts. An interrupt is an event that stops or “interrupts” the normal programming flow and directs the microprocessor to execute some special handler program, or code, for the interrupt source. Interrupts may be triggered in several ways:

Image    HIGH level detected

Image    LOW level detected

Image    HIGH to LOW transition detected

Image    LOW to HIGH transition detected

Using interrupts will certainly improve performance, but at the expense of adding a certain level of complexity to the software.

Serial Protocols

There are several serial protocols shown in the pin descriptions that I wish to discuss briefly.

SPI Serial Protocol

The first is the Serial Peripheral Interface (SPI), which is shown in the Fig. 1–19 block diagram.

Image

Figure 1–19 SPI block diagram.

The SPI interface (pronounced “spy” or “ess-pee-eye”) is a synchronous serial data link. A clock signal is needed because it is synchronous. It is also a full-duplex protocol, which means that data can be simultaneously sent and received from the host and slave. SPI is also referred to as a Synchronous Serial Interface (SSI) or a 4-wire serial bus.

The four interconnecting signal lines between the SPI host and SPI slave shown in Fig. 1–19 are explained in Table 1–6.

Table 1–6 SPI Signal Lines

Image

I2C Serial Protocol

The next serial protocol that I will discuss is the Inter-Integrated Circuit interface or I2C (pronounced “eye-two-cee” or “eye-squared-cee”), which is also a synchronous serial data link. Fig. 1–20 is a block diagram of the I2C interface, showing one master and one slave. This configuration is also known as a multidrop or bus network.

Image

Figure 1–20 I2C block diagram.

I2C supports more than one master as well as multiple slaves. This protocol was created by the Philips Company in 1982 and is a very mature technology, meaning it is extremely reliable. Only two lines are used: SCLK for serial clock and SDA for serial data. Table 1–7 shows the RasPi names for both the clock and data lines.

Table 1–7 I2C Signal Lines

Image

UART Serial Protocol

The last serial protocol shown in Table 1–2 is the standard Universal Asynchronous Receiver Transmitter (UART) that uses two pins in the RasPi and is shown in the block diagram in Fig. 1–21.

Image

Figure 1–21 UART block diagram.

The UART protocol needs no clock signal, just as it is described by the asynchronous adjective in its name. The RasPi transmits data on the pin named TXD0 and receives on the pin named RXD0. There is also no concept of a master or slave in this protocol, since it is used primarily for data communications instead of for control, which is the focus of both the SPI and I2C interfaces.

All three serial protocols described in this section are implemented in hardware, meaning that there is actual silicon dedicated to performing the protocol functions. This is the most efficient and fastest way to provide these serial interfaces, but it is not the only way. You can implement these same serial interfaces by using uncommitted GPIO pins and software. Although this would provide nearly the same functionality as the hardware implementation, it would not be as fast. The term “bit-banging” is often used to describe this approach. Sometimes you must use bit-banging when the hardware is not available.

I will now jump into the heady software arena; I’m sure you already sense that hardware and software are closely linked in the RasPi.

Software

The RasPi was designed to be run with a Linux operating system. This design decision stands in stark contrast to many other similar microprocessor boards, including the popular Arduino series, that do not operate in this fashion. This is not to imply that an Arduino board is inferior to the RasPi but simply to show that using the RasPi brings additional flexibility and capability to projects because of the Linux environment.

I will not start this discussion with a Linux tutorial, since there are many good Linux resources available on the web. Google (or your favorite search engine) will turn up many hits regarding Linux tutorials. I will instead use Linux commands and procedures, and explain them as I go along in a mentor capacity, as if I were standing beside you as you execute the commands. Additionally, I will be using the Python language to program, or code, the RasPi and will provide more guidance regarding how Python works and how it is applied with the RasPi, as it is the key to success in using the board and in understanding its operation with the underlying project code.

Initial Startup

A suggested RasPi setup that uses the connections discussed in the hardware section is shown in Fig. 1–22. This setup will be the basis for your projects once you add some prototyping hardware to the RasPi. Right now, I will be using the setup to get the RasPi configured in a proper manner to enable project development. You should connect all the components as shown in the figure, leaving the USB power connection for last. The RasPi will attempt to start up when the USB power cord is plugged in; and if you have not finished connecting all the other components, it is entirely possible that they will not be recognized in the startup sequence and your system will either not start or not operate correctly. I will also assume that you are using a “prebuilt” Linux distribution that is provided with the RasPi starter kit or purchased separately. This 4 GB card should also be plugged into the SD card holder prior to power being applied to the RasPi.

Image

Figure 1–22 A suggested RasPi configuration.

CAUTION Inserting or removing an SD card while the RasPi is powered on is never a good idea. Bad things can happen including data corruption or worse.

Also, now would be a good time to skip down to the section that discusses how to load your own Linux distribution on an SD card if you did not purchase a starter kit or a “prebuilt” SD card.

You should see the initial configuration screen, shown in Fig. 1–23, on the monitor after you connect the USB power to the RasPi. Please be patient; it takes a while. You will at first see a massive amount of text scrolling by on the screen, which will make absolutely no sense to you if you are not familiar with Linux.

Image

Figure 1–23 Raspberry Pi configuration screenshot.

Suggested configuration settings are shown in Table 1–8 along with some comments regarding why a particular setting was selected.

Table 1–8 Suggested Configuration Settings

Image

After you finish the configuration, the monitor prompt will eventually show. It is waiting for you to enter the user name, which is pi.

Image

Next, the password prompt shows Password:. Enter raspberry.

Image

Please note I am not giving away any secrets, as every unmodified RasPi Linux distribution is created with this default password. You may have changed it in the configuration menu; if so, enter that password.

Next type startx and press Enter.

Image

This will create the GUI desktop, as shown in Fig. 1–24.

Image

Figure 1–24 Raspberry Pi GUI desktop.

Congratulations, it is now about 15 pages into the book, and you now have the first indication that you have a working and useful Linux computer. Fear not; progress will be much faster from now on. To partially accomplish this goal, I will minimize the number of screenshots and simply use text to show you what to enter and how the computer responds.

Preparing your own SD card using a Windows PC

You will need two items other than the card itself. First you will need to download and install a program named win32diskimager.exe. This program is available at http://sourceforge.net/projects/win32diskimager/. The file is in a compressed Zip format from which you have to extract the program before running it. Note that in spite of the win32 in the name, this app works without a problem on my Win7, 64-bit laptop.

The second item you will need is the image file for the RasPi Linux distribution that you desire to install. The current version, at the time of this writing, may be downloaded from the main Raspberry Pi website http://downloads.raspberrypi.org/images/raspbian/2012-10-28-wheezy-raspbian/2012-10-28-wheezy-raspbian.zip. It is a very large Zip file (647 MB) from which the Linux distribution must be extracted before it can be used as a disk image file. The Raspberry Pi Foundation currently appears to be updating the Wheezy-Raspian Linux distribution almost every month. This is subject to change, so take advantage of it while it lasts.

It is now a simple matter to create your own SD card once you have the image and the disk writer program. Insert a blank SD card into the PC, run the app, and then browse to the location where the image is stored. Then click on Write, and you will get a warning about destroying existing data on the card. Click OK and wait. It takes several minutes to create the image. You now have your own Linux distribution on an SD card. Also, remember that you can rewrite an SD card as often as you want, so feel free to experiment with different distributions.

I now need you to create a new SD card, both to ensure that you understand this process and that you have a specific distribution available that will also support the Chap. 10 book project, which requires what is known as the “1-Wire” serial protocol. This distribution is named Occidentalis V0.2 and is available at http://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-2. This distribution was created by the kind folks at Adafruit, where I purchase most of my RasPi goodies. The unusual name derives from the Latin name Rubus Occidentalis for the black raspberry, which is apparent from the GUI desktop that appears when this distribution is running, as shown in Fig. 1–25.

Image

Figure 1–25 Occidentalis GUI desktop.

Some Linux Fundamentals

As I promised you earlier, I am not going to provide a tutorial on Linux in this book. However, you will still need to have some very basic knowledge of it to understand what is happening with the commands being processed. The discussion below is for readers with a very limited knowledge of Linux. Feel free to skip this section if you already have a basic to good understanding of Linux.

The Linux operating system is based upon Unix, and it has assigned built-in privileges, which limit most users to some extent but allow one user unlimited access. This unlimited user is named root and essentially is equivalent to an administrator level in a Windows operating system. Some commands can be run or executed only by root, again for security reasons. There is a fundamental computer security principle known as “least privilege” by which users are granted only as much access or privilege as they need to complete their task.

It is not considered a good idea to run all tasks or programs as root, so most of the time you will be running as the user named pi. However, as I mentioned earlier, some commands can only be run as root. The answer to this conundrum is to “promote” an ordinary user to what is known as a super user. The sudo command accomplishes this neat feat. I will frequently use the sudo command with other commands, and you now know why.

I will also typically use terminal windows to execute commands, as most of the time I will have the GUI desktop running. There are two flavors of terminal windows available, the Lightweight X11 Desktop Environment (LXDE) for normal users and a root level terminal. The only effective difference between the terminal windows is that I have to type sudo in the LXDE terminal while this is not required in the root terminal, since it already operates at that level.

You will also need to create some Python code to program the RasPi. I use a very simple but effective text editor named nano. All you need to run the editor is to open a terminal window and type nano test_my_project.py if you wanted to either create or open an existing file named test_my_project.py. The editor program has all the important commands listed at the bottom of the editor window. For example, to save the editor buffer, you have to press and hold the control key while simultaneously pressing the “o” key. This is shown as ^o on the help screen.

A few of the very common Linux commands are shown in Table 1–9. It might be helpful to refer to this table when you are trying to understand why I entered a particular command as you progress through the projects.

Table 1–9 Commonly Used Linux Commands

Image

Python

I have chosen to use Python to program the RasPi for several reasons. First, and most importantly, it is a simple programming language to use, and most beginners can start to use it immediately with little to no trouble. Second, despite being simple to use, it is a real programming language and shares most of the attributes that are common with other highlevel, high-powered languages, such as C++ or Java.

You should visit the official Python website, http://www.python.org where you will find a wealth of information regarding Python. This site should be your primary resource to use to answer any of your questions regarding the language. There are also many good Python books available, including Python Programming for the Absolute Beginner, third edition by Michael Dawson and Think Python by Allen Downey. Another useful reference would be Simon Monk’s Programming the Raspberry Pi: Getting Started with Python. Dr. Monk’s book is concise, with a brief but thorough introduction to Python fundamentals plus the bonus of a few projects at the end of the book.

Python is classified, in computer science terminology, as a high-level language, which, roughly translated, means that Python users are thinking in abstract terms. The C language, in comparison, is a fairly low-level language in which programmers must contend with bits, bytes, and memory locations. The concept of abstractions and abstract data types will become clearer as we start developing Python programs.

The Python language design encourages the creation and use of modules that can be reused. New functions, modules, and classes can easily be added. Software reuse is a key goal that all programmers should try to adopt. It makes no sense to keep reinventing the wheel when proven solutions have already been developed and are available for reuse. We will see this reuse in action in the very first project program.

Python is also an interpreted language, which means that the code is executed line-by-line by the Python “engine” as it is encountered. Programs using interpreted languages typically run slower than programs that have been compiled and linked. This performance hit will not be an issue with any of the programs within this book. The advantage of interpreted programs is that they are considerably easier to modify and rerun as compared to compiled programs. All you have to do is make any needed changes in an editor, save the code, and then rerun the program in the Python shell. This significantly reduces program development time and, at the same time, increases your productivity and efficiency.

One other detail should be mentioned before I show you how to start developing your first Python program. The language is not named after the reptile but instead takes its name from the famous BBC show, “Monty Python’s Flying Circus.” Apparently, the Python creators were great fans of the show, and they currently encourage authors (or bloggers now) to incorporate related humour when writing about Python.

IDLE

IDLE is the name of an application that creates and runs the shell environment that I will use to develop and test your Python programs. Fig. 1–26 shows a portion of the desktop with two IDLE icons appearing.

Image

Figure 1–26 IDLE desktop icons.

The top icon opens a Python version 3 shell, while the icon directly underneath opens a Python version 2 shell. I will be using the version 2 shell, as that Python version is compatible with the software libraries that are needed to run the hardware used in the projects.

User interaction using the Python shell is intuitive; results are instantly displayed after an operation is performed and the Enter key is pressed. Adding 7 + 5 with the sum displayed below the input numbers is shown in Fig. 1–27.

Image

Figure 1–27 A simple Python operation.

Displaying text in the Linux shell is also easy to accomplish; simply use the print function. Traditionally, the first program to be run in most programming books is the so-called “Hello World” program. I do not like to trifle with tradition and will adhere to this unwritten rule. Now it is perfectly possible to execute the print command and see Hello World displayed below, as is shown in Fig. 1–28.

Image

Figure 1–28 Python print command.

As this book is printed in monochrome, I will point out the following as you observe the output in the Python shell. The word print is reddish-orange, as it is a reserved word describing a preset function. The words Hello World in the parentheses following the print function are shown in green to indicate a string of characters. Character strings are enclosed between single quotes. Finally, the words Hello World displayed below the print function are in blue, as they represent a string output. This default color coding of program code is fairly standard with various development tools; however, the exact colors assigned to the different elements will vary.

From this point on, I will now use text only to show the shell prompt, commands, operations, and results to conserve valuable book space. You should also carefully observe the Linux shell because there may be information shown that I do not transcribe.

I will now show you how to create a very simple program that produces the same result as discussed above. I will use the nano editor to write the program and save it. I will then recall the saved program and run it from the Linux shell.

Open an LXDE terminal window and type:

Image

Next type:

Image

Press the key combination Ctrl and the letter o. (I will show this as ^o from now on.)

Image

This action will bring up a prompt at the bottom of the editor, requesting the name of the file in which to save the buffer’s contents. Type:

Image

The .py is a standard Python program extension. Fig. 1–29 shows the nano editor at this point in time.

Image

Figure 1–29 nano editor.

Type

Image

 to exit nano. There will now be a Python program named Hello.py in your home pi directory.

A Python shell must now be opened to allow the file that I just created to be opened and run. Opening the file is done by clicking on the File menu tab and then clicking on Open from the drop-down menu. A file browser dialog box will be opened that shows the contents of the pi directory. Select the Hello.py file, as shown in Fig. 1–30.

Image

Figure 1–30 Opening a file in the Python shell.

Selecting the Hello.py file will cause a second window to appear on the desktop with the contents of Hello.py shown in the window. This is very convenient in that you can modify the file contents without affecting any of the content happening in the Python shell. To execute the program, you must be in the second window that was just opened where you can either open the Run menu tab and select Run or simply press the F5 function key. The Hello.py program results appear in the Python shell, as can be clearly seen in Fig. 1–31.

Image

Figure 1–31 Running a program from the Python shell.

Summary

I have covered a lot of material in this chapter, from introducing the RasPi and a bit of its history to explaining the role that its inventors would like it to fulfill. I also covered the hardware aspects, as you need to understand the design decisions that went into the RasPi and the consequent constraints and attributes that you must consider when incorporating this board into a real world project.

A brief Linux introduction was covered to get you started in using this great operating system. Most people find that once they become proficient in using Linux, especially at the command-line level, they look at MS Windows with a newfound disdain. I am not pooh-poohing Windows; I am simply saying that Linux gives you much greater control of your programming environment than you could achieve by using Windows.

Next I discussed Python and demonstrated how simple it is to start programming the RasPi with the traditional “Hello World” program. Using the Python shell named IDLE just makes the whole effort very easy and, I hope, enjoyable.

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

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