Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)
Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications): Learn to design and implement reliable Python applications on the Raspberry Pi using a range of external libraries, the Raspberry Pis GPIO port, and the camera module

By Dan Nixon
$43.99
Book Sep 2015 200 pages 1st Edition
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 29, 2015
Length 200 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783551590
Category :
Table of content icon View table of contents Preview book icon Preview Book

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

Chapter 1. Your First Steps with Python on the Pi

In this chapter, we will look at setting up the Raspbian operating system on the Raspberry Pi and have a quick look at the Python development tools that come pre-installed on it, along with looking at some basic ways in which we can execute the Python code.

The only things that are required here are:

  • A Raspberry Pi

  • A USB power source capable of delivering at least 1A

  • USB keyboard

  • USB mouse

  • TV with HDMI port

  • An SD card (or microSD card for the model B+ and Pi 2) of at least 4GB capacity

  • An SD card reader

  • A USB hub (if you wish to connect more USB devices that there are ports on the Raspberry Pi)

  • Optionally, a WiFi adapter if you want to connect the Pi to your network wirelessly (the list of supported USB WiFi adapters is available at elinux.org/RPi_USB_Wi-Fi_Adapters)

Installing and setting up Raspbian


The first thing we need to do is head to the Raspberry Pi downloads page at https://www.raspberrypi.org/downloads/ and download the latest version of Raspbian. This is a version of the Debian Linux distribution, specifically designed for the Raspberry Pi.

  1. On the downloads page select the Download ZIP option under RASPBIAN.

  2. Once the file has downloaded, extract the Zip archive using the default tool on your OS. You should now have a single file ending with the file extension .img.

Writing to the SD card

The next step is to write the just downloaded operating system image to the SD card so that it can be used with the Pi. The way this is done varies depending on the operating system you use on your main PC.

Windows

On Windows, we will use a tool called Win32 Disk Imager to write the OS image to the SD card. This tool can be downloaded from the SourceForge page at sourceforge.net/projects/win32diskimager.

  1. Once downloaded and installed, insert your SD card and open Win32 Disk Imager. You should see a window similar to the following screenshot:

    The important thing to check is that a drive letter appears in the Device drop down list. If this does not happen then Win32 Disk Imager has failed to recognize your SD card. In such a case, try it in a different SD card reader. If it still does not work then it could indicate that the card has failed.

  2. Next, browse to select the .img file you had previously extracted from the downloaded Zip archive and click the Write button as shown in the following screenshot, after first making sure that the correct device is selected in the Device drop down list:

  3. You will then see a confirmation dialog similar to the one shown in the next screenshot, asking you to confirm that the image and device are correct. Assuming they are, click on Yes.

  4. Win32 Disk Imager will now write the image file to the SD card. This can take a few minutes. Once complete, you will see a confirmation dialog box as seen in the following screenshot:

You now have Raspbian loaded on the SD card and can now move on to the Boot Pi for the first time. This will be covered in the following sections.

Linux and Mac

On Linux and Mac, the dd command line utility can be used to write the operating system image to the SD card.

  1. First, we need to determine the path to the storage device you want to write to. On Linux, the easiest way to do this is by using the udev management tool to monitor the udev logs. This is done by using the following command:

    udevadm monitor --udev
    
  2. Now insert the SD card and you should see a series of log messages printed to the console, similar to those shown in the following image. The last few should contain the paths to the partitions already on the drive (in my case, /dev/sdb1 and /dev/sdb2; from this we can deduce that the path to the SD card is /dev/sdb).

  3. Next, we need to ensure that none of the existing partitions are mounted before we try to write to the SD card. This can be done by running the following command for every partition discovered using udevadm:

    umount PATH
    

    Here PATH is the path to the partition. This should give an output similar to the following image if the partition was not mounted; otherwise the command will exit without printing any output:

  4. At this point, the SD card is ready to be written to. For this we will use the following command:

    sudo dd if=[path to .img] of=[path to SD]
    

    Here [path to .img] is the path to the .img file extracted from the Zip archive downloaded earlier and [path to SD] is the path to the SD card we just discovered.

    This process will take some time (up to 20 minutes) and is complete when the command exits and you see the next shell prompt as shown in the following screenshot. If the writing fails then an error message will be printed to the terminal.

Booting the Pi for the first time

Now that you have an SD card with Raspbian installed on it, you are ready to boot the Pi for the first time and perform the first time configuration steps required to get the Pi up and running.

Note that to fully setup the Pi, you will need to have a way to connect it to the internet in order to install and update the software packages. This can either be wired (using an Ethernet cable) or wireless (using a USB WiFi adapter).

  1. Firstly, connect the mouse, keyboard, monitor, and either the WiFi adapter or the Ethernet cable to the Pi. Insert the SD card and connect a USB power source. You should see the red PWR LED (Light Emitting Diode) light up and shortly after that, the green ACT LED would start to blink.

    Note that the USB power source should be able to supply at least 1.5A to ensure reliable operation of the Pi. Usually, the USB chargers supplied with the tablets are a good choice of power supply.

  2. Once the Pi has booted, you will see the configuration utility as shown in the following screenshot. The first thing we need to do here is to expand the root partition on the SD card to fill the entire SD card. This ensures that we have the maximum space available once we start using the Pi. This is done by selecting the Expand Filesystem option at the top of the list and pressing Enter.

  3. Once the filesystem has been modified, you will see a message similar to the one shown next. Press Enter to return to the main menu.

  4. Next, we will change the password for the default Pi user. This is done by selecting the second option on the main menu, Change User Password, and pressing Enter.

  5. You will now see a message box similar to the one shown next, with instructions on entering a new password. Press Enter to continue.

  6. You will now be required to enter a new password. Press Enter when finished. Once you have done this, you will be asked to enter the password again to confirm.

    Note

    Note that when entering a password you will not see any characters appear on the screen.

  7. Now that the password has been changed, we need to set the default boot action to start LXDE, the desktop manager used on Raspbian. Select Enable Boot to Desktop/Scratch and press Enter.

  8. Now select the second Desktop option and press Enter.

  9. You may also wish to change the default locale using the Internationalisation Options menu option. By default, the Pi is configured for the UK.

  10. Once you are ready to reboot the Pi to apply all of the new settings. This is done by selecting the Finish option and pressing Enter.

  11. You will be asked for a confirmation that you want to reboot. Select Yes and press Enter.

  12. If you are using Ethernet to connect to your network then you can skip this step. Otherwise, we will now setup the WiFi adapter and connect to a wireless network.

    1. Open wpa_gui by choosing the WiFi Configuration utility in the Preferences submenu from the main menu in Raspbian.

    2. Click on Scan to search for wireless networks in range. When complete, you should see a list similar to the one in the following screenshot:

    3. When the scan completes, double click on the WiFi network you wish to connect to and you will be shown a window similar to the one in the following image, with some of the details of the network filled in:

    4. Here all that is usually needed to be done is to enter the WiFi password in the PSK field and click on Add.

    5. When done, the network should be selected in the Network drop down box automatically. Now click on Connect to connect to the network. Assuming all went well, you should see the Status of the connection show Connected, as shown in this next screenshot:

  13. Now that we have an internet connection on the Pi, the final setup is to update the software packages already installed on the Pi. This can be done by opening a terminal, by clicking on the black monitor in the top left corner of the screen and typing the following commands:

    sudo apt-get update
    sudo apt-get upgrade
    

    Each of these commands will take a few minutes to execute. The first updates the list of the available packages and the second updates each of the installed packages to the latest version.

Now that we have Raspbian setup on the Pi, we can move on to having a look at some of the tools we can use to write and execute Python scripts on the Pi.

The Python development tools


Now that the Pi is set up and running Raspbian, we can have a look at some of the tools we will use to develop Python scripts (small text files containing commands) and applications. Most of the time we will be using either the interactive Python terminal to execute the code line by line or the python executable to run full scripts and applications.

We will first look at the interactive terminal. First open a terminal by clicking on the black monitor icon in the top right corner of the desktop. This will open an LXTerminal window. In this window, type python and press Enter. This will start the interactive terminal as shown in the following screenshot:

From here we can type the Python code line by line; each line is executed as soon as it is typed, making this tool useful for quick testing and debugging (I also find that it makes a nice command line calculator). To demonstrate this, type in the following code and press Enter:

print "Hello, world!"

This will print the test Hello, world! on the line next to where you typed it in, as shown in the following screenshot:

The python executable can also be used to run the existing Python script files (which have the .py file extension), which we will look at later in the chapter.

One alternative to the interactive terminal is the IDLE Integrated Development Environment (IDE) which can be used both as an interactive terminal and a source file editor, and provides syntax highlighting for the Python files. It can be found by selecting Python 2 from the Programming submenu of the main menu on Raspbian, as shown in the following screenshot:

When first opened, it will be in the interactive terminal mode and can be used in the same way as the terminal ran from the command line, as shown in the following screenshot:

Python 2 versus Python 3

You will notice that there are two versions of Python installed by default on Raspbian: Python 2.7 and Python 3.1. Whilst the fundamentals of Python programming have not greatly changed between the two versions, there are notable differences that may prevent a code that was written for one version from working when executed with the interpreter for a different version.

For this reason, we will only use Python 2.7 in this book as this has the widest library support and is still the default Python version on many operating systems.

Note

More information of the differences between Python versions is available on the Python Wiki at wiki.python.org/moin/Python2orPython3

Running some simple Python scripts


Now we will look at writing a Python script in a file and executing it. For this we will use IDLE as it will provide syntax highlighting on the code. However, any text editor (for example, LeafPad, GEdit, nano, vim) can be used to write the Python files.

  1. First open IDLE and select New Window from the File menu, as shown in the following screenshot. This will open a new text editor window which will allow you to write and edit the script files.

  2. Now type the following code into the editor. This is a simple script that imports the time module and prints a string containing the current time to the terminal.

    import time
    print "The current time is: " + time.ctime()

    Note

    Keep in mind that the indentation level in Python is very important as this defines the scope that a line of code fits into. This will become clearer later on in the book when we start writing more complex codes.

  3. Save the file as time.py in the home directory by selecting Save from the File menu.

    Now that the script is saved, we can execute it using the Python executable at the command line.

  4. Open a terminal and enter the following command to execute the Python script:

    python time.py
    

    This will give the following output to the terminal:

    One small improvement that could be made to this process is to include a shebang in the Python script that will tell the shell what to use to execute the script. This way we do not have to explicitly include the Python command when we run the script.

  5. Go back to the Python script in IDLE and add the following line as the very first line in the file:

    #!/usr/bin/env python
  6. Next, we need to give execute permissions to the file in order to execute it directly (that is, without calling the Python executable first). This is done using the following command in the terminal:

    chmod a+x time.py
    
  7. Now we are able to execute the script using the following command:

    ./time.py
    

    This gives the following output on the terminal:

Summary


In this chapter, we looked at getting the Pi set up and running using the Raspbian operating system, and went through the Python development tools and the differences between the Python versions.

We also looked at our first snippets of Python code and the different ways that Python can be executed.

In the next chapter, we will focus more on the fundamentals of Python programming when we look at control flow operations, multiple data types, and the operations they support.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Fundamentals of Python applications Designing applications for multithreading Interacting with electronics and physical devices Debugging applications when they go wrong Packaging and installing Python modules User interface design using Qt Building easy to use commandline interfaces Connecting applications to the Internet

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 29, 2015
Length 200 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783551590
Category :

Table of Contents

18 Chapters
Getting Started with Python and Raspberry Pi Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Your First Steps with Python on the Pi Chevron down icon Chevron up icon
Understanding Control Flow and Data Types Chevron down icon Chevron up icon
Working with Data Structures and I/O Chevron down icon Chevron up icon
Understanding Object-oriented Programming and Threading Chevron down icon Chevron up icon
Packaging Code with setuptools Chevron down icon Chevron up icon
Accessing the GPIO Pins Chevron down icon Chevron up icon
Using the Camera Module Chevron down icon Chevron up icon
Extracting Data from the Internet Chevron down icon Chevron up icon
Creating Command-line Interfaces Chevron down icon Chevron up icon
Debugging Applications with PDB and Log Files Chevron down icon Chevron up icon
Designing Your GUI with Qt Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela