Home IoT & Hardware Raspberry Pi By Example

Raspberry Pi By Example

By Arush Kakkar
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to Raspberry Pi and Python
About this book
Want to put your Raspberry Pi through its paces right out of the box? This tutorial guide is designed to get you learning all the tricks of the Raspberry Pi through building complete, hands-on hardware projects. Speed through the basics and then dive right in to development! Discover that you can do almost anything with your Raspberry Pi with a taste of almost everything. Get started with Pi Gaming as you learn how to set up Minecraft, and then program your own game with the help of Pygame. Turn the Pi into your own home security system with complete guidance on setting up a webcam spy camera and OpenCV computer vision for image recognition capabilities. Get to grips with GPIO programming to make a Pi-based glowing LED system, build a complete functioning motion tracker, and more. Finally, get ready to tackle projects that push your Pi to its limits. Construct a complete Internet of Things home automation system with the Raspberry Pi to control your house via Twitter; turn your Pi into a super-computer through linking multiple boards into a cluster and then add in advanced network capabilities for super speedy processing!
Publication date:
April 2016
Publisher
Packt
Pages
294
ISBN
9781785285066

 

Chapter 1. Introduction to Raspberry Pi and Python

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:

  • Single-board computers

  • Raspberry Pi

  • Raspbian

  • Setting up Raspberry Pi

  • Basics of Python

  • Turtle programming with Python

 

Single-board computers


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:

 

Raspberry Pi


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.

Note

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.

The following table displays the URLs of the manufacturers' websites, where you can shop for Pi and related items online:

Manufacturer

Website

Newark element14

http://www.newark.com

RS Components

http://uk.rs-online.com

Egoman

http://www.egoman.com.cn

Allied Electronics

http://www.alliedelec.com

You can also shop for Pi and the other third-party add-ons at the following links:

Raspberry Pi models

The following are, at the time of writing this, the major models of Raspberry Pi:

  • 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)

Note

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.

Note

Check out the following URLs for the Compute Module and Compute Module development kit, respectively:

http://www.raspberrypi.org/products/compute-module/

http://www.raspberrypi.org/products/compute-module-development-kit/

The following table compares the currently available models of Pi:

The following image shows the top view of the Raspberry Pi Model B front:

The following image shows the top view of the flip side of Raspberry Pi Model B:

The following image shows the top view of the Raspberry Pi Model B+ front:

The following image shows the top view of the flip side of Raspberry Pi Model B+:

The following image shows the top view of the Raspberry Pi 2 Model B front. The location of the connectors and important ICs (integrated circuits) on the board is not different from Pi B+:

We will be using Raspberry Pi 2 Model B throughout this book. However, all the applications and programs in this book will work on all the models of Pi.

 

Operating systems


The Raspberry Pi primarily uses Unix-like Linux-kernel-based operating systems, such as variants of Debian and Fedora.

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

  • OpenELEC

  • Pidora (Fedora Remix)

  • RASPBMC

  • RISC OS

Note

Windows 10 and Ubuntu are only supported by the recently launched Pi 2.

Raspbian

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.

Note

To know more about Raspbian, visit http://www.raspbian.org/.

 

Setting up the Raspberry Pi


We need the following hardware to set up a Pi.

  • 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:

    Note

    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

  • A monitor

    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.txt file if you're using a VGA monitor, which will be explained in the next section.

    Note

    You can find a similar one online at https://www.adafruit.com/products/1151.

  • A Windows, Linux, or Mac OS computer with a MicroSD card reader and an Internet connection

Preparing MicroSD card manually

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, BOOT and 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.

The following are the instructions for Windows users:

  1. Download the Win32DiskImager installer, which is available at http://sourceforge.net/projects/win32diskimager/files/latest/download and then install it.

  2. Download the installable version of WinZip, which is available at http://www.winzip.com/prod_down.html, and install it.

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

  4. Extract the ZIP file using WinZip. The extracted file will be in the .img format.

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

  6. Run Win32DiskImager.exe and write the image onto the SD card:

    You might receive the following message if the card reader's write protection is on:

  7. Toggle the write protection notch and try again. You will see the following message:

  8. Click on Yes and it will start writing the image file to the microSD card:

  9. Once the image is successfully written, it will display the following message:

Note

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:

  1. Change #disable_overscan=1 to disable_overscan=1.

  2. Change #hdmi_force_hotplug=1 to hdmi_force_hotplug=1.

  3. Change #hdmi_group=1 to hdmi_group=2.

  4. Change #hdmi_mode=1 to hdmi_mode=16.

  5. Change #hdmi_drive=2 to hdmi_drive=2.

  6. Change #config_hdmi_boost=4 to config_hdmi_boost=4.

  7. Save the file.

Booting up our Pi for the first time

Let's boot up our Pi for the first time with the microSD card:

  1. Insert the microSD card into the microSD card slot of the Pi.

  2. Connect the Pi to the HDMI monitor. If you are connecting the VGA monitor, connect it using the HDMI to VGA converter.

  3. Connect the USB mouse and the USB keyboard.

  4. Connect the Pi to a power supply using the micro USB power cable. Make sure the power is switched off at this point.

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

Once the desktop is visible, go to Menu | Accessories | lxterminal. Then, type sudo raspi-config. A text-based menu, such as the following, will appear:

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:

  1. Select Expand Filesystem.

  2. In Boot Options, select B4 Desktop Autologin, as shown in the following screenshot:

    Note

    The default username is pi and 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 raspi-config menu.

    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:

    echo $SHELL
    

    We can always go to the graphical desktop from the Command Prompt by typing the startx command in the console.

  3. Go to Internationalisation Options | Change Timezone.

  4. Go to Internationalisation Options | Change Keyboard Layout | Change it to US (the default is UK).

  5. Select Enable Camera.

  6. Select Advanced Options.

  7. Under this option, select Memory Split and enter 64MB for GPU.

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:

sudo raspi-config

Shutting down and rebooting Pi safely

In the Raspbian menu, there are options to shut down and reboot the Pi.

If we click on the following Menu button on the desktop, it will display multiple options:

The following image shows the last option:

If we click on the preceding option, the following window will appear:

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:

sudo halt

You can reboot Pi with the following command:

sudo reboot

Updating the Pi

Now we have a working Pi running on the Raspbian OS. Let's update our Pi. Make sure you have a working wired or wireless Internet connection with reasonable speed for this activity:

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

  2. Run the following command to restart the networking service:

    sudo service networking restart
    
  3. Make sure that your Raspberry Pi is connected to the Internet by typing the following command:

    ping –c4 www.google.com
    
  4. 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.

  5. Run the following commands in a sequence:

    • 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 upgrade command.

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

 

Getting started with Python


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.

Readability counts."

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:

Now type the following lines and press Enter:

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.

Note

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

Note

This is the link for an interactive tutorial on vim: http://www.openvim.com/.

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 prog1.py:

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

The output of both of the preceding programs is the same and is as follows:

pi@raspberrypi ~/book/chapter01 $ python prog4.py 
0
1
1
2
3
5
8
13
21
34

Turtle programming with Python

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:

import turtle

The following code creates objects for turtle and the screen classes, respectively:

t=turtle.Turtle()
disp=turtle.Screen()

We will use the t.color() function with which we can set the pen and fill color, as follows:

t.color("black","yellow")

We will call the t.begin_fill() and t.end_fill() functions to have our shape filled with a fill color:

t.begin_fill()
t.end_fill()

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.

Note

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:

Note

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.forward(), t.backward(), t.left(), and 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.up() and 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 fractal_tree() with 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:

 

Summary


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

About the Author
  • Arush Kakkar

    Arush Kakkar is a computer vision and deep learning researcher and an undergraduate at Delhi Technological University. His primary focus is on autonomous robotics, which includes drones and self-driving cars, and he has been involved in building such systems in different capacities, such as navigation, localization, path planning. He has also leveraged state-of-the art computer vision and deep learning technologies for them. He is the electrical systems head of the Solar Car team of his university, Solaris DTU. He is currently working on his own driverless car company, CruiseX, which uses deep learning to drive more smoothly and with fewer errors.

    Browse publications by this author
Latest Reviews (14 reviews total)
Good book for starting out with the Raspberry Pi.
Like the 'example' approach.
Excellent book, very original
Raspberry Pi By Example
Unlock this book and the full library FREE for 7 days
Start now