Kirchhoff Lab

6/recent/ticker-posts

Introduction of Raspberry Pi

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 can discover many project. 

A look at a bit of history regarding the Raspberry Pi and its originally intended market may help you understand the constraints and limitations that subsequently ensued. The Raspberry Pi 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 PC. This idea ultimately led to the development of the very inexpensive Raspberry Pi. 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 Raspberry Pi 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 Raspberry Pi’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 System on a Chip type chip on the board. System on a Chip 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 System on a Chip. The System on a Chip and some other key components and connections that you should know about are identified in the figure bellow.

Figure: Key components of raspberry pi

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

Hardware Broadcom 2835 Microprocessor/Graphics Processing Unit

The System on a Chip or 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 System on a Chip 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 Raspberry Pi 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 System on a Chip or 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 several project. 

Memory 

There are two types of memory used in the Raspberry Pi. They are dynamic random access memory (DRAM) and Secure Digital (SD) flash. The original version, model A, of the Raspberry Pi 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 System on a Chip sandwich. In that figure of key components has top DRAM marked as supplied by Samsung with a part number K4P4G324EB ACC1, which translates to a low power 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 Raspberry Pi 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 Raspberry Pi,

If you purchased your Raspberry Pi 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. 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 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 as System on a Charioted minimum transfer speeds are-

  • Class 2 – 2MB/sec
  • Class 4 – 4MB/sec
  • Class 6 – 6MB/sec
  • Class 10 – 10MB/sec

What you should take away from this SD class discussion is that the higher the class number of the SD card used in the Raspberry Pi, 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 Raspberry Pi’s slow response.

Raspberry Pi Connectors 

The Raspberry Pi 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 a micro USB System on a Chipset that is wired to pass the 5-volt (V) direct current (DC) lines from a micro USB plug. (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 System on a Chipset. You can use almost any available smartphone charger that has a micro USB connector or use the power supply that came with the Raspberry Pi kit, if that’s what you purchased. A Raspberry Pi kit power supply that is rated to supply 5 V at 1000 milli Amperes (mA) or 1 ampere (A). The regulatory compliance document supplied with this Raspberry Pi.

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 Raspberry Pi provides video and audio using a fully compliant HDMI, which is modern by most standards. 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 Raspberry Pi’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 Raspberry Pi video:

  • Use the composite video output with a compatible analog monitor
  • Use an adapter to convert from HDMI to Video Graphic Array (VGA) or Digital Video Interface (DVI)
  • 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. The HDMI to DVI adapter is similar, and the cost for each is also similar. The HDMI connection also contains a very interesting surprise. The Raspberry Pi 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. The bad news is that there is currently no Raspberry Pi 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 Raspberry Pi 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 Raspberry Pi will become the ultimate remote control.

Analog Composite Video Connector

The Raspberry Pi also produces an analog video output from the RCA System on a Chipket. This analog video functionality was deliberately included in the Raspberry Pi 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.  

Audio Connector

The Raspberry Pi is also capable of creating an analog audio output in full stereo. The output is from a standard 3.5-mm stereo jack. 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 Raspberry Pi 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 here. I will discuss the Ethernet connector first, followed by the USB connectors. You would simply plug your standard Ethernet patch cable into the System on a Chipket and connect the other end to either your router or switch, if that is the way you have setup your home network. The Raspberry Pi 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 System on a Chipket as you look at it head on. The LED furthest away from the System on a Chipket 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 System on a Chipkets. The only issue with these is that the Raspberry Pi cannot supply the standard amount of current according to the USB specification, which is 500 mA per System on a Chipket. Remember that I mentioned earlier that the power supply in the Raspberry Pi kit provides up to 1000 mA. If peripherals plugged into these System on a Chipkets took 500 mA each, there would be none left for the poor Raspberry Pi! Obviously, this situation should not be allowed to happen, and there is a good and relatively cheap solution. I use a powered USB hub, that can easily provide all the current that typical unpowered USB peripherals require.

There is one USB cable that connects between the hub and the Raspberry Pi. That leaves one available USB System on a Chipket on the Raspberry Pi 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 Raspberry Pi are not currently used. Referred to as “future expansion” connectors, they reflect the dynamic nature of the Raspberry Pi project. 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 Raspberry Pi website for the latest news regarding the Raspberry Pi.

GPIO Pin Interface Connector

The General Purpose Input Output (GPIO) connector has 26 pins positioned in two rows of 13 pins each. Using two different sets of pin designations is confusing, but unfortunately, that is the situation with this board. I will try to use the Raspberry Pi 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.

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. This means that up to 17 GPIO pins are available for hardware interfacing, provided that the functions mentioned before are not needed.

I have incorporated hardware buffers into projects where 5-V sensors interface to the Raspberry Pi, thus avoiding any chance of damaging the Raspberry Pi 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 Raspberry Pi through an inadvertent construction mistake.

Digital Signal Voltage Level

The Raspberry Pi operates at a positive power-supply voltage of 3.3 V with the digital logic levels. 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.

  • 1 or high = 2.7 to 3.3V
  • 0 or LOW = 0.00 to 0.7V

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 Raspberry Pi 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 Raspberry Pi model.

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 Raspberry Pi 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, and are located next to the GPIO connector. 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.

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:

  • HIGH Level Detector
  • LOW Level Detector
  • HIGH to LOW Transition Detector
  • LOW to HIGH Transition Detector

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. 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. I2C Serial Protocol.

The next serial protocol that I will discuss is the Inter-Integrated Circuit interface or I2C, which is also a synchronous serial data link.

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.

UART Serial Protocol

The last serial protocol is the standard Universal Asynchronous Receiver Transmitter (UART) that uses two pins in the Raspberry Pi. The UART protocol needs no clock signal, just as it is described by the asynchronous adjective in its name. The Raspberry Pi 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 Raspberry Pi.

Software

The Raspberry Pi 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 Raspberry Pi but simply to show that using the Raspberry Pi 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 Raspberry Pi and will provide more guidance regarding how Python works and how it is applied with the Raspberry Pi, 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 Raspberry Pi setup that uses the connections discussed in the hardware section. Right now, I will be using the setup to get the Raspberry Pi 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 Raspberry Pi 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 Raspberry Pi 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 Raspberry Pi.

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, on the monitor after you connect the USB power to the Raspberry Pi. 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.

Suggested configuration settings are along with some comments regarding why a particular setting was selected.

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

Please note I am not giving away any secrets, as every unmodified Raspberry Pi Linux distribution is created with this default password. You may have changed it in the configuration menu. 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. 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 Raspberry Pi Linux distribution that you desire to install. The current version, at the time of this writing, may be downloaded from the main Raspberry. It be extracted before it can be used as a disk image file. The Raspberry Pi Foundation currently appears to be updating the Wheezy-Raspberry Pi a 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.

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 Raspberry Pi. 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. 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.

Python

I have chosen to use Python to program the Raspberry Pi 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 high level, 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 humor 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.

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

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.

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.

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

I have covered a lot of material in this chapter, from introducing the Raspberry Pi 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 Raspberry Pi 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 Raspberry Pi with the traditional “Hello World” program. Using the Python shell named IDLE just makes the whole effort very easy and, I hope, enjoyable.


Jeion Ahmed

Post a Comment

0 Comments