One can learn about topics in computer science in an easy way with the Raspberry Pi and Python. The Raspberry Pi family of single-board computers uses Python as the preferred development language. Using Raspberry Pi and Python to learn programming and computer science-related concepts is one of the best ways to start your journey in this amazing world of computers that is full of creative possibilities. We will explore these possibilities in this book.
We will commence our journey in this chapter by getting ourselves familiar with the following topics:
Setting up Raspberry Pi
Basics of Python
Turtle programming with Python
A single-board computer system is a complete computer on a single circuit board. The board includes a processor(s), RAM, input/output (I/O), and networking ports for interfacing devices. Unlike traditional computer systems, a single-board computer is not modular and its hardware cannot be upgraded as it is integrated on the board itself. Single-board computers are used as low-cost computers in academia, research, and embedded systems. The use of single-board computers in embedded systems is quite prevalent and many individuals and organizations have developed and released fully functional products based on single-board computers.
The Microcomputer Trainer MMD-1 designed by John Titus in 1976 is the first true single-board microcomputer that was based on the Intel C8080A. It was called dyna -micro in the prototyping phase, and the production units were called MMD-1 (short for Mini Micro Designer 1).
Popular single-board computers available in the market include but are not limited to Raspberry Pi, Banana Pro, BeagleBone Black, and Cubieboard. The following images are of the front view of BeagleBone Black, Banana Pro, and Cubieboard 4, respectively:
The Raspberry Pi is a series of low-cost, palm-sized single-board computers developed by Raspberry Pi Foundation in the UK. The intention behind the creation of the Raspberry Pi is to promote the teaching of basic computer skills in schools, which it serves very well. Raspberry Pi has expanded its footprint well beyond its intended purpose by penetrating the embedded systems market and computer science research.
This is the home page of Raspberry Pi Foundation: http://www.raspberrypi.org.
The Raspberry Pi is manufactured with licensed agreements with Newark element14, RS Components, Allied Electronics, and Egoman. These companies manufacture and sell the Raspberry Pi. The hardware is the same across all manufacturers.
Model A (not in production; discontinued in favor of the production of later and upgraded models)
Model A+ (currently in production and available for purchase)
Model B (available for purchase but not in production)
Model B+ (currently in production and available for purchase)
Raspberry Pi 2 Model B (currently in production and available for purchase)
Check out the Product page of Raspberry Pi at http://www.raspberrypi.org/products/.
Additionally, Raspberry Pi is also available in a more flexible form factor intended for industrial and embedded applications. It is known as Compute Module. A Compute Module prototyping kit is also made available by the foundation.
The following table compares the currently available models of Pi:
The following image shows the top view of the flip side of Raspberry Pi Model B+:
Raspberry Pi Models A, A+, B, and B+ are based on the ARM11 family chip, which runs on the ARMv6 instruction set. The ARMv6 instruction set does not support Ubuntu and Windows.
However, the recently launched Raspberry Pi 2 is based on ARM Cortex A7, which is capable of running Windows 10 and Ubuntu (Snappy Core). The following operating systems are officially supported by all the models of Raspberry Pi and are available for download at the download page:
Raspbian: We will be using this with Raspberry Pi throughout the book
Pidora (Fedora Remix)
Raspbian is an unofficial variant of Debian armhf (ARM Hard Float) compiled for hard float code that will run on Raspberry Pi computers. It is a free operating system based on Debian optimized for the Raspberry Pi hardware.
To know more about Raspbian, visit http://www.raspbian.org/.
Raspberry Pi 2 Model B (hereafter, this will be referred only as Pi).
Power Supply: A micro USB power supply.
Considering that we are going for slightly power-intensive usage of our Pi (such as connecting Pi Camera, webcam, and third-party sensors for Pi), a 5V 2A power supply is recommended. The micro USB pin is shown in the following image:
You can find a similar one online at http://www.adafruit.com/product/1995.
A standard USB keyboard
A MicroSD card and a MicroSD to SD card converter
We need a minimum 4 GB Micro SD card.
A USB mouse
You can use either an HDMI monitor or a standard VGA monitor.
A monitor connection cable and converter
If you are using HDMI monitor, then an HDMI cable will be sufficient. If you are using a VGA monitor, then you need to use an HDMI to VGA converter with a VGA cable. Some special changes need to be made to the
/boot/config.txtfile if you're using a VGA monitor, which will be explained in the next section.
You can find a similar one online at https://www.adafruit.com/products/1151.
This is the original way to install an OS into a MicroSD card, and many users, including me, still prefer it. It allows the SD card to be prepared manually before it is used and it allows easier access to configuration files such as
/boot/config.txt, which we might have to modify in a few cases before booting up. The default Raspbian image consists of only two partitions,
SYSTEM, which will fit into a 2 GB card. However, I recommend that you use a minimum 4 GB card to be on safe side. Choosing an 8 GB card will be adequate for most of the applications we are going to develop in this book.
Download the Win32DiskImager installer, which is available at http://sourceforge.net/projects/win32diskimager/files/latest/download and then install it.
Download the installable version of WinZip, which is available at http://www.winzip.com/prod_down.html, and install it.
Go to http://www.raspberrypi.org/downloads and download the latest image of Raspbian. It will be a compressed file in the ZIP format and will need to be extracted.
Extract the ZIP file using WinZip. The extracted file will be in the
Insert the microSD card into the card reader and plug the card reader into the computer. Many computers nowadays have an inbuilt SD card reader. In this case, you will need to insert the microSD card into the microSD to SD card converter and insert it into the computer's inbuilt SD card reader. MicroSD to SD card converters usually come bundled with microSD cards in the same package. If that's not the case, then you will have to procure it separately.
Win32DiskImager.exeand write the image onto the SD card:
You might receive the following message if the card reader's write protection is on:
Click on Yes and it will start writing the image file to the microSD card:
If you are using Linux, then you can find the instructions at https://www.raspberrypi.org/documentation/installation/installing-images/linux.md.
If you are using Mac OS, then you can find the instructions at https://www.raspberrypi.org/documentation/installation/installing-images/mac.md.
If you have an HDMI monitor, then skip this step. This additional step is required only if you are planning to use a VGA monitor in place of an HDMI monitor.
Browse the microSD card on the computer. Locate and open
config.txt. We have to edit the file in order to enable proper display on the VGA monitor.
By default, the commented options (which have
# at the beginning) are disabled. We are enabling this option by uncommenting this line, that is, by removing
# from the beginning of the commented line. This is what you need to do:
Save the file.
Insert the microSD card into the microSD card slot of the Pi.
Connect the Pi to the HDMI monitor. If you are connecting the VGA monitor, connect it using the HDMI to VGA converter.
Connect the USB mouse and the USB keyboard.
Connect the Pi to a power supply using the micro USB power cable. Make sure the power is switched off at this point.
Check all the connections once and then switch on the power supply of the Pi.
At this stage, our Pi will start booting up. You will see a green light on the Pi board blinking. This means that it's working! Now, there are few more things we need to do before we can really start using our Pi. Once it boots up, it will show the desktop as follows:
Perform the following steps. We need to use arrow keys and the Enter key to select options in the text-based menu. Press Enter to select a menu item. Also, we can use the Tab key to directly go to the Select and Finish buttons:
Select Expand Filesystem.
In Boot Options, select B4 Desktop Autologin, as shown in the following screenshot:
The default username is
piand the password is
raspberry. We need it when we don't choose any of the preceding autologin options. We can change this password from the second option in the
We can also choose to boot to the console by selecting any of the first two options in the preceding menu. The default shell of Raspbian is Bash. We can confirm it by typing the following command:
We can always go to the graphical desktop from the Command Prompt by typing the
startxcommand in the console.
Go to Internationalisation Options | Change Timezone.
Go to Internationalisation Options | Change Keyboard Layout | Change it to US (the default is UK).
Select Enable Camera.
Select Advanced Options.
Under this option, select Memory Split and enter
This option decides how much RAM is used by the GPU (Graphics Processor Unit). The more RAM is allocated to the GPU, the more intensive graphics processing can be done. 64 MB is a good value for most graphics purposes.
Once all these options are modified, select Finish. This will prompt for a reboot of the Pi. Choose Yes and let it reboot. Once rebooted, it will automatically take us to the Raspbian Desktop again.
You can always invoke the
raspi-config tool from Command Prompt with the following command and change the settings:
If we click on the following Menu button on the desktop, it will display multiple options:
The following image shows the last option:
Also, from Command Prompt LXTerminal, we can shut down Pi safely by issuing the following command:
sudo shutdown –h now
An alternative command for this is as follows:
You can reboot Pi with the following command:
Connect your Pi to an Internet modem or router with an Ethernet cable or plug in the Wi-Fi dongle to one of the USB ports.
Run the following command to restart the networking service:
sudo service networking restart
Make sure that your Raspberry Pi is connected to the Internet by typing the following command:
ping –c4 www.google.com
apt(Advanced Package Tool) is the utility used to install and remove software in Debian and its variants. We need to use it to update our Pi software.
sudo apt-get update: This command synchronizes the package list from the source. Indexes of all the packages are refreshed. This command must be issued before we issue the
sudo apt-get upgrade: This command will install the newest versions of all the already installed software. Any obsolete packages/utilities are not removed automatically. If any software is in its newest version, then it's left as it is.
sudo rpi-update: This command is used to upgrade the firmware. The kernel and firmware are installed as a Debian package, and so they will also get updates. These packages are updated infrequently after extensive testing.
sudo reboot: This will reboot the computer.
Python is a high-level general-purpose programming language. It supports multiple programming paradigms, such as object-oriented programming, imperative programming, functional programming, procedural programming, aspect-oriented programming, and metaprogramming. It has a dynamic type system, automatic memory management, and a large standard library to carry out various tasks. It emphasizes code readability, and its syntax allows you to carry out tasks in fewer lines of code than other programming languages, such as C or C++.
Python was conceived and implemented by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language, capable of exception handling and interfacing with the Amoeba operating system platform. Van Rossum is Python's principal author, and he continues to have the central role in deciding the direction of Python. He has been endowed with the title benevolent dictator for life (BDFL) by the worldwide Python community.
The core philosophy of the Python programming language is mentioned in this URL: https://www.python.org/dev/peps/pep-0020/; its first few lines are as follows:
"Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Python is the preferred programming language for the Raspberry Pi family of computers. Its interpreter comes preinstalled with Raspbian, and there is no need for any additional installation to get started with code. It is recommended that you have chapter wise directories for the code examples presented in this book, as shown in the following diagram:
Let's get started with Python. Open Raspbian's Command Prompt LXTerminal. It is located as a shortcut on the taskbar. Alternately, we can find it by navigating to Menu | Accessories | Terminal. We can start Python in interactive mode by typing
python in the prompt and then pressing the Enter key. It will take us to the Python interactive shell, as follows:
print "Hello World!"
The output will be as follows:
Python 2.7.3 (default, Mar 18 2014, 05:13:23) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World!" Hello World!
Congrats! We have started with Python programming. The interactive mode of Python is suitable for small programs. Press Ctrl + D to exit the interactive shell. For large and code-intensive projects, it's recommended that you use Python in script mode. In this book, we will be using Python in script mode unless specified explicitly. Let's look at how to use Python in script mode.
Create a subdirectory,
book, in the
/home/pi directory for the code examples in this book. We can do this with
mkdir book (by default, we are be in the
/home/pi directory). Then, navigate to this recently created directory with the
cd book command. We can verify our current directory with the
pwd command. It returns the current directory as follows:
pi@raspberrypi ~ $ mkdir book pi@raspberrypi ~ $ cd book pi@raspberrypi ~/book $ pwd /home/pi/book pi@raspberrypi ~/book $
As discussed earlier, we need to keep the code of each chapter in separate directories for better organization. Now, create the
chapter01 directory for this chapter in the current
book directory using
mkdir chapter01. Navigate to this with
cd chapter01. At the beginning of each chapter, we are required to create a directory for the chapter under
/home/pi/book for the code examples of that chapter.
We will now create a script file for our code and run it.
Use the Nano text editor to create and edit script files. If we type
nano prog1.py, then Nano will open
prog1.py for editing if it already exists in the current directory; otherwise, it will create a new file with the name
prog1.py. You can exit the Nano editor by pressing Ctrl + X.
You can find more information about nano at http://www.nano-editor.org/.
Alternatively, you can use the Leafpad text editor. We can find it by navigating to Menu | Accessories. Or, we can invoke it from Command Prompt with the
leafpad prog1.py command.
Finally, you can also use
vim, but you will need to install it by running the following command:
sudo apt-get install vim
This is the link for an interactive tutorial on
Let's write the same Python code and run it as a script. Write the following code with Nano, Leafpad, or vim, and save it as
print "Hello World!"
To run the preceding program, use the
python prog1.py command, and the output will be as follows.
We will run all the other Python programs in this book in the same way.
Let's try some more examples to have more hands-on Python.
The following is the iterative program to calculate the factorial of a given positive integer:
def fact(n): num = 1 while n >= 1: num = num * n n = n - 1 return num print (fact(10))
In the preceding program,
def fact(n) is a user-defined function that accepts an argument. The logic used to calculate the factorial of a positive integer follows the definition and the function returns a calculated factorial. The last line of the program calls the factorial function and prints the returned output as follows:
pi@raspberrypi ~/book/chapter01 $ python prog2.py 3628800
The following is an iterative program for the Fibonacci series:
def fib(n): a=0 b=1 for i in range(n): temp=a a=b b=temp+b return a for i in range (0,10): print (fib(i))
The preceding program prints the first 10 numbers in the Fibonacci series. A more "Pythonic" way of writing the same program, which eliminates the use of a temporary variable, is as follows:
def fib(n): a,b = 0,1 for i in range(n): a,b = b,a+b return a for i in range(0,10): print (fib(i))
pi@raspberrypi ~/book/chapter01 $ python prog4.py 0 1 1 2 3 5 8 13 21 34
Turtle graphics is one of the best ways to learn programming for beginners. Originally, it was part of the Logo programming language, which was primarily used to introduce programming in schools. Python has the
turtle module, which is an implementation of the same functionality provided by the original turtle. We can write programs with this module in a procedural as well as object-oriented way.
In Python, when we need to access a module that is not part of the current code, we need to import it. Over the course of the book, we will be importing various modules as and when needed, which will provide us with specific functionalities.
Let's get started with importing the
turtle module, as shown here:
The following code creates objects for turtle and the screen classes, respectively:
We will use the
t.color() function with which we can set the pen and fill color, as follows:
We will call the
t.end_fill() functions to have our shape filled with a fill color:
The code to draw an actual shape we need will be in between these two function calls, as follows:
t.begin_fill() while 1: t.forward(100) t.left(190) if abs(t.pos())<1: break t.end_fill() disp.exitonclick()
In the preceding code,
t.forward() is used to move the turtle forward a specified distance, and
t.left() is used to rotate the turtle left by 190 degrees.
t.pos() returns the current coordinates of the turtle.
Finally, we use
disp.exitonclick() to close the current output window when we click on the exit button.
At the start, the turtle cursor is at (0,0) and is pointed toward the positive direction of the x axis (facing right).
The output of the program will be a cursor drawing the desired shape progressively, and it helps the programmer understand how the program is actually working. The final output of the preceding program is as follows:
Detailed documentation for the turtle API can be found at https://docs.python.org/2/library/turtle.html.
Next, we will learn the concept of recursion. In terms of programming, recursion means calling the same block of code within itself. For a procedural and modular style of programming, this stands for calling a function or method within itself. Usually, this is done to break a big problem into similar problems with smaller input sizes and then collect the output of all these smaller problems to derive the output of the big problem. One of the best ways to see recursion at work is to visualize it using a turtle. We will now write a program to draw a fractal tree using recursion.
First, we start by importing the required libraries, as follows:
import turtle import random
We need the
random library for the
randint() function, which returns a random integer in the provided range. This is needed to make our generated tree seem different every time. Then, we will define a function to draw a part of the tree recursively:
def fractal_tree(b_len,t): if b_len > 5: temp=random.randint(1, b_len) temp_angle = random.randint(1, 25) t.forward(temp) t.right(temp_angle) fractal_tree(b_len-10,t) t.left(2 * temp_angle) fractal_tree(b_len-10,t) t.right(temp_angle) t.backward(temp)
In the preceding program, we are calling the same function twice in order to draw the further branches of the tree. If the
b_len parameter is less than or equal to 5, then it will be a leaf (which means that the function will not be called again); else, the recursion will continue. We are randomizing the angle and length of the movement of the turtle while drawing the branches here; otherwise, the tree will be symmetrical, which is very unlikely in real life. The combination of
t.right() ensures that at the end of each function call, the turtle cursor is at the same position as where it started.
Finally, we write the routine to call this recursive function:
t=turtle.Turtle() disp=turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") fractal_tree(120,t) disp.exitonclick()
The cursor does not draw the movements between the
t.down() function calls. In the preceding code, we are moving the cursor downward by 100 positions so that the tree should fit in the turtle graphics window. When we call
120 as the argument, it takes more than 30 minutes due to the high degree of recursion. The output of the preceding program is as follows:
In this chapter, we learned about the background of Raspberry Pi and Python. We understood the details of the different models of Pi. We learned how to set up the Raspberry Pi for programming. We also performed some hands-on Python programs. Then, we learned some graphics programming with the turtle library. This got us started with the Pi and the Python programming language, which we will be using throughout the rest of the book.
In the next chapter, we will learn how to play and program