Ibrahim D. Learning Python With Raspberry Pi for..Engineers 2019
Ibrahim D. Learning Python With Raspberry Pi for..Engineers 2019
# ---------------------------
#
Raspberry Pi
# Date : July, 2019
# Author : Dogan Ibrahim
#=======================================================
print("RESISTIVE POTENTIAL DIVIDER")
print("===========================")
R1flag = 1
R2flag = 0
while R1flag == 1:
Vin = float(raw_input("\nInput voltage (Volts): "))
Vo = float(raw_input("Desired output voltage (Volts): "))
R2 = float(raw_input("Enter R2 (in Ohms): "))
#
# Calculate R1
#
R1 = R2 * (Vin - Vo) / Vo
print("\nR1 = %3.2f Ohms R2 = %3.2f Ohms" %(R1, R2))
#
# Read chosen physical R1 and display actual Vo
#
NewR1 = float(raw_input("\nEnter chosen R1 (Ohms): "))
#
# Display and print the output voltage with chosen R1
#
print("\nWith the chosen R1,the results are:")
Vo = R2 * Vin / (NewR1 + R2)
print("R1 = %3.2F R2 = %3.2f Vin = %3.2f Vo = %3.3f" %(NewR1,R2,Vin,Vo))
#
# Check if happy with the values ?
#
happy = raw_input("\nAre you happy with the values? ")
happy = happy.lower()
if happy == 'y':
break
else:
mode = raw_input("Do you want to try again? ")
mode = mode.lower()
if mode == 'y':
R1flag = 1
Dogan Ibrahim
else:
R1flag = 0 LEARN DESIGN SHARE
break
GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DE
HARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ●
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE
GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DE
HARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN
Learning Python with
Raspberry Pi
for electronic engineers
Dogan Ibrahim
● All rights reserved. No part of this book may be reproduced in any material form, including
photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally
to some other sue of this publication, without the written permission of the copyright holder except in
accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a
licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P
9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be
addressed to the publishers.
● Declaration
The author and publisher have used their best efforts in ensuring the correctness of the information
contained in this book. They do not assume, or hereby disclaim, any liability to any party for any loss or
damage caused by errors or omissions in this book, whether such errors or omissions result from negligence,
accident or any other cause..
● Acknowledgements
The author would like to express his thanks to Ferdinand te Walvaart of Elektor for the valuable suggestions
he made throughout the duration of the preparation of this book. The author would like to thank also to his
wife Nadire for her encouragement, motivation, and for being patient with me while working on this book.
● ISBN 978-1-907920-80-6
Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro
engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops
and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social
media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 1 • Raspberry Pi 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
●5
Learning Python with Raspberry Pi
5.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6.4 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6.8 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
6.10 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.11 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
●6
6.22 Case Study 2 – 4 Band Resistor Colour Code Identifier Including Small Resistors . 72
●7
Learning Python with Raspberry Pi
8.6 Case Study 13 – Save Raspberry Pi 4 CPU Temperature on Memory Stick . . . . . . 152
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python . . . . . . 169
●8
Chapter 13 • Accessing
Raspberry Pi 4 Hardware and Peripheral
Devices From Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
●9
Learning Python with Raspberry Pi
14.3.1 Case Study 29 – Sending a Text Message to a Mobile Phone Using TCP/IP . . . 243
14.4.1 Case Study 32 – Sending a Text Message to a Mobile Phone Using UDP . . . . . 252
14.5 U
sing Flask to Create a Web Server to Control Raspberry Pi GPIO Ports
From the Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Chapter 15 • B
luetooth Communication on Raspberry Pi 4
Using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
15.2 Case Study 35 – Bluetooth Control of LED From a Mobile Phone . . . . . . . . . . . . 262
A.3 Case Study 36 – Display the Raspberry Pi 4 CPU Temperature Using wxPython . . 276
● 10
Preface
Preface
Python is an interpreted high-level language created in The 1990s by Guido van Rossum.
The language is procedural and object-oriented. Python is a general purpose language
which can be used for web development, general software development, mathematics and
system scripting. The latest version of Python is Python 3. However, Python 2.7 still seems
to be very popular and is used extensively. Python has some similarities to the English lan-
guage and relies on indentation to define the scope of loops, functions and classes. Other
programming languages (e.g. C) use curly-brackets for this purpose.
Python is currently the most popular teaching language. It is used as the first programming
language in most colleges and universities around the world. Most software development
companies (e.g. Google, Dropbox, Spotify, Netflix, PayPal, Reddit, etc) prefer Python lan-
guage because of its versatile features and fewer programming codes to accomplish a task.
Some of the advantages of Python can be summarized as:
• Interpreted
• Interactive
• Dynamic
• Modular
• Object-oriented
• Portable (available on Raspberry Pi as well as on the PC)
• Easy to learn
• Machine learning and artificial intelligence support
• Extensive support libraries
• Support of multitasking
• Well supported and maintained
• Free of charge
Perhaps the strongest point of Python is that it supports extensive support libraries that
include string operations, web tools, Wi-Fi and Bluetooth support, and operating system
interfaces.
Python is available on many operating systems, including Linux, Windows, MAC, and many
others. Python has recently become more popular since it is the most commonly used
programming language on the Raspberry Pi family of single-board computers. For exam-
ple, students can purchase a $50 rather powerful Raspberry Pi computer with the Python
programming language already installed. They can learn Python by experimenting on the
Raspberry Pi.
This book is about teaching the Python programming language using the Raspberry Pi 4
computer. The book is aimed for beginners, students, practicing engineers, hobbyists, and
for anyone else who may want to learn to program in Python. The book includes many ex-
ample programs and case studies. All the example programs and case studies have been
tested fully by the author and are all working. Most of the programs in the book have been
developed using Python 2.7, but they will work on Python 3 with minor changes. The graph-
● 11
Learning Python with Raspberry Pi
ics programs (tkinter) have been developed using Python 3. The example programs are
general in the sense that they aim to teach the various programming concepts of Python.
The case studies cover the use of Python in the analysis and design of electronic circuits.
Electronic engineers and readers interested in electronic circuit analysis and design will
find the case studies very useful. The following sub-headings are used while describing the
example programs and case studies:
• Title
• Description
• Aim
• Background Information
• Program Listing
Full program listings of all the programs used in the book are available at the Elektor web
site of the book. Readers should be able just to copy and use these programs in their Rasp-
berry Pi projects without any modifications. The operation of all the programs given in the
book are fully described in the book and therefore readers should find it easy to develop
these programs further, or to modify them for their own needs.
I hope you enjoy reading the book and use Python in your next Raspberry Pi project.
Dogan Ibrahim
September, 2019
London
● 12
Chapter 1 • Raspberry Pi 4
Chapter 1 • Raspberry Pi 4
1.1 Overview
Raspberry Pi has recently become one of the most popular and most powerful single-board
computers used by students, hobbyists, and professional engineers. Raspberry Pi 4 is the
latest and the most powerful version of the Raspberry Pi. In this chapter, we shall be look-
ing at the basic specifications and requirements of the Raspberry Pi 4 computer. What is
included in this chapter, can easily be applied to other models in the Raspberry Pi family.
Figure 1 shows the Raspberry Pi 4 board with its major components identified.
● 13
Learning Python with Raspberry Pi
RAM: There are 3 versions of Raspberry Pi 4 depending on the amount of DDR4 RAM re-
quired: 1GB, 2GB, and 4GB.
USB Ports: Raspberry Pi 4 includes 2 x USB 3.0, 2 x USB 2.0, and 1 x USB-C ports. USB
3.0 data transfer rate is 4,800 Mbps (megabits per second), while USB 2.0 can transfer at
up to 480Mbps, i.e. 10 times slower than the USB 2.0. The USB-C port enables the board
to be connected to a suitable power source.
Ethernet: The Ethernet port enables the board to be connected directly to an Ethernet port
on a router. The port supports Gigabit connections (125Mbps).
HDMI: Two micro HDMI ports are provided that support up to 4K screen resolutions. HDMI
adapters can be used to interface the board to standard size HDMI devices.
GPIO: A 40-pin header is provided as the GPIO (General Purpose Input Output). This is
compatible with the earlier GPIO ports.
Audio and Video Port: A 3.5mm jack type socket is provided for stereo audio and com-
posite video interface. Headphones can be connected to this port. External amplifier de-
vices will be required to connect speakers to this port. This port also supports composite
video, enabling TVs, projectors, and other composite video compatible display devices to
be connected to the port.
CSI Port: This is the camera port (Camera Serial Interface), allowing a compatible camera
to be connected to the Raspberry Pi.
DSI Port: This is the display port (Display Serial Interface), allowing a compatible display
(e.g. 7 inch Raspberry Pi display) to be connected to the Raspberry Pi.
PoE Port: This is a 4-pin header, allowing the Raspberry Pi to receive power from a net-
work connection.
Micro SD Card: This card is mounted on the cardholder placed at the bottom of the board
and it holds the operating system software as well as the operating system and user data.
● 14
Chapter 1 • Raspberry Pi 4
• Power supply
• Micro SD card
• Operating system software
• USB keyboard and mouse
• Micro HDMI cable to receive sound and video signals
• HDMI compatible display or TV (you may also need to have micro HDMI to DVI-D
or VGA adapters. A 3.5mm TRRS type cable and plug will be required if you will
be using an old TV with composite video)
Power Supply: A 5V 3A power supply with USB-C type connector is required. You may ei-
ther purchase the official Raspberry Pi 4 power supply (Figure 1.2), or use a USB-C adapter
to provide power from an external source.
Micro SD Card: It is recommended to use a micro SD card with a capacity of at least 8GB,
although higher capacity (e.g. 16GB or 32GB) is better as there will be room to grow in the
future. A Class 10 (or faster) card is recommended.
Operating System: You can purchase the operating system pre-loaded on a micro SD
card, known as NOOBS (New Out Of Box Software) which require minimum configuration
before it is fully functional. The alternative is to purchase a blank micro SD card and upload
the operating system on this card. The steps to prepare a new micro SD card with the op-
erating system is given in the next chapter.
USB Keyboard and Mouse: You can either use a wireless or wired keyboard and mouse
pair. If using a wired pair, you should connect the keyboard to one of the USB ports and the
mouse to another USB port. If using a wireless keyboard and mouse, you should connect
the wireless dongle to one of the USB ports.
Display: A standard HDMI compatible display monitor with a micro HDMI to standard HDMI
adapter can be used. Alternatively, a VGA type display monitor with a micro HDMI to VGA
adapter or DVI-D adapter can be used. If you have an old TV with composite video inter-
● 15
Learning Python with Raspberry Pi
face, then you can connect it to the Raspberry Pi 3.5mm port with a TRRS type connector.
You may also consider purchasing additional parts, such as a case, CPU fan, and so on. A
case is very useful as it protects your Raspberry Pi electronics. The working temperature of
the CPU can go as high as 80 degrees Centigrade. Using a fan (see Figure 1.3) makes the
CPU more efficient as it can lower its temperature by about 50%.
● 16
Chapter 1 • Raspberry Pi 4
● 17
Learning Python with Raspberry Pi
1.4 Summary
In this chapter we have learned the main parts and their functions on the Raspberry Pi 4
board. In addition, we have learned how to setup the Raspberry Pi 4.
In the next chapter we shall be installing the operating system on a new blank micro SD
card.
● 18
Chapter 2 • Setting Up the Raspberry Pi 4
2.1 Overview
In this chapter we shall be learning how to install the Raspberry Pi 4 operating system
Raspbian on a new blank micro SD card. If you have purchased a pre-installed micro SD
card with NOOBS, you do not need to do anything else other than plug it into your Rasp-
berry Pi.
• Activate the following link to select the operating system as shown in Figure 2.1,
and click NOOBS.
https://www.raspberrypi.org/downloads/
• As shown in Figure 2.2, there are two versions of the software: NOOBS and
NOOBS Lite. You should select to download NOOBS as it contains the Raspbian
operating system and other products. Click Download ZIP under NOOBS and
save the file in a folder (e.g. C:\RPI).
● 19
Learning Python with Raspberry Pi
• We should now format our micro SD card using SD Card Association Card For-
matter tool. Install this tool from the following site (see Figure2.3):
https://www.sdcard.org/downloads/formatter/
• Insert your micro SD card into the card reader of your PC and run the card for-
matter application. Give a volume name (e.g. RPI or NOOBS) and select Quick
Format and click Format (see Figure 2.4) after making sure that you have se-
lected the card. The formatting process should take only a few seconds.
● 20
Chapter 2 • Setting Up the Raspberry Pi 4
• We can now install the operating system on the card. Double click the operating
system file in folder C:\RPI and unzip it into the same directory.
• Select all the files (except unzipped file NOOBS_v3_1_1) in folder C:\RPI and
drag them to your micro SD card (Figure2.5).
• When the files are all copied, remove the SD card from your PC and insert into
your Raspberry Pi.
● 21
Learning Python with Raspberry Pi
confirm to install the Raspbian operating system. You should see the message Raspbian
Full: Creating filesystem at the bottom of the display (Figure 2.7). Wait for 5 to 10 min-
utes until the operating system has been installed and ready on the SD card (See Figure
2.8). You should see a progress bar at the bottom of the display as the installation process
continues.
● 22
Chapter 2 • Setting Up the Raspberry Pi 4
At this point, you are given the option of selecting a Wi-Fi network. In Figure 2.9, BTHome-
Spot-XNH is selected as the Wi-Fi network and the password id entered.
Move the mouse pointer over the blue Wi-Fi icon at the top right-hand side of the display
and you should see the IP address assigned to the Raspberry Pi. As shown in Figure 2.10,
the address 192.168.1.202 was assigned to the Raspberry Pi.
The IP address of the Raspberry Pi could also be displayed by entering command ifconfig
to a terminal session as shown in Figure 2.11.
● 23
Learning Python with Raspberry Pi
Go to the configuration menu and select Interface Options. Go down to P2 SSH (see
Figure 2.12) and enable SSH. Click <Finish> to exit the menu.
You should also enable VNC so that the Raspberry Pi can be accessed graphically over the
Internet. This can be done by entering the following command at a terminal session:
Go to the configuration menu and select Interface Options. Go down to P3 VNC and
enable VNC. Click <Finish> to exit the menu.
● 24
Chapter 2 • Setting Up the Raspberry Pi 4
At this stage, you may want to shutdown your Raspberry Pi by clicking the Applications
Menu on Desktop and selecting the Shutdown option as shown in Figure 2.13.
The program we will be using on our PC to access the Raspberry Pi is called Putty, where
it can be downloaded from the following link:
https://www.putty.org/
Putty is a standalone program and there is no need to install it. Simply double click to run
it and the Putty startup screen will be displayed. Click SSH and enter the Raspberry Pi IP
address, then click Open (see Figure 2.14). The message shown in Figure 2.15 will be
displayed the first time you access the Raspberry Pi. Click Yes to accept this security alert.
● 25
Learning Python with Raspberry Pi
You will be prompted to enter the username and password. After a successful login, you
should see the command prompt as in Figure 2.16.
● 26
Chapter 2 • Setting Up the Raspberry Pi 4
• Restart Putty
• Select SSH and enter the Raspberry Pi IP address
• Click Colours under Window
• Set the Default Foreground and Default Bold Foreground colours to black
(Red:0, Green:0, Blue:0)
• Set the Default Background and Default Bold Background to white (Red:255,
Green:255, Blue:255)
• Set the Cursor Text and Cursor Colour to black (Red:0, Green:0, Blue:0)
• Select Appearance under Window and click Change in Font settings. Set the
font to Bold 12.
• Select Session and give a name to the session (e.g. RPI4) and click Save.
• Click Open to open the Putty session with the saved configuration (see Figure
2.17)
• Next time you re-start the Putty, select the saved session and click Load followed
by Open to start a session with the saved configuration
• Connect to your Raspberry Pi using the Putty as explained earlier. Then, enter
the following command to install a program called TightVNC server on your Pi
computer. You will see many lines of messages and make sure that there are no
error messages:
● 27
Learning Python with Raspberry Pi
• Run the VNC server on your Raspberry Pi computer by entering the following
command:
pi@raspberrypi:~ $ vncserver :1
• You will be prompted to enter and verify a password. This will be the password
you will be using to access the Desktop remotely (see Figure 2.18).
• The VNC server is now running on your Raspberry Pi. The only command you
need to enter on your Pi computer to start the VNC server is:
pi@raspberrypi:~ $ vncserver :1
• We must now setup a VNC client on our laptop (or desktop). There are many VNC
clients available, but the recommended one which is compatible with TightVNC
is the TightVNC for the PC which can be downloaded from the following link:
https://www.tightvnc.com/download.php
• Download and install the TightVNC software for your PC. You will have to choose
a password during the installation.
• Start the TightVNC Viewer on your PC and enter the Raspberry Pi IP address
(see Figure 2.19) followed by :1. Click Connect to connect to your Raspberry Pi.
● 28
Chapter 2 • Setting Up the Raspberry Pi 4
Enter the password you have chosen earlier. You should now see the Raspberry Pi Desktop
displayed on your PC screen as shown in Figure 2.20.
2.6 Summary
In this chapter we have seen how to install the Raspbian operating system on our Raspber-
ry Pi 4. We have also learned how to access our Raspberry Pi remotely. In the next chapter
we shall be looking at some of the commonly used commands.
● 29
Learning Python with Raspberry Pi
3.1 Overview
Raspberry Pi operating system is based on a version of the Linux operating system. Linux
is one of the most popular operating systems in use today. Linux is very similar to other
operating systems, such as Windows and Unix. Linux is an open operating system based
on Unix and has been developed collaboratively by many companies and universities since
1991. In general, Linux is harder to manage than some other operating systems like Win-
dows, but offers more flexibility and wider configuration options. There are several popular
versions of the Linux operating system such as Debian, Ubuntu, Red Hat, Fedora and so on.
In this chapter we shall be looking at some of the commonly used Raspberry Pi commands
that we can enter from the command line. The commands entered by the user are shown
in bold for clarity.
The root directory is identified by the "/" symbol. Under the root we have directories
named such as bin, boot, dev, etc, home, lib, lost+found, media, mnt, opt, proc,
and many more. The important directory as far as the users are concerned is the home
directory which contains subdirectories for each user of the system. The full path to the
home directory is /home/pi. We can move to our home directory from any other directory
by entering the command cd ~
Some useful directory commands are given below. Command pwd displays the user home
directory:
pi@raspberrypi:~ $ pwd
/home/pi
pi@raspberrypi:~ $
To show the directory structure, enter the command ls / as shown in Figure 3.1.
To show the subdirectories and files in our home directory, enter ls as shown in Figure 3.2.
● 30
Chapter 3 • Using the Command Line
The ls command can take a number of arguments. Some examples are given below:
To display the subdirectories and files in a single row:
pi@raspberrypi:~ $ ls -1
To display the file type, enter the following command. Note that directories have a "/" after
their names, executable files have a "*" character after their names:
pi@raspberrypi:~ $ ls -F
pi@raspberrypi:~ $ ls –m
pi@raspberrypi:~ $ ls –m –F
subdirectories are created using command mkdir followed by the name of the subdirecto-
ry. In the following example, subdirectory myfiles is created in our working directory (see
Figure 3.3).
● 31
Learning Python with Raspberry Pi
The first pi in the example shows who the user of the file (or subdirectory) is, and the sec-
ond word pi shows the group name that owns the file (or subdirectory). In this example,
both the user and the group names are pi.
The permissions can be analysed by breaking down the characters into four chunks for: File
type, User, Group, World. The first character for a file is "-", and for a directory, it is "d".
Next comes the permissions for the User, Group and World. The permissions are as follows:
• Read permission (r): the permission to open and read a file or to list a directory
• Write permission (w): the permission to modify a file, or to delete or create a file
in a directory
• Execute permission (x): the permission to execute the file (applies to executable
files), or to enter a directory
The three letters rwx are used as a group and if there is no permission assigned then a "-"
character is used.
d: it is a directory
rwx: user (owner) can read, write, and execute
r-x: group can read and execute, but cannot write (e.g. create or delete)
r-x: world (everyone else) can read and execute, but cannot write
● 32
Chapter 3 • Using the Command Line
The chmod command is used to change the file permissions. Before going into details of
how to change the permissions, let us look and see what arguments are available in chmod
for changing the file permissions.
The available arguments for changing file permissions are given below. We can use these
arguments to add/remove permissions or to explicitly set permissions. It is important to
realize that if we explicitly set permissions then any unspecified permissions in the com-
mand will be revoked:
+: add
-: remove
=: set
r: read
w: write
x: execute
To change the permissions of a file we type the chmod command, followed by one of the
letters u, g, o, or a to select the people, followed by the + - or = to select the type of
change, and finally followed by the filename. An example is given below. In this example,
subdirectory Music has the user read and write permissions. We will be changing the per-
missions so that the user does not have read permission on this file:
● 33
Learning Python with Raspberry Pi
In the following example, rwx user permissions are given to subdirectory Music:
To change our working directory the command cd is used. In the following example we
change our working directory to Music:
pi@raspberrypi ~$ cd /home/pi/Music
pi@raspberrypi ~/Music $
to change our working directory to Music, we can also enter the command:
pi@raspberrypi ~$ cd ~/Music
pi@raspberrypi ~/myfiles $
pi@raspberrypi ~/Music $ cd ~
pi@raspberrypi ~$
to find out more information about a file we can use the file command. For example:
● 34
Chapter 3 • Using the Command Line
the –R argument of command ls lists all the files in all the subdirectories of the current
working directory. An example is shown in Figure 3.7.
3.4 Help
Man
To display information on how to use a command, we can use the man command. As an
example, to get help on using the mkdir command:
NAME
Mkdir – make directories
SYNOPSIS
Mkir [OPTION]…DIRECTORY…
DESCRIPTION
Create the DIRECTORY(ies), if they do not already exist.
-m, --mode=MODE
Set file mode (as in chmod), not a=rwx – umask
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Help
The man command usually gives several pages of information on how to use a command.
We can type q to exit the man command and return to the operating system prompt.
The less command can be used to display a long listing one page at a time. Using the up
and down arrow keys, we can move between pages. An example is given below. Type q to
exit:
● 35
Learning Python with Raspberry Pi
Copying a File
To make copy of a file, use the command cp. In the following example, a copy of file
mytestfile.txt is made and the new file is given the name test.txt:
Wildcards
We can use wildcard characters to select multiple files with similar characteristics. e.g. files
having the same file-extension names. The "*" character is used to match any number of
characters. Similarly, the "?" character is used to match any single character. In the exam-
ple below all the files with extensions ".txt" are listed:
pi@raspberrypi ~$ ls *.txt
The wildcard characters [a-z] can be used to match any single character in the specified
character range. An example is given below which matches any files that start with letters
o, p, q, r, s, and t, and with the ".txt" extension:
pi@raspberrypi ~$ ls [o-t]*.txt
Renaming a File
you can rename a file using the mv command. In the example below, the name of file test.
txt is changed to test2.txt:
● 36
Chapter 3 • Using the Command Line
Deleting a File
The command rm can be used to remove (delete) a file. In the example below file test2.
txt is deleted:
pi@raspberrypi ~$ rm test2.txt
the argument –v can be used to display a message when a file is removed. Also, the –i
argument asks for confirmation before a file is removed. In general, the two arguments are
used together as –vi. An example is given below:
Removing a Directory
A directory can be removed using the rmdir command:
● 37
Learning Python with Raspberry Pi
The echo command can also be used to write a line of text to a file. An example is shown
below:
Matching a String
The grep command can be used to match a string in a file. An example is given below
assuming that the file lin.dat contains sting a line of text. Notice that the matched word
is shown in bold:
Similarly, the tail command is used to display the last 10 lines of a file. The format of this
command is as follows:
● 38
Chapter 3 • Using the Command Line
Figure 3.9 Command: cat /proc/cpuinfo (only part of the output is shown)
Command uname –s displays the operating system Kernel name, which is Linux. Com-
mand uname –a displays complete detailed information about the Kernel and the operat-
ing system.
Command cat /proc/meminfo displays information about the memory on your Pi. Infor-
mation such as the total memory and free memory at the time of issuing the command are
displayed.
Command whoami displays the name of the current user. In this case it displays pi.
A new user can be added to our Raspberry Pi using the command useradd. In the example
in Figure 3.10, user called Johnson is added. A password for the new user can be added
using the passwd command followed by the username. In Figure 3.10, the password for
user Johnson is set to mypassword (not displayed for security reasons). Notice that both
the useradd and passwd are privileged commands and the keyword sudo must be en-
tered before these commands. Notice that the –m option creates a home directory for the
new user.
We can login to the new user account by specifying the username and the password.
● 39
Learning Python with Raspberry Pi
pi@raspberrypi ~$ dpkg –l
…………………………….
…………………………….
pi@raspberrypi ~$
We can also find out if a certain software package is already installed on our computer. An
example is given below which checks whether or not software called xpdf (PDF reader) is
installed. In this example, xpdf is installed and the details of this software are displayed:
If the software is not installed we get a message similar to the following (assuming we are
checking to see if a software package called bbgd is installed):
……………………………………………………………………………..
…………………………………………………………………………….
pi@raspberrypi ~$
Figure 3.11 shows a typical system resource display obtained by entering the following
command (Enter Ctrl+Z to exit):
pi@raspberrypi ~$ top
pi@raspberrypi ~$
● 40
Chapter 3 • Using the Command Line
Some of the important points in Figure 3.11 are summarized below (for lines 1 to 5 of the
display):
The process table gives the following information for all the processes loaded to the system:
● 41
Learning Python with Raspberry Pi
The ps command can be used to list all the processes used by the current user. An example
is shown in Figure 3.12.
the command ps –ef gives a lot more information about the processes running in the sys-
tem.
Killing a Process
There are many options for killing (or stopping) a process. A process can be killed by spec-
ifying its PID and using the following command:
Disk Usage
The disk free command df can be used to display the disk usage statistics. An example is
shown in Figure 3.13. option –h displays in human-readable form.
● 42
Chapter 3 • Using the Command Line
The following command will stop all the processes and make the file system safe and then
turn off the system safely:
the system can also be shut down and then re-started after a time by entering the following
command. Optionally, a shutdown message can be displayed if desired:
3.10 Summary
This chapter has described the use of some of the important Linux commands. You should
be able to get further information on each command and other Linux commands from the
internet and from other books on Raspberry Pi and Linux.
In the next chapter we shall see how to use a text editor which may be required for devel-
oping our Python programs.
● 43
Learning Python with Raspberry Pi
A text editor is used to create or modify the contents of a text file. There are many text ed-
itors available for the Linux operating system. Some popular ones are nano, vim, vi, and
many more. In this chapter, we shall be learning how to use the nano which is the most
commonly used text editor in Linux.
You should see the editor screen as in Figure 4.1. The name of the file to be edited is written
at the top middle part of the screen. The message "New File" at the bottom of the screen
shows that this is a newly created file. The shortcuts at the bottom of the screen are there
to perform various editing functions. These shortcuts are accessed by pressing the Ctrl key
together with another key. Some of the useful shortcuts are given below:
Ctrl+J: Justify
● 44
Chapter 4 • Using a Text Editor in Command Mode
Step 2: Look for word simple by pressing Ctrl+W and then typing simple in the window
opened at the bottom left-hand corner of the screen. Press the Enter key. The cursor will
be positioned on the word simple (see Figure 4.2).
● 45
Learning Python with Raspberry Pi
Step 3: Cut the first line by placing the cursor anywhere on the line and then pressing
Ctrl+K. The first line will disappear.
Step 4: Paste the line cut after the first line. Place the cursor on the second line and press
Ctrl+U (see Figure 4.3).
Step 5: Place cursor at the beginning of the word simple in the first row. Enter Ctrl+C.
The row and column positions of this word will be displayed at the bottom of the screen.
Step 6: Press Ctrl+G to display the help page as in Figure 4.4. Notice that the display is
many pages long and you can jump to the next pages by pressing Ctrl+Y or to the previous
pages by pressing Ctrl+V. Press Ctrl+X to exit the help page.
Step 7: Press Ctrl+- and enter line and column numbers as 2 and 5, followed by the Enter
key, to move cursor to line 2, column 5.
Step 8: Replace word example with word file. Press Ctrl+\ and type the first word as
example (see Figure 4.5). Press Enter and then type the replacement word as file. Press
Enter and accept the change by typing y.
● 46
Chapter 4 • Using a Text Editor in Command Mode
Step 9: Save the changes. Press Ctrl+X to exit the file. Type Y to accept the saving, then
enter the filename to be written to, or simply press Enter to write to the existing file (first.
txt in this example). The file will be saved in your current working directory.
pi@raspberrypi ~ $
In summary, nano is a simple and yet powerful text editor allowing us to create new text
files or to edit existing files.
4.2 Summary
Text editors are useful in creating new text files, or for modifying the contents of a text file.
Notice that a text editor is not the same as a word processing software. Word processing
software inserts additional control characters inside a text such as bold, underline, and
other formatting characters.
In this chapter, we have seen how to use two of the popular Linux text editor nano. The
remainder of the book is devoted to the Python programming language.
● 47
Learning Python with Raspberry Pi
5.1 Overview
In this chapter, we shall be learning how to create and then run a very simple Python pro-
gram. As described in this chapter, basically there are three methods that we can use to
create and run a Python program. The text message Hello From Raspberry Pi 4 will be
displayed on our screen as an example.
Two versions of the Python language are distributed with the Raspberry Pi at the time of
writing this book: Version 2 and 3. The actual version numbers can be displayed by enter-
ing the command python --version as shown in Figure 5.1. The display shows that the
two versions are 2.7.16 and 3.7.3. The advantage of using Python 3 is that most of the new
libraries are being developed for Python 3. Some of the Python 2.7 libraries are not com-
patible with Python 3.7. Python 3.7 has improved integer division, better Unicode support.
Additionally, version 3.7 has better error handling and improved GUI support.
• At the command prompt enter python. You should see the Python command
mode which is identified by three characters >>>
• The required text will be displayed interactively on the screen as shown in Figure
5.2
● 48
Chapter 5 • Creating and Running a Python Program
Notice that by default, entering command python invokes version 2.7. If you wish to use
version 3.7 then you should enter the command python3 instead.
• Click Programming and then click Thonny Python IDE (see Figure 5.4)
• Type in your program as shown in Figure 5.5 and save it e.g. with the name
hello2
● 49
Learning Python with Raspberry Pi
• Run the program by clicking Run. You should see the program output displayed
at the bottom part of the screen as shown in Figure 5.6.
5.6 Summary
In this chapter, we have learned how to create and run a Python program. In the remaining
chapters, of the book we will concentrate on the Python programming language.
● 50
Chapter 6 • Python Programming
6.1 Overview
Python is an interpreted, interactive and object-oriented programming language. It was
developed by Guido van Rossum in the 1980s at the National Institute for Mathematics and
Computer Science in the Netherlands. It is derived from many other languages including
C, C++, Modula-3, SmallTalk, and Unix shell. The language is now maintained by a team
of people at the Institute.
Python is interactive which means that you can issue a command and see the result im-
mediately without having to compile the command. It is interpreted, thus requiring no
pre-compilation before it is run.
In this and next chapters, we will be looking at the details of the Python programming
language on the Raspberry Pi computer, and see how we can write programs using this
language. Many example programs are given to show how electronic engineers can use the
Python language to help them in their calculations.
SUM - valid
Sum - valid
SUm - valid
_total - valid
Cnt5 - valid
8tot - invalid
%int - invalid
&xyz - invalid
My_Number - valid
@loop - invalid
_Account - valid
Note that variables total, Total, TOTAL, ToTaL, or toTAL are all different.
● 51
Learning Python with Raspberry Pi
6.4 Comments
Comment lines in Python start with a hash sign "#". All characters after the # sign are
ignored by the Python interpreter. An example comment line is shown below:
Sum = a +\
b +\
c
Sum = a + b + c
● 52
Chapter 6 • Python Programming
6.8 Indentation
In most programming languages blocks of code are identified by using braces at the begin-
ning and end of the block, or by identifying the end of the block using a suitable statement.
e.g. END, WEND, or ENDIF. In Python language, there are no braces or statements to indi-
cate the start and end of a block. Instead, blocks of code are identified by line indentation.
All statements within a block must be indented the same amount. The actual number of
spaces used to indent a block is not important as long as all the statements in the block use
the same number of spaces.
A valid block of code is given below (don't worry at this stage what the code does):
if j == 5:
a = a + 1
b = a + 2
else:
a = 0
b = 0
The following block of code is not valid since the indentation is not correct:
if j == 5:
a = a + 1
b = a + 2
else:
a = 0
b = 0
• Numbers
• Strings
• Lists
• Dictionaries
• Tuples
• Sets
• Files
● 53
Learning Python with Raspberry Pi
6.10 Numbers
Python supports the following numeric variable types:
Numbers can be represented in decimal, octal, binary, or hexadecimal. Long integers are
shown with an upper case letter L.
Integer
100 - decimal
-67 - decimal
500 - decimal
0x20 - hexadecimal
0b10000001 - binary
0o2377 - octal
202334567L - long decimal
0x3AEEFAE - hexadecimal
Floating point
2.355
23.780
-45.6
1.298
24.45E4
Complex
24.4+2,6j
0.78-4.2j
23.7j
We can assign numeric values to variables. These variable objects are created when values
are assigned to them:
sum = 28
a = 0
● 54
Chapter 6 • Python Programming
del sum, a
w = x = y = z = 0
w, x, y = 3, 5, 8
w = 3
x = 5
y = 8
Expression Operators
+ addition
- Subtraction
* multiplication
/ division
>> shift right
<< shift left
** power (exponentiation)
% remainder
Bitwise Operators
| bitwise OR
& bitwise AND
^ bitwise exclusive-or
~ bitwise complement
● 55
Learning Python with Raspberry Pi
Figure 6.1 to Figure 6.3 show examples of using numbers in Python. Statement import
is used to import a library to a Python program. math library contains a large number of
mathematical functions, such as logarithmic functions, trigonometric function, square root,
hyperbolic functions, angular conversion, and so on. Further details on these functions can
be obtained from the following link:
https://docs.python.org/3/library/math.html
random library is useful to generate random numbers. Function randint(a, b) in this li-
brary generates an integer random number between integers a and b inclusive. Details of
functions available in the random library can be obtained from the following link:
https://docs.python.org/2/library/random.html
● 56
Chapter 6 • Python Programming
6.11 Strings
In Python, strings are declared by enclosing characters between a pair of single or double
quotation marks. An example is given below:
We can manipulate strings by extracting characters, joining two strings, assigning a string
to another string, and so on. Some commonly used string manipulation operations are
shown in Figure 6.4 and Figure 6.5.
● 57
Learning Python with Raspberry Pi
Notice that a third index as the step can be used in string slicing operation. The step is add-
ed to the first offset until the second offset and the character at this position is extracted.
In the following example, the characters at positions 0, 2, 4, 6 are extracted:
>>> a = "computer"
>>> b = a[0:7:2]
>>> print(b)
cmue
● 58
Chapter 6 • Python Programming
• capitalize() change first letter of a string to upper case and all other
characters to lower case
• count(str,beg,end) find how many times str occurs in a string. String start-
ing and ending positions should be specified
• find(str,beg,end) determine if str occurs in a string. String starting and
ending positions should be specified. The index is re-
turned if the str is found, otherwise -1 is returned
• len(string) return the length of a string
• isalpha() return true if string contains all alphabetical characters
• isalnum() return true if string contains alphabetical and numeric
characters
• isdigit() return true if string contains all digits
• islower() return true if string contains all lower case letters
• isupper() return true if string contains all upper case letters
• lower() convert all upper case characters to lower case
• upper() convert all lower case characters to upper case
• lstrip() remove all leading white spaces
• rstrip() remove all trailing spaces
• swapcase() change case of all letters
• \n newline
• \a bell
• \b backspace
● 59
Learning Python with Raspberry Pi
• \f formfeed
• \r carriage return
• \t horizontal tab
• \v vertical tab
• \xhh character with 2 hexadecimal value hh
As an example, the following statement will display letter a followed by two newlines:
print("a\n\n")
• %c character
• %s string
• %d signed integer
• %u unsigned integer
• %x lower case hexadecimal number
• %X upper case hexadecimal number
• %f floating-point number
• %E exponential notation
● 60
Chapter 6 • Python Programming
s = mylist[0] # s = 'John'
s = mylist[2] # s = 230
s = mylist[2:4] # s = 230, 12.25
s = mylist[3:] # s = 12.25, 'Peter', 89
s = mylist * 2 # s =
'John', 'Adam', 230, 12.25, 'Peter', 89, 'John',
'Adam', 230, 12.25, 'Peter', 89
s = mylist + second # s = 'John', 'Adam', 230, 12.25, 'Peter', 89, 30, 23
The contents of a list can be modified by assigning a new value to the required index po-
sition. For example, we can change the 2nd element of the list mylist from 230 to 100 as:
mylist[2] = 100
Python does not allow to reference items that are not present in a list. For example, the
following statement gives an error message:
mylist[200]
Lists can be nested to form two dimensional matrices. An example is given below:
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
The nested list is indexed starting from [0][0]. For example, the elements of row 1 can be
accessed as follows:
● 61
Learning Python with Raspberry Pi
● 62
Chapter 6 • Python Programming
s = mytuple[0] # s = 'John'
s = mytuple[2] # s = 230
s = mytuple[2:4] # s = 230, 12.25
s = mytuple[3:] # s = 12.25, 'Peter', 89
s = mytuple * 2 # s = 'John', 'Adam', 230, 12.25, 'Peter', 89, 'John',
'Adam', 230, 12.25, 'Peter', 89
s = mytuple + second # s = 'John', 'Adam', 230, 12.25, 'Peter', 89, 30,
23
The following statement is not valid since we cannot change the contents of a tuple:
mytuple[2] = 200
● 63
Learning Python with Raspberry Pi
• raw_input provides a prompted read. The data from the keyboard is re-
turned as a string
figure 6.10 shows examples of using the keyboard input function. Notice that the function
returns a string. Therefore, if numeric data is entered then it should be converted into a
numeric data type before being used in mathematical operations.
Notice that Python version 3 provides the statement called input for reading prompted
data from the keyboard. This statement evaluates the data read i.e. it identifies whether
the user entered a string or a number or a list.
● 64
Chapter 6 • Python Programming
• < checks if the left operand is less than the right one
• >= checks if the left operand is greater than or equal to the right one
• <= checks if the left operand is less than or equal to the right one
• = assignment operator
• += compound add operator
• -= compound subtract operator
• *= compound multiply operator
• /= compound divide operator
• if
• if-else
• elif
• for
• while
• break
• continue
• pass
if expression: statement
or
if expression:
Statement 1
Statement 2
else:
Statement 1
Statement 2
● 65
Learning Python with Raspberry Pi
Notice the use of indentation inside the if blocks and the colon character at the end of the
if and else statements.
if a == 5: print('a is 5')
if there is only one statement after the if, then it can be typed on the same line. If there is
more than one statement then all the statements must be written on the next lines with
the same amount of indentation. An example is given below:
if a == 100:
x = 0
y = 0
else:
x = 1
y = 10
The elif statement is used to check for different conditions in an if block. An example is
given below:
if a > 10:
b = 0
c = 0
elif a == 10:
b = 2
c = 4
Notice that the if statements can be nested as shown in the following example:
if a == 100:
c = 0
k = 1
if b == 10:
c = 20
m = 1
else:
c = 23
● 66
Chapter 6 • Python Programming
Here, the sequence is evaluated first and the first item in the sequence is assigned to the
variable and the statements are executed. Then the second item is assigned to the varia-
ble and the statements are executed. This continues until there are no more items in the
sequence. An example use of the for statement is shown below:
C
O
M
P
U
T
E
R
The for statement is commonly used to create loops in programs. The range statement
denotes the range of the variable as in the following example:
0
1
2
3
4
Notice that the upper value of the range is one less than the specified value i.e. in the above
example, the range is from 0 to 4 and not to 5.
We can specify a step size in the last parameter when using the range statement, in the
following example, the step size is 5 and the list takes values 0, 5, 10, 15, 20, 25:
● 67
Learning Python with Raspberry Pi
while expression:
statements
The statements are executed while the expression evaluates to True. An example is given
below:
cnt = 0
while cnt < 5:
print(cnt)
cnt = cnt + 1
0
1
2
3
4
Notice that the statements that belong to the while statement must be indented. It is im-
portant to make sure that the expression is modified inside the loop, otherwise, an infinite
loop will be formed as shown in the following example:
cnt = 0
while cnt < 5:
print(cnt)
cnt = 0
while cnt < 5:
cnt = cnt + 1
if cnt == 3:
continue
print(cnt)
● 68
Chapter 6 • Python Programming
1
2
4
5
cnt = 0
while cnt < 5:
cnt = cnt + 1
if cnt == 3:
break
print(cnt)
1
2
C
O
M
Passed
P
U
T
E
R
● 69
Learning Python with Raspberry Pi
We have covered the basic statements of the Python programming language. We will now
develop several projects using the knowledge we have gained so far.
Aim: The aim of this case study is to show how the keyboard input, lists and control state-
ments can be used in a program.
Background Information: Resistor values are identified by the following colour codes:
Black: 0
Brown: 1
Red: 2
Orange: 3
Yellow: 4
Green: 5
Blue: 6
Violet: 7
Grey: 8
White: 9
First two colour determine the first two digits of the value while the last colour determines
the multiplier. For example, red red red corresponds to 22 x 102 = 2200 Ohms.
Program Listing: Figure 6.11 shows the program listing (program: resistor.py). At the
beginning of the program, a list called colour is created which stores the valid resistor
colours. Then a heading is displayed and a while loop is created which runs as long as
string variable yn is equal to y. Inside the loop the program reads the three colours from
the keyboard using functions raw_input and stores as strings in variables FirstColour,
SecondColour and ThirdColour. These strings are then converted into lower case so that
they are compatible with the values listed in the list box. The index values of these colours
in the list are then found using function calls of the form colours.index. Remember that
the index values start from 0. As an example, if the user entered red then the correspond-
ing index value will be 2. The resistor value is then calculated by multiplying the first colour
number by 10 and adding to the second colour number. The result is then multiplied by
the power of 10 of the third colour index. The final result is displayed on the screen. The
program then asks whether or not the user wants to continue. If the answer is y then the
program returns to the beginning, otherwise the program is terminated.
#===================================================
# RESISTOR COLOUR CODES
# ---------------------
#
● 70
Chapter 6 • Python Programming
while yn == 'y':
FirstColour = raw_input("Enter First Colour: ")
SecondColour = raw_input("Enter Second Colour: ")
ThirdColour = raw_input("Enter Third Colour: ")
#
# Convert to lower case
#
FirstColour = FirstColour.lower()
SecondColour = SecondColour.lower()
ThirdColour = ThirdColour.lower()
#
# Find the values of colours
#
FirstValue = colours.index(FirstColour)
SecondValue = colours.index(SecondColour)
ThirdValue = colours.index(ThirdColour)
#
# Now calculate the value of the resistor
#
Resistor = 10 * FirstValue + SecondValue
Resistor = Resistor * (10 ** ThirdValue)
print("Resistance = %d Ohms" % (Resistor))
#
# Ask for more
#
yn = raw_input("\nDo you want to continue?: ")
yn = yn.lower()
● 71
Learning Python with Raspberry Pi
The program was created using the nano text editor and then run from the command line
by entering the following command:
Program Listing: Figure 6.13 shows the program listing (program: resistor2.py). Col-
ours gold and silver are added to the list. The indexes of gold and silver in the list are 10
and 11 respectively. Most of the program is same as in Figure 6.11, except that if the third
colour is gold then the result is divided by 10. Similarly, if the third colour is silver then
the result is divided by 100. Notice that if the resistor value is less than 10 Ohms then it
is displayed in floating-point format with 2 digits after the decimal point by using the print
formatting parameter %3.2f.
#=================================================
# RESISTOR COLOUR CODES
# ---------------------
#
# The user enters the three colours of a resistor
# and the program calculates and displays the value
# of the resistor in Ohms. The program identifies all
# types of resistors with 4 colour bands
#
# Program: resistor2.py
● 72
Chapter 6 • Python Programming
while yn == 'y':
FirstColour = raw_input("Enter First Colour: ")
SecondColour = raw_input("Enter Second Colour: ")
ThirdColour = raw_input("Enter Third Colour: ")
#
# Convert to lower case
#
FirstColour = FirstColour.lower()
SecondColour = SecondColour.lower()
ThirdColour = ThirdColour.lower()
#
# Find the values of colours
#
FirstValue = colours.index(FirstColour)
SecondValue = colours.index(SecondColour)
ThirdValue = colours.index(ThirdColour)
#
# Now calculate the value of the resistor
#
Resistor = 10 * FirstValue + SecondValue
if ThirdValue == 10:
Resistor = Resistor / 10.0
print("Resistance = %3.2f Ohms" % (Resistor))
elif ThirdValue == 11:
Resistor = Resistor/100.0
print("Resistance = %3.2f Ohms" % (Resistor))
else:
Resistor = Resistor * (10 ** ThirdValue)
print("Resistance = %d Ohms" % (Resistor))
#
# Ask for more
#
yn = raw_input("\nDo you want to continue?: ")
yn = yn.lower()
● 73
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how the keyboard input and flow control state-
ments can be used in a program.
Background Information: When a number of resistors are in series then the resultant
resistance is the sum of the resistance of each resistor. When the resistors are in parallel
then the reciprocal of the resultant resistance is equal to the sum of the reciprocal resist-
ances of each resistor.
Program Listing: Figure 6.15 shows the program listing (program: serpal.py). At the
beginning of the program a heading is displayed and the program enters into a while loop.
Inside his loop the user is prompted to enter the number of resistors in the circuit and
whether they are connected in series or in parallel. Function str converts a number into
its equivalent string. e.g. number 5 is converted into string "5". If the connection is serial
(mode equals to 's') then the value of each resistor is accepted from the keyboard and the
resultant is calculated and displayed on the screen. If on the other hand the connection is
parallel (mode is equal to 'p') then again the value of each resistor is accepted from the
keyboard and the reciprocal of the number is added to the total. When all the resistor val-
ues are entered, the resultant resistance is displayed on the screen.
● 74
Chapter 6 • Python Programming
#===================================================
# RESISTORS IN SERIES OR PARALLEL
# -------------------------------
#
# This program calculates the total resistance of
# serial or parallel connected resistors
#
# Program: serpal.py
# Date : July, 2019
# Author : Dogan Ibrahim
#===================================================
print("RESISTORS IN SERIES OR PARALLEL")
print("===============================")
yn = "y"
while yn == 'y':
N = int(raw_input("\nHow many resistors are there?: "))
mode = raw_input("Are the resistors series (s) or parallel (p)?: ")
mode = mode.lower()
#
# Read the resistor values and calculate the total
#
resistor = 0.0
if mode == 's':
for n in range(0,N):
s = "Enter resistor " + str(n+1) + " value in Ohms: "
r = int(raw_input(s))
resistor = resistor + r
print("Total resistance = %d Ohms" %(resistor))
● 75
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how to use the keyboard input and flow control
statements in a program.
● 76
Chapter 6 • Python Programming
The above formula is used to calculate the required value of R1, given Vin, Vo, and R2
Program Listing: Figure 6.18 shows the program listing (program: divider.py). At the
beginning of the program, a heading is displayed. The program then reads Vin, Vo, and R2
from the keyboard. The program calculates R1 and displays R1 and R2. The user is then
asked to enter a chosen physical value for R1. With the chosen value of R1, the program
displays Vin, Vo, R1, and R2 and asks the user whether or not the result is acceptable. If the
answer to this question is y then the program terminates. If on the other hand, the answer
is n then the user is given the option of trying again.
#======================================================
# RESISTIVE POTENTIAL DIVIDER
# ---------------------------
#
# This is a resistive potential divider circuit program.
# The program calculates the resistance values that will
# lower the input voltage to the desired value
#
# Program: divider.py
# Date : July, 2019
# Author : Dogan Ibrahim
#=======================================================
print("RESISTIVE POTENTIAL DIVIDER")
print("===========================")
R1flag = 1
R2flag = 0
while R1flag == 1:
Vin = float(raw_input("\nInput voltage (Volts): "))
Vo = float(raw_input("Desired output voltage (Volts): "))
R2 = float(raw_input("Enter R2 (in Ohms): "))
#
# Calculate R1
#
R1 = R2 * (Vin - Vo) / Vo
print("\nR1 = %3.2f Ohms R2 = %3.2f Ohms" %(R1, R2))
#
# Read chosen physical R1 and display actual Vo
● 77
Learning Python with Raspberry Pi
#
NewR1 = float(raw_input("\nEnter chosen R1 (Ohms): "))
#
# Display and print the output voltage with chosen R1
#
print("\nWith the chosen R1,the results are:")
Vo = R2 * Vin / (NewR1 + R2)
print("R1 = %3.2F R2 = %3.2f Vin = %3.2f Vo = %3.3f" %(NewR1,R2,Vin,Vo))
#
# Check if happy with the values ?
#
happy = raw_input("\nAre you happy with the values? ")
happy = happy.lower()
if happy == 'y':
break
else:
mode = raw_input("Do you want to try again? ")
mode = mode.lower()
if mode == 'y':
R1flag = 1
else:
R1flag = 0
break
● 78
Chapter 6 • Python Programming
Some examples of using the trigonometric functions are given in Figure 6.20.
A function that we create can be called from anywhere in a program. Functions have their
own variables and their own commands. As we have seen in earlier parts of this chapter,
Python has a large number of built-in functions for various operations such as arithmetic,
trigonometric, string manipulation and so on. User-defined functions are created by pro-
grammers. In this section, we shall be looking at how functions can be created and used
in our programs.
• functions begin with the keyword def, followed by function name, and round
brackets, followed by a colon sign.
• Input arguments to the function must be placed inside the brackets at the begin-
ning of the function definition.
• The body of a function must be indented with the same number of spaces on the
left hand side
• An optional text message can be displayed at the first line of a function to de-
scribe what the function does.
• A function must be terminated with the return statement
● 79
Learning Python with Raspberry Pi
An example function, named Mult is given below. This function takes two numbers first and
second as its arguments, multiplies them, and returns the result:
A function is called from the main program by specifying the name of the function and
enclosing any arguments in a pair of brackets. For example, to call the above function to
multiply numbers 5 and 3 and sore the result in variable called a, we include the following
statement in our program:
a = Mult(5, 3)
a = Mult(first = 5, second = 3)
Another example is shown in Figure 6.22. In this example, the function displays a string
passed as an argument. Notice that there is no data returned from this function.
The variables used in a function are local to that function. Thus, for example, if there are
two variables with the same name, one inside the function and the other one outside,
changing the one inside the function does not change the one outside. Variables outside
a function are called global variables, whereas the ones inside a function are called lo-
cal variables. See Figure 6.23 for an example where the contents of variable res are not
changes outside the function.
● 80
Chapter 6 • Python Programming
• Global variables are variables assigned at the top of the program outside the
function definitions
• Global names must be declared only if they are assigned within a function
• Global names may be referenced within a function without being declared
Therefore, by declaring a variable outside the functions and also inside a function but with
the global keyword allows us to change its contents inside the function. An example is given
below which identifies the use of global variables:
as explained above, it the value of a global variable is not changed inside a function then
there is no need to define it as global. In the following code there is no need to define x as
global inside the function:
x = 10
y = 4
def tst():
global y
y = x + 2
It is important to note that the variables in a function call are passed by value. This means
that the value of a parameter cannot be changed inside a function. An example is shown
in Figure 6.24. In this example, notice that the value of variable cnt is not changed inside
the function call.
● 81
Learning Python with Raspberry Pi
A function normally returns only one item back to the calling program. In some applications,
we may want to return more than one item to the calling program. This is easily done by
returning a tuple and then unpacking it in the main program. An example is shown in Figure
6.25. In this example, function MyFunc is declared with two arguments. The arguments
are added and stored in a local variable called sum. Similarly, the difference of the argu-
ments is stored in variable diff. The function returns both sum and diff as a tuple. The
calling main program unpacks the returned data and stores in variables x and y.
Example 1
Write a program to read an angle from the keyboard in degrees and display the trigonomet-
ric sine of this angle. Repeat until the user stops the program.
Solution 1
The required program listing is shown in Figure 6.26 (program: trig.py). The angle entered
by the user is converted into floating point and is stored in variable angle. Then the trigo-
nometric sine of this angle is displayed. The program continues until the user enters n in
response to prompt Any more?
#----------------------------------------------
# TRIGONOMETRIC SINE PROGRAM
# ==========================
#
# This program reads an angle from the keyboard
# and displays its trigonometric sine
● 82
Chapter 6 • Python Programming
#
# Author: Dogan Ibrahim
# File : trig.py
# Date : July, 2019
#----------------------------------------------
import math
yn = 'y'
print("Trigonometric sine")
print("==================\n")
while yn == 'y':
angle = float(raw_input("Enter angle in degrees: "))
r = math.radians(angle)
s = math.sin(r)
print("sine of %3.2f degrees is: %f\n" %(angle, s))
yn = raw_input("Any more? ")
Example 2
Modify the program in Example 1 so that the user can choose between sine, cosine, and
tangent.
Solution 2
The modified program listing is shown in Figure 6.28 (program: trigall.py). The user is
given a menu with four choices: sine, cosine, tangent, exit. The angle is read from the key-
board and is converted into radians. The program then calculates the trigonometric value
and displays on the screen. This process is repeated until the user selects the exit option.
● 83
Learning Python with Raspberry Pi
#-----------------------------------------------------
# TRIGONOMETRIC SINE,COSINE,TANGENT PROGRAM
# =========================================
#
# This program reads an angle from the keyboard
# and displays its trigonometric sine, cosine, or
# tangent depending on user choice. The angle is
# read in degrees,converted into radians and then
# the required trigonometric function is calculated
#
# Author: Dogan Ibrahim
# File : trigall.py
# Date : July, 2019
#-----------------------------------------------------
import math
choice = '1'
while choice != '0':
print("Trigonometric Sine, Cosine, or Tangent")
print("======================================\n")
print("1. Sine")
print("2. Cosine")
print("3. Tangent")
print("0. Exit")
choice = raw_input("Enter choice: ")
if choice != '0':
angle = float(raw_input("Enter angle in degrees: "))
r = math.radians(angle)
if choice == '1':
s = math.sin(r)
strng = "sine"
elif choice == '2':
s = math.cos(r)
strng = "cosine"
elif choice == '3':
s = math.tan(r)
strng = "tangent"
print(strng + " of %3.2f degrees is: %f\n" %(angle, s))
print("End of program")
● 84
Chapter 6 • Python Programming
Example 3
Write a program to tabulate the trigonometric sines of angles from 0º to 90º in steps of 5º.
Solution 3
The required program listing is shown in Figure 6.30 (program: sinetable.py). After dis-
playing a heading, the for statement is used to create a loop. Variable angle takes values
from 0 to 90 (inclusive) in steps of 5. The trigonometric sine is calculated and displayed.
#--------------------------------------------------
# TRIGONOMETRIC SINE TABLE
# ========================
#
# This program tabulates the trigonometric sine of
# angles from 0 to 90 degrees in steps of 5 degress
#
# Author: Dogan Ibrahim
# File : sinetable.py
# Date : July, 2019
#--------------------------------------------------
import math
● 85
Learning Python with Raspberry Pi
print("End of program")
Example 4
Repeat Example 3, but tabulate the trigonometric sine, cosine and tangent of angles from
0º to 30º in steps of 2º.
Solution 4
The required program listing is shown in Figure 6.32 (program: alltrig.py). After displaying
a heading, the program calculates and displays the trigonometric functions sine, cosine and
tangent.
#--------------------------------------------------
# TABLE OF TRIGONOMETRIC FUNCTIONS
# ================================
#
# This program tabulates the trigonometric sine,
# cosine and tangent from 0 to 30 degrees in steps
# of 2 degrees
#
# Author: Dogan Ibrahim
# File : alltrig.py
# Date : July, 2019
#--------------------------------------------------
● 86
Chapter 6 • Python Programming
import math
print("End of program")
Example 5
Write a program to read metres from the keyboard. Convert into yards and inches and
display the result.
Solution 5
The required program listing is shown in Figure 6.34 program: conv.py). After displaying
a heading, metres is read from the keyboard using the raw_input statement. The value is
then converted into yards and inches by multiplying with 1.0936 and 39.370 respectively.
The results are displayed on the screen.
● 87
Learning Python with Raspberry Pi
#--------------------------------------------------
# CONVERSION PROGRAM
# ==================
#
# This program reads metres from the keyboard and
# converts and displays in yards and inches
#
# Author: Dogan Ibrahim
# File : conv.py
# Date : July, 2019
#--------------------------------------------------
print("Convert metres into yards and inches")
print("====================================")
metres = float(raw_input("Enter metres: "))
yards = 1.0936 * metres
inches = 39.370 * metres
print("%f metres = %f yards, %f inches" %(metres, yards, inches))
print("End of program")
Example 6
Repeat Example 5 but do the conversion in a function called Conv. Show how this function
can be called from the main program.
Solution 6
The required program listing is shown in Figure 6.36 (program: convfunc.py). Function
Conv is declared at the beginning of the program. Metres to be converted into yards and
inches is passed as an argument to the function. The function returns the yards and inches
in a tuple. The main program reads the metres from the keyboard and calls function Conv.
The result is displayed on the screen.
● 88
Chapter 6 • Python Programming
#--------------------------------------------------
# CONVERSION PROGRAM
# ==================
#
# This program reads metres from the keyboard and
# converts and displays in yards and inches
#
# Author: Dogan Ibrahim
# File : convfunc.py
# Date : July, 2019
#--------------------------------------------------
def Conv(m):
"Convert metres into yards and inches"
y = 1.0936 * m
i = 39.370 * m
return y, i
Example 7
Write a function called Tconv to convert ºC to ºF. Show how this function can be used in a
main program.
Solution 7
The formula to convert ºC to ºF is given by:
F = 1.8C + 32
The required program listing is shown in Figure 6.38 (program: ctof.py). Main program
reads the temperature in degrees Centigrade from the keyboard and calls function Tconv
to convert into Fahrenheit. The result is displayed on the screen.
● 89
Learning Python with Raspberry Pi
#-----------------------------------------------------
# CONVERSION PROGRAM
# ==================
#
# This program reads temperature in degrees Celsius
# from the keyboard and converts into degrees Fahrenheit
#
# Author: Dogan Ibrahim
# File : ctof.py
# Date : July, 2019
#-----------------------------------------------------
def Tconv(C):
"Convert Centigrade to Fahrenheit"
F = 1.8 * C + 32
return F
Example 8
Write a function called Cyl to calculate the area and volume of a cylinder, given its radius
and height. Use this function in a main program.
Solution 8
The area and volume of a cylinder are given by the formula:
Area = 2πrh
Volume = πr2h
The required program listing is shown in Figure 6.40 (program: cylinder.py). the radius
● 90
Chapter 6 • Python Programming
and height of the cylinder are passed as arguments to a function which calculates the area
and volume of the cylinder and returns the results to the main program which are displayed
on the screen.
#-----------------------------------------------------
# CONVERSION PROGRAM
# ==================
#
# This program reads the radius and height of a cylinder
# and calculates and displays its area and volume
#
# Author: Dogan Ibrahim
# File : cylinder.py
# Date : July, 2019
#-----------------------------------------------------
import math
● 91
Learning Python with Raspberry Pi
Example 9
Write a program to store the names of the days of a week and then display these names.
Solution 9
The required program listing is shown in Figure 6.42 (program: wdays.py). List days
stores the names of the days in a week. A for loop is used to display these names.
#----------------------------------------------
# DAYS OF A WEEK
# ==============
#
# This program displays teh days of a week
#
# Author: Dogan Ibrahim
# File : wdays.py
# Date : July, 2019
#----------------------------------------------
days = ["Monday","Tuesday","Wednesday","Thursday",\
"Friday","Saturday","Sunday"]
Example 10
Write a program to read a word from the keyboard and then display the letters of this word
in reverse order on the screen.
Solution 10
The required program listing is shown in Figure 6.44 (program: letters.py). A word is read
from the keyboard and stored in string variable word. Then the letters of this word are
displayed in reverse order.
● 92
Chapter 6 • Python Programming
#----------------------------------------------
# LETTERS OF A WORD
# =================
#
# This program reads a word and displays its letter
# in reverse order
#
# Author: Dogan Ibrahim
# File : letters.py
# Date : July, 2019
#----------------------------------------------
word = raw_input("Enter a word: ")
l = len(word)
k = 0
while l != 0:
k = k -1
print(word[k])
l = l -1
Example 11
Write a calculator program to carry out the four simple mathematical operations of addi-
tion, subtraction, multiplication, and division on two numbers received from the keyboard.
Solution 11
The required program listing is shown in Figure 6.46 (program: calc.py). Two numbers are
received from the keyboard and stored in variables n1 and n2. Then, the required math-
ematical operation is received and it is performed. The result, stored in variable result, is
displayed on the screen. The user is given the option of terminating the program.
● 93
Learning Python with Raspberry Pi
#----------------------------------------------
# CALCULATOR PROGRAM
# ==================
#
# This is a simple calculator program that can
# carry out 4 basic arithmetic opertions
#
# Author: Dogan Ibrahim
# File : calc.py
# Date : July, 2019
#----------------------------------------------
any = 'y'
while any == 'y':
print("\nCalculator Program")
print("==================")
if op =="+":
result = n1 + n2
elif op == "-":
result = n1 - n2
elif op == "*":
result = n1 * n2
elif op == "/":
result = n1 / n2
print("Result = %f" %(result))
any = raw_input("\nAny more (yn): ")
● 94
Chapter 6 • Python Programming
Example 12
Write a program to simulate double dice. i.e. to display two random numbers between 1
and 6 every time it is run.
Solution 12
The required program listing is shown in Figure 6.48 (program: dice.py). Here, the random
number generator randint is used to generate random numbers between 1 and 6 when the
Enter key is pressed. The program is terminated when letter X is entered.
#----------------------------------------------
# DOUBLE DICE
# ===========
#
# This program displays two random dice numbers
# between 1 and 6 when the Enter key is pressed
#
# Author: Dogan Ibrahim
# File : dice.py
# Date : July, 2019
#----------------------------------------------
import random
strt = 'a'
● 95
Learning Python with Raspberry Pi
Example 13
Write a program to display the squares of integer numbers between 1 and 10.
Solution 13
The required program listing is shown in Figure 6.50 (program: sqrs.py).
#----------------------------------------------
# SQUARES OF NUMBERS
# ==================
#
# This program displays the squares of numbers
# between 1 and 10
#
# Author: Dogan Ibrahim
# File : sqrs.py
# Date : July, 2019
#----------------------------------------------
print("NUMBER SQUARE")
print("====== ======")
● 96
Chapter 6 • Python Programming
Example 14
Write a program to calculate and display the sum of integer numbers in a list.
Solution 14
The required program listing is shown in Figure 6.52 (program: nsums.py). The program
calculates the sum of numbers between 1 and 10 and displays the result.
#----------------------------------------------
# SUM OF NUMBERS
# ==============
#
# This program calculates and displays the sum
# of numbers in a list
#
# Author: Dogan Ibrahim
# File : nsums.py
# Date : July, 2019
#----------------------------------------------
numbers = [1, 3, 5, 2, 9, 7]
L = len(numbers)
sum = 0
for k in range(L):
sum = sum + numbers[k]
The program displays 27 as the sum of the numbers in the list in Figure 6.52.
● 97
Learning Python with Raspberry Pi
Example 15
Write a program to use functions to calculate and display the areas of shapes: square,
rectangle, triangle, circle, and cylinder. The sizes of the required sides should be received
from the keyboard.
Solution 15
The areas of the shapes to be used in the program are as follows:
The required program listing is shown in Figure 6.53 (program: areas.py). a different func-
tion is used for each shape and the sizes of the sides are received inside the functions. The
main program displays the calculated area for the chosen shape.
#------------------------------------------------------------
# AREAS OF SHAPES
# ===============
#
# This program calculates and displays the areas of various
# geometrical shapes
#
# Author: Dogan Ibrahim
# File : areas.py
# Date : July, 2019
#------------------------------------------------------------
import math
● 98
Chapter 6 • Python Programming
print("AREAS OF SHAPES")
print("===============\n")
print("What is the shape?: ")
shape = shape.lower()
if shape == 's':
a = float(raw_input("Enter a side of the square: "))
area = Square(a)
s = "Square"
elif shape == 'r':
a = float(raw_input("Enter one side of the rectangle: "))
b = float(raw_input("Enter other side of the rectangle: "))
area = Rectangle(a, b)
s = "Rectangle"
elif shape == 'c':
radius = float(raw_input("Enter radius of the circle: "))
area = Circle(radius)
s = "Circle"
elif shape == 't':
base = float(raw_input("Enter base of the triangle: "))
height = float(raw_input("Enter height of the triangle: "))
area = Triangle(base, height)
s = "Triangle"
elif shape == 'y':
radius = float(raw_input("Enter radius of cylinder: "))
height = float(raw_input("Enter height of cylinder: "))
area = Cylinder(radius, height)
s = "Cylinder"
● 99
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how to use the keyboard input, flow control
statements, and logarithms in a program.
For example, if the ratio of output/input voltage is 0.707, this corresponds to -3dB. Similar-
ly, a ratio of 0.5 corresponds to -6dB. To find the actual voltage ratio with a given dB, we
have to take the anti-logarithm as given by the following formula:
As an example, -10dB corresponds to the voltage ratio of Vo/Vin = Antilog10 (-0.5) = 0.316
There are many types of resistive attenuator circuits in use, but the commonly used ones
are the T and Pi type circuits, having 3 resistors each. Figure 6.55 shows the T type atten-
uator with two identical resistors R1 and a single resistor R2.
● 100
Chapter 6 • Python Programming
The design equations of this circuit are as follows (see web site: https://www.electronics-
tutorials.ws/attenuators/pi-pad-attenuator.html for more details). The source and the load
resistances are assumed to be equal in this design:
(6.3)
(6.4)
Where, Z is the source resistance, which is also equal to the load resistance, and K is known
as the attenuation factor, where:
K = Antilog10(dB/20) = 10dB/20
For example, for a 6dB attenuation, K will be 106/20 = 1.9953. Alternatively, if we want to
attenuate the input signal by a factor of 12, then the value of K will be 12.
Figure 6.56 shows the Pi type resistive attenuator again with two identical resistors R1 and
a single resistor R2.
The design equations of this circuit are as follows (see web site: https://www.electronics-
tutorials.ws/attenuators/pi-pad-attenuator.html for more details). The source and the load
resistances are assumed to be equal in this design:
(6.5)
(6.6)
Where, Z is the source resistance, which is also equal to the load resistance, and K is the
impedance factor as before.
● 101
Learning Python with Raspberry Pi
Program Listing: Figure 6.57 shows the program listing (program: attenuator.py). After
displaying a heading, the user is prompted to enter the source (which is also the load) re-
sistance Z, attenuation factor K in decibels, and the type of circuit to be used as T or P (for
Pi). The program calculates and displays the values of the resistors.
#----------------------------------------------------
# RESISTIVE ATTENUATOR DESIGN
# ===========================
#
# This program designs a T or Pi type resistive
# attenuator. The user enters the source (also load)
# resistance, atenuation factor and type of design
#
# Author: Dogan Ibrahim
# File : attenuator.py
# Date : July, 2019
#----------------------------------------------------
print("Resistive Attenuator Design")
print("===========================")
Z = float(raw_input("Enter source resistance in Ohms: "))
Kdb = float(raw_input("Enter attenuation Factor in dB: "))
T = raw_input("Enter attenuator type (T or P): ")
T = T.lower()
K = pow(10.0, Kdb/20.0)
if T == 't':
R1 = Z * (K - 1) / (K + 1)
R2 = R1
R3 = 2 * Z * K / (K * K - 1)
elif T == 'p':
R1 = Z * (K + 1) / (K - 1)
R3 = R1
R2 = Z * (K * K - 1) / (2 * K)
print("\nResults:")
print("-------")
print("Z = %f Ohms\nK = %f dB\nK (Vi/Vo) = %f\nR1=%f Ohms\nR2=%f Ohms\
\nR3=%f Ohms"
%(Z, Kdb, K, R1, R2, R3))
An example run of the program is shown in Figure 6.58. The design parameters are as
follows:
● 102
Chapter 6 • Python Programming
Aim: The aim of this case study is to show how to use the keyboard input, flow control
statements, and logarithms in a program.
Background Information: In an attenuator where the source and the load resistances
are not equal to each other different formula are used to calculate the resistance values. In
this section, we will only consider a Pi type network shown in Figure 6.60.
Figure 6.60 Pi type attenuator with different source and load resistances
● 103
Learning Python with Raspberry Pi
Program Listing: Figure 6.62 shows the program listing (program: attenuator2.py). After
displaying a heading, the user is prompted to enter the source and the load resistances ZS
and ZL, and the attenuation factor K in decibels. The program calculates and displays the
values of the resistors.
#----------------------------------------------------
# RESISTIVE Pi ATTENUATOR DESIGN
# ==============================
#
# This program designs a Pi type resistive attenuator
# where the source and the load resistances may be
# different to each other
#
# Author: Dogan Ibrahim
# File : attenuator2.py
# Date : July, 2019
#----------------------------------------------------
import math
● 104
Chapter 6 • Python Programming
print("\nResults:")
print("-------")
print("ZS = %f Ohms\nZL = %f Ohms\nK = %f dB\nK (Vi/Vo) = %f\nR1=%f Ohms\
nR2=%f Ohms\nR3=%f Ohms"%(ZS, ZL, Kdb, K, R1, R2, R3))
An example run of the program is shown in Figure 6.63. The design parameters are as
follows:
● 105
Learning Python with Raspberry Pi
6.31 Exceptions
It is possible that there are major errors in our programs, such as dividing by zero, file
privilege error, and so on. Normally, when Python encounters such errors it cannot handle
them and the program crashes.
One way to handle such errors orderly and avoid crashes is to use exception handling in our
programs. The basic method is that whenever an error occurs the program detects this er-
ror and takes appropriate measures to handle the error and continue to execute normally.
Exception handling is also useful if we wish to terminate a running program in an orderly
manner, for example, to shut down any input-output operations when the program is ter-
minated asynchronously by the user (e.g. by pressing the Cntrl+C key).
The statements try and except are used to handle unexpected error or terminations in our
programs. The general format of exception handling is as follows:
try:
Normal program statements
Normal program statements
except condition 1:
If condition 1 type error occurs then execute this block of code
……………..
……………..
except condition 2:
If condition 2 type error occurs then execute this block of code
……………….
……………….
else:
If there are no errors detected then execute this block of code
…………………
…………………
We can use the except statement with no condition in order to handle any type of excep-
tion. Some of the commonly used exceptions are:
● 106
Chapter 6 • Python Programming
exception KeyError: a dictionary key is not found in the set of existing keys
exception KeyboardInterrupt: u
ser hit the interrupt key (normally the Cntrl+C
or Delete key)
exception MemoryError: operation ran out of memory
exception RuntimeError: a
n error is detected that does not fall in any other
categories
exception ValueError: a
n operation or function receives an argument that has
the right type but an appropriate value
Example 1
Write a program to wait for an input from the keyboard. Terminate the program orderly
when the Cntrl+C keys are pressed on the keyboard.
Solution 1
Figure 6.66 shows the program listing (program: except1.py). Exception KeyboardIn-
terrupt is used in this program. Message End of Program is displayed when Cntrl+C key
combination is pressed on the keyboard.
#=====================================================
# KeyboardInteerupt EXCEPTION
#
# This program detects the keyboard entry Cntrl+C and
# the program is teminated orderly after the message
# End of Program is displayed
#
# Author : Dogan Ibrahim
# File : except1.py
# Date : July, 2019
#======================================================
try:
mode = raw_input("Enter Cntrl+C to terminate the program: ")
except KeyboardInterrupt:
print("\nEnd of Program")
● 107
Learning Python with Raspberry Pi
Example 2
Write a program to detect division by zero and to display the message Divide by Zero
when this exception is detected.
Solution 2
Figure 6.68 shows the program listing (program: except2.py). Here, the program is forced
to divide a number by zero and this is detected as an exception and the program displays
a message when this occurs.
#=====================================================
# ZeroDivisionError EXCEPTION
#
# This program detects when a number is divided by zero
# and generates an exception to display a message
##
# Author : Dogan Ibrahim
# File : except2.py
# Date : July, 2019
#======================================================
print("Divide by zero exception")
try:
s = 10 / 0
except ZeroDivisionError:
print("Divide by Zero")
● 108
Chapter 6 • Python Programming
Example 3
Write a program to look for KeyboardInterrupt exception and display the message Ex-
ception not occurred if an exception has not occurred.
Solution 3
Figure 6.69 shows the program listing (program: except3.py). The block inside finally is
executed regardless of whether an exception occurs.
#=====================================================
# try/finally In EXCEPTION
#
# This program detects the keyboard entry Cntrl+C and
# displays the message Keyboard Interrupt if interrupt
# occurs. Message Continue is displayed regardless of
# whether an exception occurrede
#
# Author : Dogan Ibrahim
# File : except3.py
# Date : July, 2019
#======================================================
try:
mode = raw_input("Enter Cntrl+C to terminate the program: ")
except KeyboardInterrupt:
print("\nKeyboard Interrupt")
finally:
print("\nContinue")
Aim: The aim of this case study is to show how to use the keyboard input, and flow control
statements.
● 109
Learning Python with Raspberry Pi
Background Information: Zener diodes are used in voltage regulator circuits. A zener
diode is like a general-purpose diode. When the diode is biased in the forward direction it
behaves just like a normal signal diode, but when biased in the reverse direction, the volt-
age remains constant for a wide range of currents. As a result of this characteristic, zener
diodes are used as fixed voltage sources in power supply applications. The typical forward
voltage of the diode at 1mA current is around 0.6 volts. As shown in Figure 6.71, in the
reverse direction a small leakage current flows. As the breakdown voltage is approached
the current begins to avalanche and the voltage across the zener diode becomes nearly
constant. There is a minimum current that puts the device into the breakdown region, and
a maximum current at which point the device can be damaged if the current is increased.
Zener diodes are available from about 2.4V to 200V and some popular ones have the fixed
voltages of 2.7V, 3.3V, 4.7V, 5.1V, 10V, 12V, 15V, etc.
Figure 6.72 shows a zener diode used as a voltage regulator. Input voltage is applied to
the cathode terminal of the diode through a resistor and the output voltage is taken across
the diode. Design of a zener diode regulator circuit depends on the correct choice of the
resistor.
The calculation of resistor Rs depends on the load current requirements and its minimum
value is given by:
● 110
Chapter 6 • Python Programming
Where Vin is the input voltage, Vz is the zener voltage, Izmin is the minimum zener current
(or zener test current in data sheets), and ILmax is the maximum load current. Before
choosing a zener diode for an application we have to make sure that the maximum power
capacity of the diode is not exceeded when there is no load. This is given by:
Pz = Vz x Is (6.8)
Where,
Program Listing: Figure 6.73 shows the program listing (program: zener.py). At the
beginning of the program a heading is displayed and the user is prompted to enter Vin,
Vz, Izmin, and ILmax. The required resistor value and the minimum power ratings of the
resistor and the zener diode are calculated and displayed.
#----------------------------------------------------
# ZENER DIODE VOLTAGE REGULATOR
# =============================
#
# This is a zener diode based voltage regulator design
# program which calculates the required resistance value
#
# Author: Dogan Ibrahim
# File : zener.py
# Date : July, 2019
#----------------------------------------------------
print("Zener Diode Voltage Regulator")
print("=============================")
Vin = float(raw_input("Enter Vin (Volts): "))
Vz = float(raw_input("Enter zener (load) voltage (Volts): "))
Izmin = float(raw_input("Enter minimum zener current (mA): "))
IzminA = Izmin / 1000.0
ILmax = float(raw_input("Enter maximum load current (mA): "))
ILmaxA = ILmax / 1000.0
#
# Now do the calculations
#
Rs = (Vin - Vz) / (IzminA + ILmaxA)
Is = (Vin - Vz) / Rs
● 111
Learning Python with Raspberry Pi
Pz = Vz * Is
Pz = Pz * 1000.0
Prs = (Vin - Vz) * Is
Prs = Prs * 1000.0
#
# Display the results
#
print("\nResults")
print("=======")
print("Vin=%3.2fV\nVz=%3.2fV\nIzmin=%3.2fmA\nILmax=%3.2fmA\nRs=%3.2f Ohms\
\nPrs=%3.2fmW\nPz=%3.2fmW" %(Vin, Vz, Izmin, ILmax, Rs, Prs, Pz))
Example run of the program is shown in Figure 6.74, which has the following specifications:
• Vin = 10V
• Vz = 5.1V
• Izmin = 5mA
• ILmax = 100mA
Figure 6.75 shows the designed zener diode circuit where the output voltage is 5.1V. The
required resistor value is calculated to be 46.67 Ohms. We should choose 47 ohms 1W as
the nearest physical resistor. The 5.1V zener diode should have around 1W power rating.
● 112
Chapter 6 • Python Programming
• time.localtime() returns the current date and time in the following format:
time.struct_time(tm_year=2013,tm_mon=12,tm_mday=18,
tm_hour=12,tm_min=45,tm_sec=3,tw_wday=2,tm_
yday=352,
• tm_isdst=0)
• time.asctime() returns the date and time in standard readable format
• time.clock() returns the current CPU time in seconds
• time.ctime() returns the current date and time
• time.time() returns the current time in seconds since the epoch
• time.sleep(x) suspends the calling program for x seconds
The datetime module can also be used for date and time functions. This module must be
imported in order to use these functions. Some examples of date functions are shown in
Figure 6.77.
Function strftime(format) is very useful as it can be used to format a date and time
string. Some examples of using this function are given in Figure 6.78.
● 113
Learning Python with Raspberry Pi
def hello():
print("Hello there!")
we can now import this module in our Python programs. An example program called
myprog.py is shown below:
import msg
msg.hello()
Running the program: python myprog.py will display the following output:
Hello there!
We can also modify our program myprog.py and import and then call the module as fol-
lows:
msg.py
def hello():
print("Hello there!")
name = "Jones"
myprog.py
import msg
msg.hello()
print(msg.name)
● 114
Chapter 6 • Python Programming
Hello there!
Jones
Aliases can be created for modules. This is shown in the following code:
myprog.py
import msg as tst
tst.hello()
Hello there!
Example 4
Write a module that calculates the cube of the integer number passed to it. Show how this
module can be imported and used in a program.
Solution 4
Figure 6.79 shows the module listing (program: cubeno.py). Function cube inside cubeno.
py has the number as its argument. The cube of this number is calculated and returned.
Figure 6.80 shows the program (program: myprog.py). As an example, when the number
is 3, the output from the program is:
Cube of 3 is: 27
def cube(N):
r = N * N * N
return r
import cubeno
n= 3
res = cubeno.cube(n)
print("Cube of %d is: %d" %(n,res))
Module Search Path: When a module is to be imported, Python looks at the following
folders in the order given:
● 115
Learning Python with Raspberry Pi
• The folder from which the module is called (where the calling main program is)
• The list of directories contained in the PYTHONPATH environment variable.
• Installation dependent list of directories configured when Python was installed
Python search path can be displayed by entering the following command interactively:
To make sure that your module is found by Python, you can do one of the following:
• Put the module program file in the folder where your main program is
• Modify PYTHONPATH environment variable to contain the folder where the
mo-dule program is
• Put the module program in one of the folders already contained in the
PYTHONPATH
6.35 Summary
In this chapter, we have learned how to use the basic functions of the Python programming
language. Many examples and case studies are given to help the user understand the var-
ious topics.
In the next chapter, we shall be looking at plotting graphs using Python. Examples of using
Python to design electronic circuits will be given in the form of case studies.
● 116
Chapter 7 • Plotting Graphs With Python
7.1 Overview
In the last chapter, we have learned the basic features of the Python programming lan-
guage and many examples and case studies are given.
In this chapter, we shall be looking at how to draw graphs using the Python programming
language. In addition, examples and case studies will be given on drawing graphs for elec-
tronic circuits.
We must import module matplotlib at the beginning of our programs before we can use
Matplotlib using the statement:
Perhaps the easiest way to learn how to use Matplotlib is to look at an example.
Notice that Matplotlib is supported by Python v3 and therefore if you are using the com-
mand line, the command to start your program should be:
Additionally, graphs can only be plotted in Desktop mode. If you are not using a directly
connected monitor then you should start the VNC server on your Raspberry Pi and then
start the VNCViewer on your PC to get into the Desktop mode.
Example 1
Write a program to draw a line graph passing from the following (x, y) points:
x: 2 4 6 8
y: 4 8 12 16
Solution 1
The required program listing is shown in Figure 7.1 (program: graph1.py). This program
is very simple. Function call plt.plot plots the graph with the specified x and y values. The
graph is shown on Desktop when statement plt.show() is executed. Start the program by
entering the following command in the Accessories-> Terminal windows at the Desktop:
● 117
Learning Python with Raspberry Pi
#----------------------------------------------
# SIMPLE LINE GRAPH
# =================
#
# This program draws a lien graph passing from
# the following points:
# x = 2 4 6 8
# y = 4 8 12 16
#
# Author: Dogan Ibrahim
# File : graph1.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
x = [2, 4, 6, 8]
y = [4, 8, 12, 16]
plt.plot(x, y)
plt.show()
Figure 7.2 shows the graph plotted by the program. Notice that at the bottom of the graph
we have several buttons to control the graph, such as zoom, save, etc.
● 118
Chapter 7 • Plotting Graphs With Python
We can add titles, axis labels, and grid to our graph using the following functions:
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Simple X-Y Graph")
plt.grid(True)
Example 2
Write a program to draw a sine curve from 0 to 2π.
● 119
Learning Python with Raspberry Pi
Solution 2
We have to use numpy arrays to store our data points before plotting. Figure 7.4 shows
the program listing (program: graph2.py).
#----------------------------------------------
# SINE GRAPH
# ==========
#
# This program draws a sine graph from 0 to 2pi
#
# Author: Dogan Ibrahim
# File : graph2.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
#
# Calculate the data points in np
#
x = np.arange(0, 2 * np.pi, 0.1)
y = np.sin(x)
#
# Now plot the graph
#
plt.plot(x, y)
plt.xlabel("X values")
plt.ylabel("Sin(X)")
plt.title("Sine Wave")
plt.grid(True)
plt.show()
● 120
Chapter 7 • Plotting Graphs With Python
Example 3
Draw the graph of the following function as x is varied from 0 to 4:
y = 2x2 + 3x + 2
Solution 3
Figure 7.6 shows the program listing (program: graph3.py). After calculating the x and y
values the graph is drawn as shown in Figure 7.7.
#----------------------------------------------
# Function Graph
# ==============
#
# This program draws a graph of the function:
# y = 2x2 + 3x + 2 from x=0 to x = 4
#
# Author: Dogan Ibrahim
# File : graph3.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
#
# Calculate the data points in np
#
x = np.arange(0, 4, 0.1)
y = [(2 * i * i + 3 * i + 2) for i in x]
● 121
Learning Python with Raspberry Pi
Example 4
This is an example of drawing two graphs on the same axes. Write a program to draw the
graphs of the following two functions as x is varied from 0 to 3:
y = x2 + 2
y = x2 + 4
Solution 4
Figure 7.8 shows the program listing (program: graph4.py). After calculating the x and y
values the graphs are drawn as shown in Figure 7.9.
#----------------------------------------------
# Function Graph
# ==============
#
# This program draws a graph of the functions:
# y = x2 + 2
# y = x2 + 4 from x=0 to x = 3
#
● 122
Chapter 7 • Plotting Graphs With Python
#
# Calculate the data points in np
#
x = np.arange(0, 3, 0.1)
y1 = [(i * i + 2) for i in x]
y2 = [(i * i + 4) for i in x]
#
# Now plot the graph
#
plt.plot(x, y1, linestyle='solid')
plt.plot(x, y2, linestyle='dashed')
plt.xlabel(“X values")
plt.ylabel(“Y values")
plt.title(“y=x2+2 and y=x2+4")
plt.grid(True)
plt.show()
In order to identify the individual graphs in a multi-graph drawing, we can plot each graph
with a different colour, or with different types of lines. Some examples are shown below:
● 123
Learning Python with Raspberry Pi
or
Figure 7.10 shows the graph in Figure 7.9 drawn with different line styles.
Example 5
In this example, we use legends to identify multiple graphs in a multi-graph drawing. The
functions to be drawn are same as the ones given in the previous example.
Solution 5
Figure 7.11 shows the program listing (program: graph5.py). Matplotlib functions label
is used to identify the two graphs. Also, statement plt.legend() must be specified to draw
the legend.
#----------------------------------------------
# Function Graph
# ==============
#
# This program draws a graph of the functions:
# y = x2 + 2
# y = x2 + 4 from x=0 to x = 3
#
# In this program the graphs are identified
#
# Author: Dogan Ibrahim
● 124
Chapter 7 • Plotting Graphs With Python
# File : graph5.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
#
# Calculate the data points in np
#
x = np.arange(0, 3, 0.1)
y1 = [(i * i + 2) for i in x]
y2 = [(i * i + 4) for i in x]
#
# Now plot the graph
#
plt.plot(x, y1, linestyle='solid', label='x2+2')
plt.plot(x, y2, linestyle='dashed', label='x2+4')
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("y=x2+2 and y=x2+4")
plt.grid(True)
plt.legend()
plt.show()
● 125
Learning Python with Raspberry Pi
Example 6
Write a program to draw a pie chart for the following data;
Solution 6
Figure 7.13 shows the program listing (program: graph6.py). The Pie chart is drawn with
equal aspect ratio so that is a circle.
#----------------------------------------------
# Pie Chart
# =========
#
# This program draws a pie chart for the data:
#
# France=15%, Germany=20%,Italy=20%,UK=45%
#
# Author: Dogan Ibrahim
# File : graph6.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
x, chrt = plt.subplots()
chrt.pie(sizes, labels=labels)
chrt.axis('equal')
plt.show()
● 126
Chapter 7 • Plotting Graphs With Python
We can explode parts of the Pie chart by specifying the parts to be exploded. For example,
to explode the fourth item in our example, we can issue the statement:
The amount of explosion is determined by the value we specify. Also, the percentages of
each part can be written inside the Pie chart elements by using the statement:
Parts of the Pie chart can be shadowed if desired to give it a 3D effect. This can be done
using the statement:
shadow=True
The program shown in Figure 7.15 (program: graph7.py) makes use of the above features
and the resulting Pie chart is shown in Figure 7.16.
#----------------------------------------------
# Pie Chart
# =========
#
# This program draws a pie chart for the data:
#
# France=15%, Germany=20%,Italy=20%,UK=45%
#
# Part UK is exploded in this graph.Also, the
# percentage of each part is written inside the
# corresponding parts and pats are shadowed
#
# Author: Dogan Ibrahim
● 127
Learning Python with Raspberry Pi
# File : graph7.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
x, chrt = plt.subplots()
chrt.pie(sizes, labels=labels, explode=explode,\
autopct='%1.1f%%',shadow=True)
chrt.axis('equal')
plt.show()
Example 7
Write a program to draw a bar chart for the following data:
Solution 7
Figure 7.17 shows the program listing (program: graph8.py). After specifying the values
for each bar, the bar chart is drawn.
● 128
Chapter 7 • Plotting Graphs With Python
#----------------------------------------------
# Bar Chart
# =========
#
# This program draws a bar chart for the data:
# France=10, Italy=8,Germany=6,UK=2
#
# Author: Dogan Ibrahim
# File : graph8.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
● 129
Learning Python with Raspberry Pi
We can plot a horizontal bar chart by replacing the statement plt.bar with plt.barh.
Aim: The aim of this case study is to show how to use the keyboard input, flow control
statements, and also how to draw graphs using the Python programming language.
Background Information: RC circuits are used in many radio and communications cir-
cuits. A typical RC transient circuit consists of a resistor in series with a capacitor as shown
in Figure 7.19. When the switch is closed, the voltage across the capacitor rises exponen-
tially with a time constant, T = RC.
Expressed mathematically, assuming that initially the capacitor is discharged, when the
switch is closed the voltage across the capacitor rises a given by the following formula:
(7.1)
Initially, the voltage across the capacitor is 0V, and in steady-state the voltage across the
capacitor becomes equal to Vin. The time constant is the time where the output voltage
rises to around 63.2% of its final value.
Program Listing: Figure 7.20 shows the program listing (program: RCrise.py). After
displaying heading, the values of the input voltage Vin, and resistor and capacitor values
are read from the keyboard. Notice that Python V3 does not support function raw_input,
instead in Python V3 we have to use just input for reading from the keyboard. The program
then calculates the time constant as T=RC and displays the time constant and also draws
the time response of the circuit. The graph is drawn as the time value (x-axis) changes
from 0 to 6T and 50 points are taken to draw the graph. The time constant is also written
on the graph at the point (Time constant, Vin / 2). The horizontal axis is in seconds, while
the vertical axis is in volts.
#----------------------------------------------
# RC TRANSIENT RESPONSE
# =====================
#
# This program reads the R and C values and then
# calculates and displays the time conctant. Also,
● 130
Chapter 7 • Plotting Graphs With Python
#
# Read Vin, R and C
#
Vin = float(input("Enter Vin in Volts: "))
R = float(input("Enter R in Ohms: "))
C = float(input("Enter C in microfarads: "))
C = C / 1000000.0
#
# Calculate and display time constant
#
T = R * C
F = 6.0 * T
N = F / 50.0
print("Time constant = %f seconds" %(T))
#
# Now plot the time response
#
x = np.arange(0, F, N)
y = [(Vin * (1.0 - math.exp(-i/T))) for i in x]
plt.plot(x, y)
plt.xlabel("Time (s)")
plt.ylabel("Capacitor Volts")
plt.title("RC Response")
plt.grid(True)
TC = "T="+str(T)+"s"
plt.text(T, Vin/2, TC)
plt.show()
● 131
Learning Python with Raspberry Pi
Figure 7.21 shows an example graph displayed by the program. In this program the follow-
ing input values were used (see Figure 7.22):
• Vin = 10 Volts
• R = 1000 Ohm
• C = 100 microfarad
Aim: The aim of this case study is to show how to use the keyboard input, flow control
statements, and also how to draw graphs using the Python programming language.
(7.2)
● 132
Chapter 7 • Plotting Graphs With Python
Where Vo is the initial voltage across the capacitor (normally the same as Vin) before s2 is
closed. Again, T=RC is known as the time constant of the circuit.
Program Listing: Figure 7.24 shows the program listing (program: RCfall.py). After dis-
playing heading, the values of the initial voltage across the capacitor (Vo), and the resistor
and capacitor are read from the keyboard. Notice that Python V3 does not support function
raw_input, instead in Python V3 we have to use just input for reading from the keyboard
The program then calculates the time constant as T=RC and displays the time constant and
also draws the time response of the circuit. The graph is drawn as the time value (x-axis)
changes from 0 to 6T and 50 points are taken to draw the graph. The time constant is also
written on the graph at the point (Time constant, Vo / 2). The horizontal axis is in seconds,
while the vertical axis is in volts.
#----------------------------------------------
# RC TRANSIENT RESPONSE
# =====================
#
# This program reads the R and C values and then
# calculates and displays the time constant. Also,
# the time response of the circuit is drawn as the
# capacitor is discharged
#
# Author: Dogan Ibrahim
# File : RCfall.py
# Date : July, 2019
#----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
import math
#
# Read Vo, R and C
#
Vo = float(input("Enter Initial Capacitor Voltage in Volts: "))
R = float(input("Enter R in Ohms: "))
C = float(input("Enter C in microfarads: "))
● 133
Learning Python with Raspberry Pi
C = C / 1000000.0
#
# Calculate and display time constant
#
T = R * C
F = 6.0 * T
N = F / 50.0
print("Time constant = %f seconds" %(T))
#
# Now plot the time response
#
x = np.arange(0, F, N)
y = [(Vo * (math.exp(-i/T))) for i in x]
plt.plot(x, y)
plt.xlabel("Time (s)")
plt.ylabel("Capacitor Volts")
plt.title("RC Response")
plt.grid(True)
TC = "T="+str(T)+"s"
plt.text(T, Vo/2, TC)
plt.show()
Figure 7.25 shows an example graph displayed by the program. In this program the follow-
ing input values were used (see Figure 7.26):
• Vin = 10 Volts
• R = 1000 Ohm
• C = 100 microfarad
● 134
Chapter 7 • Plotting Graphs With Python
(7.3)
Where Vin is in volts, R in Ohms, L in Henries, and t in seconds. The time constant of this
circuit is given by T = L/R.
After the current reaches its steady-state value, disconnecting the DC supply and shorting
the leads causes the current in the circuit to fall exponentially, given by the following for-
mula:
(7.4)
The transient response of RL circuits is similar to those of the RC circuits and therefore are
not covered further in this book.
● 135
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how to use the keyboard input, flow control
statements, and also how to draw graphs using the Python programming language.
Background Information: An RLC circuit (Figure 7.27) is a second-order system that can
have 3 modes of operation depending on the values of the components when a DC voltage
is applied across its terminals.
Underdamped mode: This mode is identified when the following condition holds true:
(7.5)
When DC voltage is applied to the circuit, the current in the circuit is given by the following
formula:
(7.6)
Where,
and, (7.7)
(7.8)
When DC voltage is applied to the circuit, the current in the circuit is given by the following
formula:
(7.9)
Where,
and, (7.10)
● 136
Chapter 7 • Plotting Graphs With Python
(7.11)
When DC voltage is applied to the circuit, the current in the circuit is given by the following
formula:
(7.12)
Where,
and, (7.13)
Program Listing: Figure 7.28 shows the program listing (program: RLC.py). At the be-
ginning of the program a heading is displayed and then the values of the input voltage,
resistor, capacitor and the inductor are read and stored in variables Vin, R, C, and L re-
spectively. The program then finds out in which mode the circuit will be operating based
on the value of ξ. Then, three functions are used, one for each mode, to calculate and plot
the transient response of the circuit. The mode of the circuit is displayed on the graph at
the coordinate (3T, 0), where T = 2π/W. In all the graphs, 80 points are used to draw the
points from 0 to 6T.
#------------------------------------------------
# RLC TRANSIENT RESPONSE
# ======================
#
# This program reads the R,L,C values and then
# calculates and displays the transient response
#
# Author: Dogan Ibrahim
# File : RLC.py
# Date : July, 2019
#------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
import math
global x, y, z
def critically_damped():
global x,y
x = np.arange(0, F, N)
y = [Vin*((1/L) * i * math.exp(-i*w)) for i in x]
def underdamped():
global x,y,z
● 137
Learning Python with Raspberry Pi
x = np.arange(0, F, N)
zeta = math.sqrt(1 - z*z)
y = [Vin*(1/(w*L*zeta)*(math.exp(-z*w*i))*math.sin(w*i*zeta)) for i in x]
def overdamped():
global x,y,z
x = np.arange(0, F, N)
y = [Vin*(1/(w*L*(math.sqrt(z*z-1))))*(math.exp(-z*w*i))*\
math.sinh(w*i*math.sqrt(z*z-1)) for i in x]
#
# Read Vin, R,C and L
#
Vin = float(input("Enter Vin in Volts: "))
R = float(input("Enter R in Ohms: "))
C = float(input("Enter C in microfarads: "))
C = C / 1000000.0
L = float(input("Enter L in millihenries: "))
L = L / 1000.0
w = math.sqrt(1/(L * C))
z = (R/2) * math.sqrt(C / L)
T = (2.0 * math.pi) / w
F = 6 * T
N = F / 80.0
#
# Find the mode of operation
#
mode = R - 2.0 * math.sqrt(L / C)
if abs(mode) < 0.01:
case = 2
md = "Critically Damped"
critically_damped()
elif mode < 0:
case = 1
md = "Underdamped"
underdamped()
elif mode > 0:
case = 3
md = "Overdamped"
overdamped()
● 138
Chapter 7 • Plotting Graphs With Python
#
# Now plot the time response
#
plt.plot(x, y)
plt.xlabel("Time (s)")
plt.ylabel("Current")
plt.title("RLC Response")
plt.grid(True)
plt.text(3*T,0, md)
plt.show()
Figure 7.29 shows a typical run of the program with the following values:
• Vin = 10 Volts
• R = 10 Ohms
• C = 100 microfarads
• L = 200 microhenries
7.7 Summary
In this chapter, we have learned how to draw line graphs, pie charts, and bar graphs using
the Python programming language. We have also learned how to plot the time response of
RC and RLC transient circuits. In the next chapter, we shall be looking at how data can be
saved in files on the Raspberry Pi micro SD card using the Python programming language.
● 139
Learning Python with Raspberry Pi
8.1 Overview
In the last chapter, we have learned how to draw graphs in Python, and also have learned
how to plot the transient responses of RC and RLC circuits. In this chapter, we will look
at the file operations in Python programming, especially using the Raspberry Pi. We will
learn how to create new files, read existing files, and carry out other file operations on the
Raspberry Pi micro SD.
A file in Python is opened using the keyword open. The general format of the open state-
ment is:
The filename is the name of the file that should be created (if new) or opened (if already
existing).
Access mode defines the type of operation to be performed on the file. Some commonly
used access modes are:
An opened file should be closed properly using the close() statement so that its contents
are not destroyed.
f = open("myfile.txt", "r")
● 140
Chapter 8 • Files in Python With the Raspberry Pi
The file is opened in the default working directory of the user, which is /home/pi on the
Raspberry Pi. The file should be closed using the statement:
f.close()
Data can be read and written to an opened file using the following statements:
• f.read() read contents of entire file. The number of bytes to read can be
specified with the statement f.read(n). For example, f.read(5)
will read 5 bytes from the file.
• f.readline() read a file line by line.
• F.readlines() read content of a file until end of file is reached
an example is shown below (characters enters by the user are in bold for clarity):
Some operating system based file operations are given below. Before using these opera-
tions, we must import the os module to our program:
Figure 8.1 shows a program code that creates a file called myfile.txt in the default di-
rectory and the following line of text written to the file. Command ls can be issued to see
that the file has actually been created. Entering command cat myfile.txt will display the
contents of the file:
● 141
Learning Python with Raspberry Pi
Some examples are given below to show how the various file operations can be used in
Python programs.
Example 1
Write a program to calculate the squares of numbers from 1 to 10 and store your results as
a table in a file called squares.txt.
Solution 1
The required program listing is shown in Figure 8.2 (program: flsqr.py). A for loop is used
to create the table. The file is opened in write mode and the table data is stored in the file.
#===================================================
# SQUARES OF NUMBERS
# ==================
#
# This program calculates the squares of numbers
# from 1 to 10 and saves them as a table in a file
# called squares.txt.
#
# Author: Dogan Ibrahim
# File: flsqr.py
# Date: July, 2019
#===================================================
f = open("squares.txt", "w")
f.write("Number Square\n")
f.close()
Figure 8.3 shows the file contents by issuing the cat command.
● 142
Chapter 8 • Files in Python With the Raspberry Pi
Example 2
Write a program to read the contents of the file created in Example 1 using the read()
statement and display the data on the screen.
Solution 2
The required program listing is shown in Figure 8.4 (program flrd1.py). File squares.txt is
opened in read mode. This program uses function read to read the entire contents of the
file which is then displayed on the screen.
#===================================================
# Read and Display Contents of a File
# ===================================
#
# This program reads teh contents of file squares.txt
# and displays its contents on teh screen
#
# Author: Dogan Ibrahim
# File: flrd1.py
# Date: July, 2019
#===================================================
f = open("squares.txt", "r")
contents = f.read()
print(contents)
f.close()
Example 3
Write a program to read contents of the file created in Example 1 line by line using the
readline() statement and display the data on the screen.
Solution 3
The required program listing is shown in Figure 8.5 (program: flrd2.py). File squares.txt
is opened in read mode. This program uses function readline() to read the file line by line.
Notice that a newline character is displayed at the end of each line so that there is a blank
● 143
Learning Python with Raspberry Pi
line between each line as shown in part in Figure 8.6. By adding statement strip() to the
print statement we can disable this extra new line .i.e. use print(line.strip()) instead of
print(line)
#===================================================
# Read and Display Contents of a File
# ===================================
#
# This program reads the contents of file squares.txt
# and displays its contents on the screen
#
# Author: Dogan Ibrahim
# File: flrd2.py
# Date: July, 2019
#===================================================
f = open("squares.txt", "r")
while True:
line = f.readline()
if not line:
break;
print(line.strip())
f.close()
Example 4
Write a program to read contents of the file created in Example 1 and store the data in a
list.
Solution 4
Figure 8.7 shows the program listing (program: flrd3.py). At the beginning of the program,
an empty list called MyList is created. File squares.txt is then opened in read mode. The
lines are read from the file and stored in MyList. Figure 8.8 shows the contents of MyList
after the program is run.
● 144
Chapter 8 • Files in Python With the Raspberry Pi
#===================================================
# Read Contents of a File and Store in a List
# ===========================================
#
# This program reads the contents of file squares.txt
# and stores the data in a list
#
# Author: Dogan Ibrahim
# File: flrd3.py
# Date: July, 2019
#===================================================
MyList = list()
with open("squares.txt", "r") as f:
for line in f:
MyList.append(line.strip())
print(MyList)
f.close()
Example 5
Write a program to read and display the contents of the file created in Example 1 using
function readlines().
Solution 5
Figure 8.9 shows the program listing (program: flrd4.py). Function readlines() is similar
to function read(), but it reads all the lines of a file into a list. The output from the program
is shown in Figure 8.10.
#===================================================
# Read Contents of a File and Store in a List
# ===========================================
#
# This program reads the contents of file squares.txt
# and stores the data in a list
#
# Author: Dogan Ibrahim
# File: flrd4.py
# Date: July, 2019
#==================================================
● 145
Learning Python with Raspberry Pi
print(MyList)
f.close()
(8.1)
(8.2)
(8.3)
● 146
Chapter 8 • Files in Python With the Raspberry Pi
In this case study, we will calculate the magnitude in decibels and the phase in degrees as
the frequency is changed from 0 to 150Hz in steps of 10Hz.
Program Listing: Figure 8.12 shows the program listing (program: freqrc.py). At the
beginning of the program, the values of R and C are read from the keyboard. The program
then calculates the magnitude in decibels and the phase angle in degrees as the frequency
is changed and saves the results in the file.
#===================================================
# Frequency Response of RC circuit
# ================================
#
# This program calculates teh frequency reponse of
# an RC circuit and saves teh frequecny-magnitude in
# a file called rcfreq.txt
#
# Author: Dogan Ibrahim
# File: freqrc.py
# Date: July, 2019
#===================================================
import math
#
# Now calculate and store the freq-magnitude in a file
#
f = open("rcfreq.txt", "w")
f.write("Frequency (Hz) Magnitude (dB) Phase (degrees)\n")
● 147
Learning Python with Raspberry Pi
d = w * C * R
denom = d * d + 1
M = math.sqrt(1 / denom)
M = 20 * math.log10(M)
phase = -math.degrees(math.atan(d))
f.write("%3d %10.4f %10.4f\n" %(freq, M, phase))
f.close()
Aim: The aim of this case study is to show how to measure the Raspberry Pi CPU temper-
ature and then save it in a file with time stamping.
To measure the temperature from Python we have to issue the following commands in a
Python V3 session (see also Appendix A.3):
>>> fl = open("/sys/class/thermal/thermal_zone0/temp")
● 148
Chapter 8 • Files in Python With the Raspberry Pi
>>> rd = float(fl.read())
>>> Temp = rd / 1000
>>> Print(temp)
40.894
>>> close(fl)
>>>
Program Listing: Figure 8.14 shows the Python V3 program listing (program: cputemp.
py). At the beginning of the program, the time module is imported to the program. The
program then opens a file called cputemp.txt in write mode. A loop is formed where the
CPU temperature is measured every 10 seconds and is saved in the file with current time
stamping. The number of records saved is displayed every 10 seconds. The program is
terminated orderly and the file is closed when the user enters Cntrl+C at the keyboard.
#-------------------------------------------------------
# SAVE THE RASPBERRY PI 4 CPU TEMPERATURE IN A FILE
# =================================================
#
# This program measures and saves the CPU temperature
# of teh Raspberry Pi 4 every 10 seconds and the saves
# in a file called cputemp.txt
#
# Author: Dogan Ibrahim
# File : cputemp.py.py
# Date : July, 2019
#-------------------------------------------------------
import time
#
#Read the CPU temperature
#
try:
while True:
fl = open("/sys/class/thermal/thermal_zone0/temp")
rd = fl.read()
temp = (float)(rd) / 1000
tim = time.ctime()
MyFile.write("%s %5.2f C\n" %(tim, temp))
count = count + 1
print("Saved %d records" %(count))
fl.close()
time.sleep(10)
● 149
Learning Python with Raspberry Pi
except KeyboardInterrupt:
print("End of saving the temperature\n")
MyFile.close()
Figure 8.15 shows a typical run and the output from the program.
Plug-in your USB memory stick to one of the Raspberry Pi USB ports
pi@raspberrypi:~ $ ls –l /dev/disk/by-label
You should see a display similar to the one shown in Figure 8.16. Notice that in this display
sda1 with the label name DOGANS is our memory stick
● 150
Chapter 8 • Files in Python With the Raspberry Pi
We now have to create a Mount Point, which is a directory that will point to our memory
stick. Enter the following command:
Now we have to mount the drive. Enter the following command to mount the drive:
To display the contents of the memory stick, enter the following command:
pi@raspberrypi:~ $ ls –l /media/usb
when you restart your Raspberry Pi your drive mount will be lost and you will have to mount
again using the above instructions. You can make your memory stick to be mounted auto-
matically after system re-start. The steps or this are as follows:
Enter the following command and note the uuid number of your memory stick (see Figure
8.17). In this example, the uuid number was: 4083-7126
pi@raspberrypi:~ $ ls –l /dev/disk/by-uuid
● 151
Learning Python with Raspberry Pi
After restarting your Raspberry Pi, the memory stick will be mounted automatically. Enter
the following command to make sure that the files on your memory stick will be displayed:
pi@raspberrypi:~ $ ls –l /media/usb
Note: You can unmount the drive after re-start, or remove the drive from file /etc/fstab
if it is not required anymore.
Aim: The aim of this case study is to show how to save data on an USB memory stick with
time stamping.
Program Listing: Before writing the program it is assumed that the memory stick is al-
ready mounted either manually or automatically after system re-start on your Raspberry
Pi. Figure 8.18 shows the program listing (program: usbwrite.py). You should run this
program with Python V3:
#-------------------------------------------------------
# SAVE THE RASPBERRY PI 4 CPU TEMPERATURE IN A FILE
# =================================================
#
# This program measures and saves the CPU temperature
# of the Raspberry Pi 4 every 10 seconds and the saves
# in a file called usbcputemp.txt on an USB memory stickt
● 152
Chapter 8 • Files in Python With the Raspberry Pi
#
# Author: Dogan Ibrahim
# File : usbwrite.py
# Date : July, 2019
#-------------------------------------------------------
import time
#
#Read the CPU temperature
#
try:
while True:
fl = open("/sys/class/thermal/thermal_zone0/temp")
rd = fl.read()
temp = (float)(rd) / 1000
tim = time.ctime()
MyFile.write("%s %5.2f C\n" %(tim, temp))
count = count + 1
print("Saved %d records" %(count))
fl.close()
time.sleep(10)
except KeyboardInterrupt:
print("End of saving the temperature on the memory stick\n")
MyFile.close()
Notice that the memory stick is identified by folder name: /media/usb/. Figure 8.19
shows running and displaying the contents of file cputemp.txt on the memory stick.
Figure 8.19 Running and displaying the file on the USB memory stick
● 153
Learning Python with Raspberry Pi
8.7 Summary
In this chapter, we have learned how to create files either on the micro SD card or on an
external USB memory stick, and how to write and read from the files on these media.
In the next chapter, we shall be looking at matrices and see how matrices can be created,
inverted etc. Additionally, we shall be learning how to use matrices to carry out mesh and
nodal analysis of electrical circuits.
● 154
Chapter 9 • Array and Matrix Operations With Python
9.1 Overview
In the last chapter, we have learned how to store data in files, both on the micro SD card
and on an external USB memory stick. In this chapter, we shall be looking at the arrays and
matrices and learn how we can use matrices in solving mesh and nodal electrical circuits in
order to calculate the current and voltage in the circuit.
9.2 Arrays
Arrays can be created using the numpy module. The following example shows how a 2 x
2 array can be created:
Array elements can be accessed by specifying the row and column numbers. The element
at the top left-hand side is (0 , 0). Some examples are given below:
>>> print(x[0,1])
4.0
>>>
To change a row:
To change an element:
>>> x[0, 1] = 5
>>> print(x)
[[12.2 5. ]
[-3 5.2]]
>>>
We can specify all the elements of an array as floating point by specifying dtype=float as
shown below:
● 155
Learning Python with Raspberry Pi
A unit matrix can be created using function identity and specifying the order of the matrix.
In the following example a 3 x 3 unit matrix called A is created:
>>> A = identity(3)
>>> print(A)
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
>>>
● 156
Chapter 9 • Array and Matrix Operations With Python
Before analysing electrical circuits, we shall be looking at the solution of systems of linear
algebraic equations using the Python programming language.
We can express the above general system of equations as a matrix operation as follows:
(9.1)
● 157
Learning Python with Raspberry Pi
or as,
Ax = b 9.2)
where,
A = (9.3)
x = (9.4)
b = (9.5)
A-1Ax = A-1b
or,
x = A-1b (9.6)
Therefore, we can find the solution by taking the inverse of A and multiplying with b. Func-
tion inv returns the inverse of a matrix. Some examples are given below.
Example 1
2x + 3y = 11
4x + y = 7
Solution 1
Here, A =
x =
b =
● 158
Chapter 9 • Array and Matrix Operations With Python
The solution is shown in Figure 9.4 where the result is given as x = 1, y = 3. Notice that
module inv must be imported from numpy.linalg.
Python also supports the function solve for solving a system of linear equations without
having to use equation (9.6). An example is given below.
Example 2
Solve the following system of linear equations:
2x + y + 2z = 10
x + y + z = 6
x + 2y + 3z = 14
Solution 2
Here, A =
x =
b =
The solution is shown in Figure 9.5 where function solve is used. Notice that module solve
must be imported from numpy.linalg. In this example, the solution is found to be x =1,
y = 2, z = 3
Example 3
Solve the following system of linear equations:
2x + y + 2z = 18.3
2.5x + y + z = 11.35
x + 2y + 2z = 12.7
● 159
Learning Python with Raspberry Pi
Solution 3
Here, A =
x =
b =
The solution is shown in Figure 9.6 where function solve is used. In this example, the solu-
tion is found to be x =2.5, y = -3.1, z = 8.2
Aim: The aim of this case study is to show how to read data from the keyboard in the form
of a matrix, and how to calculate the current and voltages in a DC circuit consisting of re-
sistors and batteries.
In this case study, the circuit shown in Figure 9.7 is used as an example. This circuit con-
sists of 3 resistors: 10 Ohms, 20 Ohms, and 40 Ohms, and two voltage sources (batteries):
10 Volts and 20 Volts.
● 160
Chapter 9 • Array and Matrix Operations With Python
From an inspection of the circuit, we can write the elements of matrices A, b and x for this
circuit are as follows:
Here, A =
x =
b =
Just as a reminder, assuming that the currents in each loop are taken in the same direction
(e.g. clockwise):
Program Listing: Figure 9.8 shows the program listing (program: mesh.py). At the be-
ginning of the program a heading is displayed. Arrays A and b are cleared (filled with ze-
roes). The program then reads the number of rows of the A matrix, which is also equal to
the number of columns. Then the elements of A and b matrices are read and the currents
are calculated and displayed. As shown in Figure 9.9, the currents in the two loops are:
I1 = -0.143A and I2 = -0.429A. We can then calculate the voltage across each resistor as
follows:
#====================================================
# CIRCUIT MESH ANALYSIS
# =====================
#
# This program carries out mesh analysis of a circuit.
# The user enters the circuit elements in the form of
# A and b matrices and the program calculates and
● 161
Learning Python with Raspberry Pi
#
# Read the matrix A elements
#
for i in range(0, rows):
for j in range(0, cols):
A[i, j] = float(raw_input("Enter A%d%d:" %(i+1, j+1)))
#
# Read the matrix b elements
#
print("")
for i in range(0, rows):
b[i] = float(raw_input("Enter b%d:" %(i+1)))
#
# Calculate and display the currents in the circuit
#
x = solve(A, b)
print("\nResults:")
for i in range(0, rows):
print("I%d = %7.3fA" %(i+1, x[i]))
● 162
Chapter 9 • Array and Matrix Operations With Python
Aim: The aim of this case study is to show how a more complex circuit can be analysed
using the program developed in the previous case study.
The circuit used in this case study is shown in Figure 9.10, which consists of 8 resistors and
4 voltage sources (batteries) in 3 loops.
Figure 9.11 shows the currents in each loop calculated using program mesh.py developed
in the previous case study. In this example, the loop currents are: I1 = 4.569A, I2 =
13.708A, I3 = 1.054A
● 163
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how a more complex circuit can be analysed
using the program developed in the previous case study.
The circuit used in this case study is shown in Figure 9.12, which consists of 4 resistors a
voltage source and a current source.
The circuit shown in Figure 9.12 can be converted into its equivalent circuit by replacing the
current source with a voltage source as shown in Figure 9.13.
The circuit now consists of 2 loops with 333 resistors. Using the mesh analysis program
as shown in Figure 9.14, the current in the circuit are calculated to be: I1 = 0.182A, I2 =
-0.182A.
● 164
Chapter 9 • Array and Matrix Operations With Python
Aim: The aim of this case study is to show how to do node analysis of a circuit using Py-
thon.
Background Information: Node analysis is similar to mesh analysis but here we have
to enter the circuit elements at the nodes of the circuit. If there are n nodes in a circuit
then there will be n-1 independent equations where one node is taken to be the reference
node. Then the matrix equation Ax = b is formed where A represents the circuit elements
in terms of conductances (inverse or resistance), x represents the voltages at each node
in the circuit, and b represents the current sources. The matrix equation is then solved as
shown in the examples earlier in this chapter. After calculating the voltages in the circuit,
we can easily calculate the current through every resistor.
In this case study, the circuit shown in Figure 9.15 is used as an example. This circuit con-
sists of 4 resistors and 2 current sources, and has 3 nodes.
From an inspection of the circuit, we can write the elements of matrices A, b and x for this
circuit are as follows:
● 165
Learning Python with Raspberry Pi
Here, A =
x =
b =
To make the calculation simpler, we will be entering the resistances to the program and the
program will convert them into conductances for its internal calculations.
Program Listing: Figure 9.16 shows the program listing (program: node.py). At the be-
ginning of the program a heading is displayed and the user is asked to enter the number
of nodes there are in the circuit (excluding the reference node). The elements at each node
are then entered for the A matrix in terms of the resistances at each node. A 0 must be
entered to terminate the entry for a node. The program internally converts the en-
tered values into conductances by taking their inverses. This makes it easier to enter the
element values. The currents at each node are then entered for the b matrix. The program
calculates and displays the voltages at the nodes. After calculating the voltages, we can
easily calculate the current through each resistor by dividing the voltage across it by its
resistance.
#====================================================
# CIRCUIT NODE ANALYSIS
# =====================
#
# This program carries out node analysis of a circuit.
# The user enters the circuit elements in the form of
# A and b matrices and the program calculates and
# displays the values of the voltages in the circuit
#
# Author: Dogan Ibrahim
# File : node.py
# Date : July 2019
#======================================================
from numpy import array
from numpy import *
from numpy.linalg import solve
● 166
Chapter 9 • Array and Matrix Operations With Python
A = zeros((rows, cols))
b = zeros(rows)
#
# Read the matrix A elements
#
total = 0
elements = 1
for i in range(0, rows):
for j in range(0, cols):
while True:
elements = float(raw_input("Enter A%d%d:" %(i+1, j+1)))
if elements == 0:
break
total = total + (1 / elements)
A[i, j] = total
total = 0
print("")
#
# Read the matrix b elements
#
print("")
for i in range(0, rows):
b[i] = float(raw_input("Enter b%d:" %(i+1)))
#
# Calculate and display the currents in the circuit
#
x = solve(A, b)
print("\nResults:")
for i in range(0, rows):
print("V%d = %7.3fV" %(i+1, x[i]))
Figure 9.17 shows the output when the program is run for this example. The voltages at
each node are calculated to be: V1 = 404.286V, V2 = 350.000V, V3 = 412.875V.
● 167
Learning Python with Raspberry Pi
9.8 Summary
In this chapter, we have learned how to create arrays and matrices and how to use them in
mesh and node circuit analysis. Several examples and case studies are given to show how
circuits can be analysed using the arrays and matrices in Python programming language. In
the next chapter, we shall be learning how to use GUI (Graphical User Interface) in Python
programs and then learn how to develop GUI based programs for analysing RLC resonant
circuits and also how to calculate the inductance of single-layer air-core coils.
● 168
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
10.1 Overview
In the last chapter, we have learned how to use arrays and matrices to carry out mesh and
node analysis for electrical circuits.
In this chapter, we shall be learning how to use the Tkinter graphical user interface soft-
ware in Python programs. After making an introduction to Tkinter and learning how to use
its basic features, we shall be analysing and designing a transistor circuit with the help of
GUI interfaces.
Tkinter consists of a number of widgets used to build GUI applications. Some of the com-
monly used widgets are further information on widgets can be obtained from the link:
https://docs.python.org/3/):
• pack() organize the widgets such that they occupy the entire available
width
• grid() organize the widgets in table-like structure
• place() place the widgets at desired positions
● 169
Learning Python with Raspberry Pi
10.2.1 Label
Example 1
Create a Label and display the message Hello From Tkinter… with this label.
Solution1
Figure 10.1 shows the required program listing (program: gui1.py). At the beginning of
the program, module tkinter is imported into the program. A window is created with the
title MY FIRST TKINTER EXAMPLE. Then the font size is changed and a Label is created
to display message Hello From Tkinter…
#====================================================
# DISPLAY TEXT USING A LABEL
# ==========================
#
# This rogram displays text "Hello From Tkinter..."
# using a Label.
#
# Author: Dogan Ibrahim
# File : gui1.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
window.mainloop()
You should run your program from the Desktop if a monitor is connected directly to your
Raspberry Pi. Alternatively, start the VNC server on your Raspberry Pi and create a Desktop
using the VNC Viewer:
pi@raspberrypi:~ $ vncserver :1
● 170
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Once in the Desktop mode, open a terminal session (Accessories -> Terminal) and enter
the following command to run your program:
Figure 10.2 shows the message displayed on the Desktop. Clicking the up expand button
expands the window to its full size as shown in Figure 10.3.
We can insert the following statement after the window title in order to increase the initial
size of the window. The corresponding display is shown in Figure 10.4:
window.geometry("400x400")
● 171
Learning Python with Raspberry Pi
When widgets are packed, we can specify whether it should expand to take up all the avail-
able space. By default, widgets are not expanded. We can specify the following keywords
with the pack() function:
• side="position" to specify the position, where it can take the values: top, bot-
tom, left, right
• expand="yes" expands to the allocated space
• fill="stretch" can be used to stretch the widget, where it can take the values: x
(horizontal stretching), y (vertical stretching) or both (stretch in both directions)
• Setting expand="yes" and fill="both" will place the widget in the center of the
window.
For example, displaying 3 labels with different sizes with the default pack() will see that
each label is given the size of the text it displays:
BxxxxxxxE
BxxxxxxxxxxxE
BxxxxE
Where B and E are the beginnings and endings of the labels respectively. If now we use the
pack(fill="x") option, the labels will be horizontally stretched so that all three labels have
the same width (the texts are not the same width):
B xxxxxxx E
BxxxxxxxxxxxE
B xxxx E
We can use internal or external Paddings to adjust the placement of widgets. padx and
pady add external horizontal padding to a widget respectively, and ipadx and ipady add
horizontal and vertical internal padding (padding added to the inside of the widget borders)
to a widget respectively. By default, no padding is added to a widget.
● 172
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
10.2.2 Button
Example 2
Create a Label and a Button such that the Button has the title Click Me. When the button
is clicked the message You Clicked Me should be displayed by the Label.
Solution 2
Figure 10.5 shows the program listing (program: gui2.py). Inside the main program, the
window title and size are specified. Then a Button widget is declared with the title Click
Me. When the button is clicked, function disp is called which displays the message You
Clicked Me.
#====================================================
# LABEL AND BUTTON EXAMPLE
# ========================
#
# This rogram displays text “You Clicked Me" when the
# button is clicked
#
# Author: Dogan Ibrahim
# File : gui2.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
def disp():
LabelWidget = Label(window, text = “You Clicked Me")
LabelWidget.config(font=labelfont)
LabelWidget.pack(side="top")
window.mainloop()
● 173
Learning Python with Raspberry Pi
Figure 10.6 and Figure 10.7 show the display before and after clicking the button.
Example 3
Show the differences between using different parameters of function pack().
Solution
Figure 10.8 to Figure 10.10 show various displays with different parameters of function
pack().
● 174
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Example 4
Write a program that uses a Label and two Buttons. Pressing one of the buttons should
display message Button 1 Pressed, and pressing the other button should terminate the
program.
Solution 4
Figure 10.11 shows the program listing (program: gui3.py). The output of this program is
shown in Figure 10.12.
#==========================================================
# LABEL AND TWO BUTTONS
# =====================
#
# This rogram displays text “Button1 Pressed" when one
# button is clicked,and terminates when other one is pressed
#
● 175
Learning Python with Raspberry Pi
window = Tk()
def disp():
LabelWidget = Label(window, text = “Button 1 Pressed")
LabelWidget.config(font=labelfont)
LabelWidget.pack()
window.mainloop()
Figure 10.13 shows another example (program: gui4.py) with a label and two buttons. The
output of this program is shown in Figure 10.14.
#====================================================
# LABEL AND TWO BUTTONS
# =====================
#
# Label and 2 Buttons.
#
# Author: Dogan Ibrahim
● 176
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
# File : gui4.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
window.title("EXAMPLE")
window.geometry("300x300")
Button1 = Button(window, text = "Hello").pack(side="left",fill="y")
Label1=Label(window,text="This is Top").pack(side="top")
Button2=Button(window,text="Here").pack(side="right",expand="yes",fill="x")
window.mainloop()
The anchor option of function pack() can be used to position a widget. Eight points of a
compass (E, W, N, S, NE, NW, SE, SW) and CENTER are supported.
The foreground colour, background colour, the height and width of a widget can be con-
trolled as shown in Figure 10.15 (program: gui5.py). The output of this program is shown
in Figure 10.16.
#============================================
# USING COLOURS
# =============
#
# Using foreground and background colours and
● 177
Learning Python with Raspberry Pi
window = Tk()
window.title("EXAMPLE")
labelfont=('times', 18, 'bold')
L1=Label(window,text="Hello Tkinter")
L1.config(bg='black', fg='white')
L1.config(font=labelfont)
L1.config(height=4, width=20)
L1.pack(expand="yes", fill="both")
window.mainloop()
10.2.3 Message
Example 5
Write a program to use the message widget to display the message This is a message
from Tkinter.
Solution 5
Figure 10.17 shows the program listing (program: gui6.py). The output of the program is
shown in Figure 10.18.
#=================================================
# MESSAGE WIDGET
# ==============
#
# This program displays the message: This is a message
● 178
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
# from Tkinter
#
# Author: Dogan Ibrahim
# File : gui6.py
# Date : July 2019
#=================================================
from tkinter import *
window = Tk()
window.title(“EXAMPLE")
msg = Message(window,text="This is a message from Tkinter")
msg.config(fg='blue',bg='white',font=('times',18,'italic'))
msg.pack(fill="x", expand="yes")
window.mainloop()
10.2.4 Entry
Example 6
This example shows how to use the Entry widget. This widget is a single-line text input
field used to get text from the user. In this example, the user enters a text and this text is
displayed on the screen.
Solution 6
Figure 10.19 shows the program listing (program: gui7.py). The insert method of Entry
has two parameters. The first parameter is the position where the text should be inserted
and 0 is the first position at the left. The next parameter is a string that is optional where
this string is displayed when function insert is called. In the program in Figure 10.19. A
Button entitled Get is created and when this button is pressed the user entered text is dis-
played on the screen. Figure 10.20 shows an output from the program.
● 179
Learning Python with Raspberry Pi
#=================================================
# Entry WIDGET
# ============
#
# This program reads user's text and displays it
#
# Author: Dogan Ibrahim
# File : gui7.py
# Date : July 2019
#=================================================
from tkinter import *
window = Tk()
def get():
value=ent.get()
print("%s" %value)
ent = Entry(window)
ent.insert(0, '')
ent.pack(side="top", fill="x")
ent.focus()
butn = Button(window, text="Get", command=get)
butn.pack(side="left")
window.mainloop()
10.2.5 Grid
So far we have aligned our widgets using the options of function pack(). Grids are very
useful when we want to line up widgets horizontally. Grids allow tabular displays where we
can arrange the row and column positions of widgets in a grid fashion. In general, input
forms (e.g. Entry) are best arranged using grids. Grid row and column co-ordinates start
from 0. An example uses of grids are shown below.
Example 7
Write a program to display the names of 6 countries on 6 buttons using grids.
● 180
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Solution 7
Figure 10.21 shows the program listing (program: gui8.py). Notice how the row and
column numbers are used to position the buttons on the screen. Figure 10.22 shows the
output of the program.
#=================================================
# Using Grids
# ===========
#
# In this example the names of 6 counries are displayed
#
# Author: Dogan Ibrahim
# File : gui8.py
# Date : July 2019
#=================================================
from tkinter import *
window = Tk()
countries = ['UK','Germany','France','Italy','Belgium','Ireland']
r = 0
for country in countries:
Button(window, text = country, width = 50).grid(row = r, column = 0)
r = r + 1
window.mainloop()
● 181
Learning Python with Raspberry Pi
Example 8
Write a program to display a country and 6 possible options where only one of the options is
the capital city of the country. Choose the country as France and the possible capital cities
as: London, Rome, Paris, Ankara, Istanbul, and Madrid.
Solution 8
Figure 10.23 shows the program listing (program: gui9.py). 6 Radio buttons are used to
display the 6 cities. Clicking on a city enables its Radio button as shown in Figure 10.24.
#====================================================
# Using Radio Buttons
# ===================
#
# In this example a country and 6 cities are displayed
# and the user is asked to click the capital city of
# the displayed country.
#
# Author: Dogan Ibrahim
# File : gui9.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
capcity = 0
window.geometry("400x150")
window.mainloop()
● 182
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Example 9
Modify the program in Figure 10.23 so that the user is given a message based on the
selected country. For example, you may display Correct when the correct capital city is
selected, or Not Correct when a wrong selection is made.
Solution 9
Figure 10.25 shows the modified program (program: gui10.py). Every capital city is given
a value from 1 to 6. A Button is created with the title Select one. Also, grids are used to
display all the widgets in the program. When the button is clicked, function choice is acti-
vated. Inside this function the program checks the value of user's choice. Variable capcity.
get() returns an integer variable between 1 and 6 corresponding to the values of the 6
cities displayed by the Radio buttons. If the user selects the correct answer (Paris in this
example, which has the value 3) then a Label displays the message Correct, otherwise
message Not Correct is displayed at the specified row and column co-ordinates. Figure
10.26 shows a typical run of the program where the incorrect and then the correct answer
is chosen.
#====================================================
# Using Radio Buttons
# ===================
#
# In this example a country and 6 cities are displayed
# and the user is asked to click the capital city of
# the displayed country. Messages are displayed to let
# the user know if the chosen city is correct or not
#
# Author: Dogan Ibrahim
# File : gui10.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
window.title("Capital Cities")
def choice():
if capcity.get() == 3:
● 183
Learning Python with Raspberry Pi
capcity = IntVar()
value = 0
window.mainloop()
The program given in Figure 10.25 can be made more efficient and more user-friendly by
storing the cities in a list and using a for loop to display the Radio buttons as shown in
Figure 10.27 (program: gui11.py).
#====================================================
# Using Radio Buttons
# ===================
#
# In this example a country and 6 cities are displayed
● 184
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
window = Tk()
window.title("Capital Cities")
cities = ["London","Rome ","Paris ","Ankara ","Istanbul","Madrid "]
def choice():
if capcity.get() == 2:
Label(window, text=" Correct").grid(row=1, column=5)
else:
Label(window, text="Not Correct").grid(row=1, column=5)
capcity = IntVar()
value = 0
window.mainloop()
10.2.7 Checkbox
Checkboxes are also known as tickboxes and they allow users to make multiple selections
from a number of different options. Checkboxes are shown as small square boxes on the
screen. A checkbox can either be in the state of off or on. An example is given below to
illustrate how a checkbox can be used in a Python program.
● 185
Learning Python with Raspberry Pi
Example 10
Write a program to use checkboxes. A button should be used with the title: Select the
programming languages you know. The user will be given the following choices: Pascal,
Basic, C. The program displays the selected options. Use a button with the title Quit to
terminate the program.
Solution 10
Figure 10.28 shows the program listing (program: gui12.py). The user makes a selection
by clicking all the boxes that are relevant. When the selection button is clicked, function
choice is called. This function displays the choices made by the user as shown in the exam-
ple display in Figure 10.29.
#====================================================
# Using Checkbuttons
# ===================
#
# In this example the user selects the programming
# languages that he/she knows
#
# Author: Dogan Ibrahim
# File : gui12.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
window.title("Programming Languages")
languages = ["Pascal","Basic","C"]
def choice():
if Var1.get() == 1:
Label(window, text="Pascal").grid(row=1, column=5)
if Var2.get() == 1:
Label(window, text="Basic").grid(row=2,column=5)
if Var3.get() == 1:
Label(window, text="C").grid(row=3,column=5)
Var1 = IntVar()
● 186
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Var2 = IntVar()
Var3 = IntVar()
Checkbutton(window,text=languages[0],variable = Var1).grid(row=1,sticky="w")
Checkbutton(window,text=languages[1],variable = Var2).grid(row=2,sticky="w")
Checkbutton(window,text=languages[2],variable = Var3).grid(row=3,sticky="w")
window.mainloop()
• askquestion
• askokcancel
• askretrycancel
• askyesno
• askyesnocancel
• showerror
• showinfo
• showwarning
Example 11
Write a program to show the output when some of the above dialogs are used.
Solution 11
Figure 10.30 shows the program listing (program: gui13.py). Four buttons are used in
this program. Pressing the buttons displays 4 different types of dialogs as shown in Figure
10.31.
● 187
Learning Python with Raspberry Pi
#====================================================
# Using Dialogs
# =============
#
# In this example two dialog type displays are shown
#
# Author: Dogan Ibrahim
# File : gui13.py
# Date : July 2019
#====================================================
from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("Dialogs")
def error():
messagebox.showerror("","You clicked error")
def okcancel():
messagebox.askokcancel("","You clicked OK or CANCEL")
def yesno():
messagebox.askyesno("","You clicked YES-NO")
def warning():
messagebox.showwarning("","You clicked WARNING")
window.mainloop()
● 188
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Example 12
Write a program using a tkinter dialog to display the files in the default directory /home/pi
Solution 12
Figure 10.32 shows the program listing (program: gui14.py). The output of the program
is shown in Figure 10.33.
#====================================================
# Using Dialogs
# =============
#
# In this example the default folder is listed with all
# the files and the user is asked to select a file
#
# Author: Dogan Ibrahim
# File : gui14.py
# Date : July 2019
#====================================================
from tkinter import *
from tkinter import filedialog
window = Tk()
filedialog.askopenfilename(initialdir="/home/pi",title="Select a file")
window.mainloop()
● 189
Learning Python with Raspberry Pi
The file option of the dialog widget supports the following additional file operations:
Example 13
In this example, a vertical scale is drawn and its current numeric value is displayed on the
screen.
Solution 13
Figure 10.34 shows the program listing (program: gui15.py). The range of the scale is set
using the from_= and to= statements. The numeric value of the scale is obtained using
the statement S1.get(). Figure 10.35 shows the output of the program when the scale
was set to 15.
#====================================================
# Using Scales (Slides)
# =====================
#
# This example displays the scale's numeric value on
# the screen
#
# Author: Dogan Ibrahim
# File : gui15.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
def get():
print(S1.get())
window.mainloop()
● 190
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
Example 14
By default, scales start from 0 when they start. We can, however use the statement set(n)
to set the initial value of the scale to n. In this example, we will be drawing a horizontal
scale that goes from 0 to 50 and starting at 25.
Solution 14
Figure 10.36 shows the program listing (program: gui16.py). The output of the program
is shown in Figure 10.37.
#====================================================
# Using Scales (Slides)
# =====================
#
# This example displays a horizontal scale that goes
# from 0 to 50 with 25 as the starting value
#
# Author: Dogan Ibrahim
# File : gui16.py
# Date : July 2019
#====================================================
from tkinter import *
window = Tk()
def get():
print(S1.get())
window.mainloop()
Figure 10.36 Program listing
● 191
Learning Python with Raspberry Pi
10.2.10 Menu
Menus are useful tools for users to make a choice from a number of options. We can see
menus in almost all applications. For example, Windows Word has a number of menu op-
tions at the top of the screen, such as under File we have the menu options of New Open
Save Save As Print Share, etc. An example is given below which shows how the menu
widget can be used in a program.
Example 15
Write a menu based program using the menu widget. The menu should have the top-level
options: File and Home. File menu should further have the submenus: New Open Save
Save As and Exit.
Solution 15
Figure 10.38 shows the program listing (program: gui17.py). Two menus are created:
filemenu and homemenu. Under filemenu the following submenus are created using
the add_command statement: New Open Save Save As Exit. Command add_separa-
tor adds a separator between the menu items. When a menu item is clicked the program
jumps to the function specified in the command field of the submenu and a message is dis-
played on the screen about the selected submenu item. For example, clicking on submenu
OpenFile sends the program control to function OpenFile where message Open File is
displayed by the function. Figure 10.39 shows the output of the program.
#========================================================
# Using Menu
# ==========
#
# This example shows how a menu and submenus can be created
#
# Author: Dogan Ibrahim
# File : gui17.py
# Date : July 2019
#========================================================
from tkinter import *
window = Tk()
window.title("MENU")
def NewFile():
● 192
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
print("New File")
def OpenFile():
print("Open File")
def SaveFile():
print("Save File")
def SaveAs():
print("Save As")
menu = Menu(window)
window.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open", command=OpenFile)
filemenu.add_command(label="Save", command=SaveFile)
filemenu.add_command(label="Save As", command=SaveAs)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=window.quit)
homemenu = Menu(menu)
menu.add_cascade(label="Home", menu=homemenu)
window.mainloop()
● 193
Learning Python with Raspberry Pi
Example 16
Write a tkinter based program to display the following messages when the mouse is clicked
when its pointer is over a button widget:
Action Display
Clicking left mouse Left mouse button clicked
Clicking right mouse button Right mouse button clicked
Double-clicking left mouse button Double left mouse button clicked
Solution 16
Figure 10.40 shows the program listing (program: gui18.py). Figure 10.41 shows the out-
put of the program when the left mouse and right mouse were clicked over the widget, and
then the left mouse was clicked twice. Notice that the left mouse button is identified with
<Button-1>, right mouse button with <Button-2> and double clicking the left mouse
with <Double-1>.
#===========================================================
# Events and Binds
# ================
#
# In this example when the mouse is clicked when the mouse
# pointer is over a widget, message Mouse Over is displayed
#
# Author: Dogan Ibrahim
# File : gui18.py
# Date : July 2019
#===========================================================
from tkinter import *
window = Tk()
window.geometry(“150x100")
def leftbutton(event):
print(“Left mouse button clicked")
def rightbutton(event):
print(“Right mouse button clicked")
def doubleleftbutton(event):
print(“Double left mouse button clicked")
● 194
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
window.mainloop()
Event Description
● 195
Learning Python with Raspberry Pi
<Return> User pressed the Enter key. Other keys can also be used,
e.g. Shift_L. For any shift key, Control_L for any control
key, Alt_L for any Alt key, etc.
Aim: The aim of this case study is to show how to use tkinter to read user input from the
keyboard and also how to calculate the resonance frequency of an RLC circuit.
(10.1)
(10.2)
(10.3)
The voltage across the inductor and capacitor at resonance are given by:
(10.4)
(10.5)
● 196
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
(10.6)
The upper and lower -3dB frequency points are given by:
(10.7)
And
(10.8)
Program Listing: Figure 10.43 shows the program listing (program: resonance.py). The
program is based on using the Entry widgets of tkinter to read the values of the resistance,
inductance, capacitance, and the applied voltage. 4 Labels and 4 Entry widgets are used to
read the values of R, L, C and V. Two Buttons are used in the program, entitled Quit and
Calculate. Clicking Quit terminates the program. Clicking Calculate calls function calcu-
late where formula (10.1) to (10.8) are used to calculate the various resonance values.
The calculated values are displayed using Labels inside function calculate.
#==============================================================
# Series RLC Circuit Resonance Calculations
# =========================================
#
# This program reads the values RLC and calculates and
# displays all the resonace related values
#
# Author: Dogan Ibrahim
# File : resonance.py
# Date : July 2019
● 197
Learning Python with Raspberry Pi
#==============================================================
from tkinter import *
import math
window = Tk()
window.title("SERIES RLC RESONANCE")
#
# Calculate and display the various resonance values
#
def calculate():
R = Re.get()
Rr = float(R) # R as floating point
L = Le.get()
Lr = float(L) /1000.0 # convert to Henries
C = Ce.get()
Cr = float(C) / 1000000.0 # convert to Farads
V = Ve.get()
Vr = float(V) # V as floating point
#
# Now carry out the calculations
#
LC = math.sqrt(Lr * Cr)
fr = 1.0 / (2*math.pi*LC) # resonant frequency
Ir = Vr / Rr # current in circuit
Xl = 2 * math.pi * fr * Lr # inductive reactance
Vl = Ir * Xl # Voltage across L and C
Q = 2 * math.pi * fr * Lr / Rr # Q factor
BW = fr / Q # Bandwidth
fl = fr - BW / 2 # lower -3dB freq
fh = fr + BW / 2 # higher -3dB freq
#
# Now display the calculated values
#
Label(window, text=" fr (Hz)= %10.2f" %(fr)).grid(row=8, column=0)
Label(window, text=" I(A)= %10.2f" %(Ir)).grid(row=9, column=0)
Label(window, text=" Xl (Ohms)= %10.2f" %(Xl)).grid(row=10, column=0)
Label(window, text=" Vl (Volts)= %10.2f" %(Vl)).grid(row=11, column=0)
Label(window, text=" Q= %10.2f" %(Q)).grid(row=12, column=0)
Label(window, text=" BW= %10.2f" %(BW)).grid(row=13, column=0)
Label(window, text=" fl (Hz)= %10.2f" %(fl)).grid(row=14, column=0)
Label(window, text=" fh (Hz)= %10.2f" %(fh)).grid(row=15, column=0)
#
# Display the circuit components to be read
#
● 198
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
#
# Read the circuit component values usieng Entry
#
Re = Entry(window)
Re.grid(row=1, column=1)
Le = Entry(window)
Le.grid(row=2, column=1)
Ce = Entry(window)
Ce.grid(row=3, column=1)
Ve = Entry(window)
Ve.grid(row=4, column=1)
#
# Button to Quit the program
#
butnquit = Button(window, text="Quit", command=window.quit)
butnquit.grid(row=18, column=0)
#
# Button to calculate the values
#
butncalc = Button(window, text="Calculate", command=calculate)
butncalc.grid(row=18, column=1)
window.mainloop()
Figure 10.44 shows a typical run of the program. Notice that the resistance is entered in
Ohms, capacitance in microfarads, inductance in millihenries, and voltage in Volts. The
frequency is displayed in Hertz.
● 199
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how to use tkinter to read user input from the
keyboard and also how to calculate the inductance of a single layer air core coil.
Background Information: The inductance of a single layer air core coil can be calculated
using the well-known Wheeler's formula. The formula, given below is accurate to within 1%
for L/D > 0.4 i.e, the coil is not too short. For short coils this formula is not very suitable:
(10.9)
Program Listing: Figure 10.45 shows the program listing (program: coil.py). The pro-
gram uses tkinter Entry widgets to read D, N, and L from the keyboard. The inductance is
then calculated and displayed. The user is warned that the results may not be accurate if
the coil is not short. Figure 10.46 shows a typical run of the program.
#=====================================================================
# Inductance of a Single Layer Coil
# =================================
#
# This program calculates teh inductance of a single layer air
# core coil. Number of turns,diameter,and length are read from keyboard
#
# Author: Dogan Ibrahim
# File : coil.py
# Date : July 2019
#=====================================================================
● 200
Chapter 10 • Using the Tkinter Graphical User Interface (GUI) in Python
window = Tk()
window.title(“INDUCTANCE")
#
# Calculate and display the various resonance values
#
def calculate():
N = Ne.get()
Nf = float(N) # N as floating point
D = De.get()
Df = float(D) # D as floating point
L = Le.get()
Lf = float(L) # L as floating point
#
# Now carry out the calculation and display the inductance
#
Ind = (Df * Df * Nf * Nf) / (45 * Df + 100* Lf)
Label(window, text="Inductance (microhenries)= %10.4f" %(Ind)).grid(row=5,
column=0)
if Lf / Df <= 0.4:
Label(window, text="Coil is too short,may not be accurate").grid(row=7,
column=0)
else:
Label(window, text=" “).grid(row=7,
column=0)
#
# Display the coil parameters to be read
#
N = Label(window, text="Number of turns (N): “).grid(row=1, column=0)
D = Label(window, text="Coil diameter (cm) : “).grid(row=2, column=0)
L = Label(window, text="Coil length(cm) : “).grid(row=3, column=0)
#
# Read the coil parameter values usieng Entry
#
Ne = Entry(window)
Ne.grid(row=1, column=1)
De = Entry(window)
De.grid(row=2, column=1)
Le = Entry(window)
Le.grid(row=3, column=1)
● 201
Learning Python with Raspberry Pi
#
# Button to Quit the program
#
butnquit = Button(window, text="Quit", command=window.quit)
butnquit.grid(row=8, column=0)
#
# Button to calculate the values
#
butncalc = Button(window, text="Calculate", command=calculate)
butncalc.grid(row=8, column=1)
window.mainloop()
● 202
Chapter 11 • BJT Transistor Circuit Analysis and Design
11.1 Overview
In the last chapter, we have learned how to develop GUI based programs using the tkinter.
In this chapter, we shall be concentrating on analysing and designing transistor circuits
using the Python programming language.
Aim: The aim of this case study is to show how DC analysis can be carried out on a BJT
transistor configured as in Figure 11.1.
Background Information: The voltages and currents relating to Figure 11.1 can be cal-
culated as follows:
● 203
Learning Python with Raspberry Pi
and (11.1)
(11.2)
(11.3)
(11.4)
There are 3 equations: (11.2), (11.3), and (11.4) with 3 unknowns: IB. VC. and IC. Solving
these equations we find the value of VC as:
(11.5)
Program Listing: Figure 11.2 shows the program listing (program: bias1.py). The pro-
gram displays a heading and then reads the values of the two resistors, supply voltage, and
the current gain β (or B) of the transistor. It then calculates and displays the base current,
collector current, emitter current, and the collector-emitter voltage using the above equa-
tions. Figure 11.3 shows a typical run of the program with the following component values:
RB = 3300 Ohm
RC = 1000 Ohm
VCC = 10 Volt
β = 100
#=================================================
# Collector Feedback Biasing
# ==========================
#
# This program analyzes a collector feedbak bias
#
# Author: Dogan Ibrahim
# File : bias1.py
# Date : July 2019
#=================================================
print("Collector Feedback Biassed Transistor Analysis")
print("==============================================")
#
# Read the component values
#
● 204
Chapter 11 • BJT Transistor Circuit Analysis and Design
#
# Calculations
#
Vb = 0.7
Vcnum = RB*Vcc + Vb * RC * (1 + B)
Vcdenom = RC * (1 + B) + RB
Vc = Vcnum / Vcdenom
Vce = Vc
IB = 1000.0 * ((Vc - Vb) / RB)
IC = B * IB
#
# Display the results
#
print("\nVb=%7.3f V\nVc=%7.3f V\nVce=%7.3f V\nIB=%7.3f mA\nIC=%7.3f mA"
%(Vb,Vc,Vce,IB,IC))
● 205
Learning Python with Raspberry Pi
Aim: The aim of this case study is to show how DC analysis can be carried out on a BJT
transistor configured as in Figure 11.4.
Background Information: The voltages and currents relating to Figure 11.4 can be cal-
culated as follows:
(11.6)
(11.7)
(11.8)
(11.9)
(11.10)
(11.11)
(11.12)
(11.13)
● 206
Chapter 11 • BJT Transistor Circuit Analysis and Design
(11.14)
Notice that the base current is usually very small compared to the collector current and
in most calculations equations (11.10), (11.11), and (11.12) are approximately replaced
with:
Program Listing: Figure 11.5 shows the program listing (program: bias2.py). The pro-
gram displays a heading and then reads the values of all the two resistors, supply voltage,
and the current gain β (or B) of the transistor. It then calculates and displays all the voltag-
es and current shown in equations (11.6) to (11.14). A typical run of the program is shown
in Figure 11.6 with the following component values:
Vcc = 12 Volt
RB1 = 30,000 Ohm
RB2 = 10,000 Ohm
RC = 1000 Ohm
RE = 1000 Ohm
β = 100
#=================================================
# Voltage Divider Biasing
# =======================
#
# This program analyzes a voltage divider bias
#
# Author: Dogan Ibrahim
# File : bias2.py
# Date : July 2019
#=================================================
print("Voltage Divider Biassed Transistor Analysis")
print("===========================================")
#
# Read the component values
#
Vcc = float(raw_input("Enter supply voltage (Volts): "))
RB1 = float(raw_input("Enter RB1 (Ohms): "))
RB2 = float(raw_input("Enter RB2 (ohms): "))
RC = float(raw_input("Enter RC (Ohms): "))
RE = float(raw_input("Enter RE (Ohms): "))
B = float(raw_input("Enter current gain(B): "))
● 207
Learning Python with Raspberry Pi
#
# Calculations
#
Vb = 0.7
VB = Vcc * (RB2 / (RB1 + RB2))
IB1 = (Vcc - VB) / RB1
IE = (VB - Vb) / RE
RB = RB1 * RB2 / (RB1 + RB2)
IB = (VB - Vb) / (RB + RE * (B + 1))
IB2 = IB1 - IB
IC = IE - IB
VCE = Vcc - (IC * RC + IE * RE)
VE = IE * RE
VC = Vcc - RC * IC
IB1 = 1000.0 * IB1
IB2 = 1000.0 * IB2
IE = 1000.0 * IE
IC = 1000.0 * IC
IB = 1000.0 * IB
#
# Display the results
#
print("\nVB=%7.3f V\nVCE=%7.3f V\nVE=%7.3f V\nVC=%7.3f V" %(VB,VCE,VE,VC))
print("\nIB1=%7.3f mA\nIB2=%7.3f mA\nIB=%7.3f mA\nIC=%7.3f mA\nIE=%7.3f mA"
%(IB1,IB2,IB,IC,IE))
● 208
Chapter 11 • BJT Transistor Circuit Analysis and Design
Aim: The aim of this case study is to show how a single-stage common emitter amplifier
can be designed using the Python programming language.
Background Information: The circuit diagram of a single stage common emitter am-
plifier circuit is shown in Figure 11.7. The AC parameters of this amplifier circuit can be
calculated using the following formula (see Hybrid Pi model):
The design starts from the specification of the required voltage gain, or the input voltage
and the required output voltage. The power supply voltage is usually supplied. We first have
to find the resistor values for biasing the transistor and also providing the required gain.
Briefly, the steps are as follows:
● 209
Learning Python with Raspberry Pi
• Given the input and required output voltages, calculate the required voltage gain.
• Choose a collector current of around 2mA.
• Assume the VCE to be Vcc/2
• Choose a value for RL. Thinking that the gain without the source and load resis-
tors is given by RL x IE /25 at room temperature, choose RL to give 30% higher
gain than the required value
• Choose a value for RE (assuming that IE = Ic) from equation Vcc = IcRL + VCE
+IcRE
• Calculate base current from IB / β
• Calculate the base voltage from VB = 0.7 + IcRE
• Assume that the current in R1 and R2 will be 10 times the base current and cal-
culate suitable values for R1 and R2
• Calculate the input and output impedances
• Check that the overall gain is as required, if not go back and adjust Ic, RL, or RE
• Calculate suitable values for C1, C2 and CE
Program Listing: Figure 11.8 shows the program listing (program: amplifier.py). At the
beginning of the program, a heading is displayed.
#=====================================================
# Single Stage Common Emitter Amplifier Design
# ============================================
#
# This program designs a common emitter amplifier
#
# Author: Dogan Ibrahim
# File : amplifier.py
# Date : July 2019
#======================================================
import math
● 210
Chapter 11 • BJT Transistor Circuit Analysis and Design
#
Vcc = float(raw_input("Enter supply voltage (Volts): "))
Vin = float(raw_input("Enter Vin (Volts): "))
Vout = float(raw_input("Enter Vout (Volts): "))
RS = float(raw_input("Enter Rs (ohms): "))
RL = float(raw_input("Enter RL (Ohms): "))
f = float(raw_input("Enter lowest frequency to amplify (Hz): "))
B = float(raw_input("Enter current ratio (B): "))
#
# Calculations
#
Gr = Vout / Vin # Gain
IC = 2 # IC=2mA
Ge = Gr * (1.3) # Estimate gain 30% higher
RC = Ge * 25 / IC # Collector resistance
RCRL = (RC * RL) / (RC + RL)
re = 25.0 / IC
Rinbase = B * re # Base resistance
G1 = RCRL / re # G1
VCE = Vcc / 2 # VCE
IC = IC / 1000.0
RE = (Vcc - RC * IC - VCE) / IC # RE
VB = 0.7 + IC * RE
IB = IC / B
IR1R2 = 10.0 * IB # 10 times base current
R2 = VB / IR1R2
R1 = (Vcc - VB) / IR1R2
RB = (R1 * R2) / (R1 + R2)
Zi = (RB * Rinbase) / (RB + Rinbase)
G2 = Zi / (RS + Zi)
G = G1 * G2
XC = Zi / 10.0
C1 = 1000000.0 / (2 * math.pi * f * XC)
Zo = RCRL
XC = Zo / 10.0
C2 = 1000000.0 / (2 * math.pi * f * XC)
XC = RE / 10.0
CE = 1000000.0 / (2 * math.pi * f * XC)
#
# Display the results
#
print("\nRESULTS:")
print("=======")
print("Gain=%7.3f\nIC=%7.3f mA\nIB=%7.3f mA" %(G,IC*1000.0,IB*1000.0))
● 211
Learning Python with Raspberry Pi
An example run of the program is shown in Figure 11.9. In this example the following spec-
ifications were assumed:
Vin = 0.010V
Vout = 0.4V
Rs = 100 Ohm
RL = 15K
fl = 40Hz
Vcc = 12V
β = 100
It is clear that the required voltage gain of the transistor (without the source and load re-
sistances) is 0.4V/0.010V = 40.
● 212
Chapter 11 • BJT Transistor Circuit Analysis and Design
11.7 Summary
In this chapter, we have learned how to use Python to analyze the DC bias characteristic of
BJT transistors. We have also developed a program to design single stage common emitter
transistor amplifier with the given specifications. In the next chapter, we shall be looking at
how to design active filters with the help of Python.
● 213
Learning Python with Raspberry Pi
12.1 Overview
In the last chapter, we have learned how to develop programs to analyze and design tran-
sistor bias circuits and common emitter based single stage amplifiers. In this chapter, we
shall be learning how to use Python to design active low-pass filters. Low-pass and Band-
pass filters are used commonly in electrical circuits, especially in communications circuits.
In this chapter, we shall only be looking at the design of second-order active low-pass
filters. Filters of higher-order can easily be designed by cascading the basic second-order
sections. When cascading filter sections, the overall gain is the product of the gain of each
section.
Aim: The aim of this case study is to show how a second-order active filter can be designed
using the Python programming language.
Background Information: There are several forms of second-order active low-pass fil-
ters. The one used in this case study is the well-known Sallen-Key type filter whose circuit
diagram is shown in Figure 12.1. The filter consists of two capacitors and two resistors. This
type of filter has unity gain in the pass-band.
It is possible to design Sallen-Key type filters with higher gains, but care should be taken
since the high gain filters can easily become unstable and oscillate, giving high overshoot
in their time responses and high gains at their cut-off frequencies. The Q factor of a filter
defines its quality, i.e. the damping of the response. For low-pass filters, Q should have a
value of 0.707. Higher values of Q may cause instability and overshoots in the time and fre-
quency responses. Another parameter used in filter design is the damping factor, denoted
with ξ. This is related to the Q factor with the following equation:
The ideal value for ξ is also 0.707. Lower values of ξ give rise to oscillations and instability
in the designed circuit. To maintain stability the gain of an active filter must not be greater
● 214
Chapter 12 • Active Filters
Figure 12.2 shows the filter frequency response for various values of ξ. It is clear from this
figure that ξ = 0.707 gives a flat response.
or C2 / C1 <= 0.5
or,
● 215
Learning Python with Raspberry Pi
Program Listing: Figure 12.3 shows the program listing (program: lowpass.py). At the
beginning of the program a heading is displayed and the user is required to enter the filter
cut-off frequency, C1 and C2 in microfarads. The program calculates and displays the re-
quired resistors, making sure that the above inequality is satisfied. The user is then asked
to enter the actual physical resistors to be used and displays the actual cut-off frequency
when these resistors are used. If the user is not happy with the calculated cut-off frequency
then the program is restarted so that the user can select new values for the capacitors.
#=====================================================
# Second Order Low-Pass Active Filter Design
# ==========================================
#
# This program designs a second order low-pass filter
#
# Author: Dogan Ibrahim
# File : lowpass.py
# Date : July 2019
#======================================================
import math
yn = 'n'
while yn == 'n':
print("Second Order Low-Pass Active Filter Design")
print("==========================================")
#
# Read the cut-off frequency and C1, C2
#
C1 = 1
C2 = 1
f = float(raw_input("Enter the cut-off frequency (Hz): "))
C1F = C1 / 1000000.0
C2F = C2 / 1000000.0
● 216
Chapter 12 • Active Filters
#
# Calculations
#
n = C1F / C2F
r = 2 * math.pi * f * C2F * math.sqrt(n)
R = 1 / r
#
# Display the results
#
print("\nRESULTS:")
print("=======")
print("C1=%7.3f uF\nC2=%7.3f uF\nR1=%7.3f Ohm\nR2=%7.3f Ohm" %(C1,C2,R,R))
An example run of the program is shown in Figure 12.4. In this example, the following
specifications were used:
● 217
Learning Python with Raspberry Pi
The resistor values are calculated to be R1 = R2 = 18.759 Ohm. Selecting the nearest phys-
ical value as 18 Ohm gives the cut-off frequency as 1042.033Hz. We accept this value and
respond with y to terminate the program. The application given in the following link can be
used to display the frequency response, Q factor, etc of a low-pass Sallen-Key type filter:
http://sim.okawa-denshi.jp/en/OPstool.php
Using this application, the transfer function, Q factor, damping factor, the frequency and
phase responses of the designed filter with the new resistors are shown in Figure 12.5 and
Figure 12.6.
● 218
Chapter 12 • Active Filters
The above application also shows the step response of the designed filter. This is shown in
Figure 12.7.
● 219
Learning Python with Raspberry Pi
12.5 Summary
In this chapter, we have learned how to design active low-pass filters of type Sallen-Key
using the Python programming language. Interested readers can expand their knowledge
and learn how to design other types of filters, such as high-pass and band-pass. In the next
chapter, we shall be looking at how to access the Raspberry Pi 4 hardware and peripheral
devices from Python.
● 220
Chapter 13 • Accessing Raspberry Pi 4 Hardware and Peripheral Devices From Python
13.1 Overview
All versions of Raspberry Pi include a socket for connecting external devices, such as sen-
sors, LEDs, actuators, etc. For the sake of completeness, in this chapter, we will look at how
external devices connected to Raspberry Pi can be accessed from Python. In this chapter,
the following types of peripheral access from Python will be covered with one example from
each type of access.
There are many project-based books on using Python to access peripheral devices connect-
ed to Raspberry Pi. Interested readers can search Google or Amazon for articles and books
in this field. The author has the following publications on this topic:
Before going into the details of the hardware interface, it is worthwhile to look at the Rasp-
berry Pi 4 GPIO connector. This is a 40-pin dual-in-line 2.54mm wide connector as shown
in Figure 13.1.
● 221
Learning Python with Raspberry Pi
The GPIO provides 26 general purpose bi-directional I/O pins. Some of the pins have mul-
tiple functions. For example, pins 3 and 5 are the GPIO2 and GPIO3 input-output pins
respectively. These pins can also be used as the I2C bus I2C SDA and I2C SCL pins respec-
tively. Similarly, pins 9,10,11,19 can either be used as general purpose input-output, or as
the SPI bus pins. Pins 8 and 10 are reserved for UART serial communication.
Two power outputs are provided: +3.3V and +5.0V. The GPIO pins operate at +3.3V logic
levels (not like many other computer circuits that operate with +5V). A pin can either be
an input or an output. When configured as an output, the pin voltage is either 0V (logic
0) or +3.3V (logic 1). Raspberry Pi 3 is normally operated using an external power supply
(e.g. a mains adapter) with +5V output and minimum 2A current capacity. A 3.3V output
pin can supply up to 16mA of current. The total current drawn from all output pins should
not exceed the 51mA limit. Care should be taken when connecting external devices to the
GPIO pins as drawing excessive currents or short-circuiting a pin can easily damage your Pi.
The amount of current that can be supplied by the 5V pin depends on many factors such as
the current required by the Pi itself, current taken by the USB peripherals, camera current,
HDMI port current, and so on.
When configured as an input, a voltage above +1.7V will be taken as logic 1, and a voltage
below +1.7V will be taken as logic 0. Care should be taken not to supply voltages greater
than +3.3V to any I/O pin as large voltages can easily damage your Pi.
If you get an error while trying to import the GPIO library then it is possible that the library
is not installed. Enter the following commands while in the command mode (identified by
the prompt pi@raspberrypi:~ $) to install the GPIO library (characters that should be
entered by you are in bold):
The GPIO provides a number of useful functions. Some of the available functions are given
in the next sections
● 222
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
GPIO.setmode(GPIO.BOARD)
The second numbering system, also known as the BCM method is the preferred method
and it uses the channel numbers allocated to the pins. This method requires that you know
which channel number refers to which pin on the board. In this book, we shall be using this
second method. Enter the following statement to use the BCM method:
GPIO.setmode(GPIO.BCM)
The GPIO is a 40 pin header, mounted at one side of the board. Appendix A shows the
Raspberry Pi 4 GPIO pin configuration.
Input Configuration
You need to configure the channels (or port pins) you are using whether they are input or
output channels. The following statement is used to configure a channel as an input. Here,
channel refers to the channel number based on the setmode statement above:
GPIO.setup(channel, GPIO.IN)
When there is nothing connected to an input pin, the data at this input is not defined. We
can specify additional parameters with the input configuration statement to connect pull-up
or pull-down resistors by software to an input pin. The required statements are:
For pull-down:
For pull-up:
We can detect an edge change of an input signal at an input pin. Edge change is when
the signal changes from LOW to HIGH (rising edge), or from HIGH to LOW (falling edge).
For example, pressing a push-button switch can cause an edge change at the input of a
pin. The following statements can be used to wait for an edge of the input signal. These
are blocking functions. i.e. the program will wait until the specified edge is detected at the
input signal. For example, if this is a push-button, the program will wait until the button is
pressed:
● 223
Learning Python with Raspberry Pi
GPIO.wait_for_edge(channel, GPIO.RISING)
GPIO.wait_for_edge(channel, GPIO.FALLING)
We can also wait until either a rising or a falling edge is detected by using the following
statement:
GPIO.wait_for_edge(channel, GPIO.BOTH)
We can use event detection function with an input pin. This way, we can execute the event
detection code whenever an event is detected. Events can be rising edge, falling edge, or
change in either edge of the signal. Event detection is usually used in loops where we can
check for the event while executing other code.
GPIO.add_event_detect(channel, GPIO.RISING)
We can check whether or not the event occurred by the following statement:
If GPIO.event_detected(channel):
……………………………
……………………………
GPIO.remove_event_detect(channel)
We can also use interrupt facilities (or callbacks) to detect events. Here, the event is han-
dled inside a user function. The main program carries on its usual duties and as soon as
the event occurs the program stops whatever it is doing and jumps to the event handling
function. For example, the following statement can be used to add interrupt based event
handling to our programs on rising edge of an input signal. In this example, the event han-
dling code is the function named MyHandler:
def MyHandler(channel):
………………….
………………….
● 224
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
We can add more than one interrupt by using the add_event_callback function. Here the
callback functions are executed sequentially:
GPIO.add_event_detect(channel, GPIO.RISING)
GPIO.add_event_callback(channel, MyHandler1)
GPIO.add_event_callback(channel, MyHandler2)
……………………………………………………….
……………………………………………………….
def MyHandler1(channel):
……………………
……………………
def MyHandler2(channel):
……………………
……………………
When we use mechanical switches in our projects we get what is known as the switch
bouncing problem. This occurs as the contacts of the switch bounce many times until they
settle to their final state. Switch bouncing could generate several pulses before it settles
down. We can avoid switch bouncing problems in hardware or software. GPIO library pro-
vides a parameter called bounce-time that can be used to eliminate the switch bouncing
problem. An example use of this parameter is shown below where the switch bounce time
is assumed to be 10ms:
GPIO.add_event_detect(channel,GPIO=RISING,callback=MyHandler, bouncetime=10)
We can also use the callback statement to specify the switch bouncing time as@
To read the state of an input pin we can use the following statement:
GPIO.input(channel)
Output Configuration
The following statement is used to configure a channel as an output. Here, channel refers
to the port number based on the setmode statement described earlier:
GPIO.setup(channel, GPIO.OUT)
We can specify a value for an output pin during its setup. For example, we can configure a
channel as output and at the same time set its value to logic HIGH (+3.3V):
● 225
Learning Python with Raspberry Pi
To send data to an output port pin we can use the following statement:
GPIO.output(channel, value)
At the end of the program, we should return all the used resources to the operating system.
This is done by including the following statement at the end of our program:
GPIO.cleanup()
Aim: The aim of this case study is to show how an LED can be connected to a GPIO pin and
how the GPIO library can be used to flash the LED.
Background Information: The forward voltage of an LED is around 1.8V. The current
through the LED depends on the required light intensity and the type of LED used. In gen-
eral 3mA should give enough visible light for small LEDs. Because the output voltage of
a GPIO pin is +3.3V we have to use a current limiting resistor in series with the LED. The
value of the current limiting resistor is calculated as:
R = (3.3V – 1.8V / 3mA = 500 Ohm. We can choose a 470 Ohm resistor
Figure 13.2 shows the LED connected to pin GPIO 2 of the Raspberry Pi.
Program Listing: The program is very simple and is shown in Figure 13.3 (program: LED.
py). At the beginning of the program the RPi.GPIO and the time modules are imported to
the program. Then the pin numbering is configured to use BCM notation and GPIO is con-
figured as an output pin. The remainder of the program is run indefinitely in a while loop
where the LED is turned ON and OFF with one second delay between each output. Run the
program with the command: python LED.py from the command line. You can enter Cn-
trl+C to terminate the program.
● 226
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
#-------------------------------------------------------
#
# FLASHING LED
# ============
#
# In this project a small LED is connected to GPIO 2 of
# the Raspberry Pi 4. The program flashes the LED every
# second.
#
# Program: LED.py
# Date : August 2019
# Author : Dogan Ibrahim
#--------------------------------------------------------
import RPi.GPIO as GPIO # import GPIO library
import time # import time library
GPIO.setwarnings(False) # disable warning messages
try:
while True:
GPIO.output(2, 1) # turn ON LED
time.sleep(1) # wait 1 second
GPIO.output(2, 0) # turn OFF LED
time.sleep(1) # wait 1 second
except KeyboardInterrupt:
GPIO.cleanup()
13.3 PWM
PWM waves are frequently used in power control applications. The waveform is basically a
positive square wave with variable ON and OFF times. As shown in Figure 13.4, the total of
the ON and OFF times is known as the period of the waveform. The ratio of the ON time to
the period is known as the Duty Cycle and it is represented as a percentage. i.e.
where, T is the ON time, and P is the period (ON time + OFF time).
● 227
Learning Python with Raspberry Pi
By varying the duty cycle from 0% to 100% we can easily control a load, e.g. a motor. For
example, at 50% duty cycle the load receives half of the total power. Similarly, at 100%
duty cycle the load receives full power.
Aim: The aim of this case study is to show how a PWM waveform can be generated using
the PWM library.
Program Listing: Figure 13.5 shows the program listing (program: PWM.py). GPIO is
configured as a PWM channel with the frequency of the waveform set to 1kHz. The PWM is
initially started with 50% Duty Cycle and then the Duty Cycle is varied every 0.1 seconds
(100 ms).
● 228
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
#====================================================
# VARYING THE LED BRIGHTNESS
# ==========================
#
# In this program a PWM waveform is supplied to the
# LED with varying Duty Cycle. The net effect is that
# the LED brightness changes
#
# Author: Dogan Ibrahim
# File : PWM.py
# Date : August 2019
#======================================================
import RPi.GPIO as GPIO # import GPIO
import time # import time
GPIO.setwarnings(False)
try:
while True:
p.ChangeDutyCycle(DC) # change Duty Cycle
DC = DC + 1 # increment Duty Cycle
if DC > 100: # if > 100
DC = 0 # set to 0
time.sleep(0.1) # 0.1 second delay
13.4 I2C
I2C (or I2C) is a bus standard developed by Philips back in the '80s to enable communica-
tion between processors and sensors. This bus standard uses two wires for communication:
SDA (data) and SCL (clock). The bus operates as master-slave where the Raspberry Pi is
the master and the sensors or actuators are the slaves. The SDA and SCL lines are pulled
up to +3.3V through internal pull-up resistors inside Raspberry Pi. Each slave has its own
unique address, and the address of a slave can normally be changed to avoid a clash on
the bus. Communication on the I2C bus is always started by the master where it sends the
address of the slave it wants to communicate with. Only one slave on the bus can respond
to this request.
● 229
Learning Python with Raspberry Pi
Before using the I2C bus we have to import module smbus into our program. The following
commands are provided by the Python I2C module:
Aim: The aim of this case study is to show how an I2C type LCD can be connected to Rasp-
berry Pi and how data can be displayed on the LCD.
Background Information: The circuit diagram of the project is shown in Figure 13.6. Al-
though Raspberry Pi 3 is shown in the Figure, the same circuit can be used with Raspberry
Pi 4 as well. The I2C LCD has 4 pins: GND, +V, SDA, and SCL. SDA is connected to pin
GPIO 2 and SCL is connected to pin GPIO 3. +V pin of the display should be connected to
the +5V (pin 2) of the Raspberry Pi 3 (some versions of Raspberry Pi, such as the Rasp-
berry Pi Zero and Raspberry Pi Zero W cannot supply enough power to drive the LCD. It is
recommended to use an external +5V supply to power for the LCD if you are using one of
these models). Note that there is no problem mixing the +3.3V GPIO pins of the Raspberry
Pi with the +5V of the I2C LCD. This is because the Raspberry Pi is the I2C master device
and the SDA and SCL lines are pulled up to +3.3V through resistors. SCL line is the clock
which is always output from the master device. The slave device (I2C LCD here) only pulls
down the SDA line when it acknowledges the receipt of data and it does not send any data
to the master device. Therefore, there are no voltage level problems as long as the Rasp-
berry Pi I2C output pins can drive the I2C LCD inputs, which is the case here.
● 230
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
Program Listing: Before using the I2C pins of the Raspberry Pi we have to enable the I2C
peripheral interface on the device. The steps for this are as follows:
Now we have to install the I2C library on our Raspberry Pi 4. The steps are as follows:
Enter the following commands from the command menu:
Enter the following command to test the installation. You should see i2c_bcm2837 listed:
Add the following lines (if they are not already there):
i2c-bcm2837
i2c-dev
Exit from nano by typing Ctrl X and Y to save the file. You can check the
contents of this file by entering the command:
● 231
Learning Python with Raspberry Pi
Connect your LCD to the Raspberry Pi 4 device and enter the following command to check
whether or not the LCD is recognized by the Raspberry Pi 4:
You should see a table similar to the one shown below. A number in the table means that
the LCD has been recognizes correctly and the I2C slave address of the LCD is shown in the
table. In this example the LCD address is 27:
1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- 27 -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
We should now install an I2C LCD library so that we can send commands and data to our
LCD. There are many Python libraries available for the I2C type LCDs. The one chosen here
is called the RPi_I2C_driver. This library is installed as follows:
https://gist.github.com/DenisFromHR/cc863375a6e19dce359d
• Scroll down to section RPi_I2C_driver.py. Click Raw at the top right-hand side
of the screen and save the file in a folder (e.g. Desktop) with the name RPi_
I2C_driver.py (the easiest option might be to copy the file into the Notebook
and then save it as RPi_I2C_driver.py).
• Start the WinSCP file copy utility (you should install it if you already do not have
it) on your PC and copy file RPi_I2C_driver.py to folder usr/lib/python2.7
on your Raspberry Pi 4.
• Check to make sure that the file is copied successfully. You should see the file
listed with the command:
pi@raspberrypi: ~ $ ls /usr/lib/python2.7
● 232
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
We are now ready to write our program. Figure 13.7 shows the program listing (lcd.py). At
the beginning of the program libraries RPi.GPIO, timer, and the LCD driver library RPi_I2C_
driver are imported to the program. Then text TESTING I2C is displayed.
#---------------------------------------------------------
#
# I2C LCD SECONDS COUNTER
# =======================
#
# In this program an I2C LCD is connected to the Raspberry Pi
# and text TESTING I2C is displayed on the LCD
#
# Program: lcd.py
# Date : August 2019
# Author : Dogan Ibrahim
#----------------------------------------------------------
import RPi_I2C_driver
LCD = RPi_I2C_driver.lcd()
LCD.lcd_clear() # clear LCD
LCD.lcd_display_string("TESTING I2C", 1) # display string
while True:
pass
The I2C LCD library supports the following functions (see the I2C LCD library documenta-
tion for more details):
13.5 SPI
Serial Peripheral Interface (SPI) bus consists of two data wires and one clock wire. Addi-
tionally, a chip enable (CE) connection is used to select a slave in a multi-slave system. The
wires used are:
MOSI: M
aster Out Slave In. This signal is output from the master and is input to
a slave
MISO: Master In Slave Out. This signal is output from a slave and input to a master
● 233
Learning Python with Raspberry Pi
There are 4 SPI operational modes known as mode 0 to mode3. The mode determines the
relationship between the clock pulses and the data pulses. Data can be read at the leading
edge or at the trailing edge of the clock. CPOL (clock polarity) and CPHA (clock phase) de-
termine the mode of operation. CPOL determines the polarity of the clock. In mode 0, both
CPOL and CPHA are 0 and data is sampled at the leading rising edge of the clock. In mode
2, CPOL=1 and CPHA=0, data is sampled at the leading falling edge of the clock. In mode
1, CPOL=0 and CPHA=1 and the data is sampled on the trailing falling edge of the clock. Fi-
nally, in mode 3, CPOL=1 and CPHA=1 where the data is sampled on the trailing rising edge
of the clock. Mode 0,0 is used by the Raspberry Pi which is the most commonly used mode.
The SPI bus on the Raspberry Pi supports the following functions:
Function Description
Aim: The aim of this project is to show how an SPI bus compatible external ADC chip can
be connected and controlled from Python.
Background Information: The dual MCP3002 ADC chip is used in this project to provide
analog input capability to the Raspberry Pi. This chip has the following features:
● 234
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
The MCP3002 is a successive approximation 10-bit ADC with on-chip sample and hold
amplifier. The device is programmable to operate as either differential input pair or as dual
single-ended inputs. The device is offered in an 8-pin package. Figure 13.8 shows the pin
configuration of the MCP3002.
In this case study the supply voltage and the reference voltage are set to +3.3V. Thus, the
digital output code is given by:
Each quantization level corresponds to 3300mV/1024 = 3.22mV. The MCP3002 ADC has
two configuration bits: SGL/DIFF and ODD/SIGN. These bits follow the sign bit and are
used to select the input channel configuration. The SGL/DIFF is used to select single-ended
or pseudo-differential mode. The ODD/SIGN bit selects which channel is used in single-
ended mode and is used to determine polarity in pseudo-differential mode. In this project
we are using channel 0 (CH0) in single ended mode. According to the MCP3002 datasheet,
SGL/DIFF and ODD/SIGN must be set to 1 and 0 respectively.
Figure 13.9 shows the circuit diagram of the project (although Raspberry Pi 3 is shown in
the figure, the circuit is applicable to all versions of Raspberry Pi). A TMP36DZ type analog
temperature sensor chip is connected to CH0 of the ADC. TMP36DZ is a 3 terminal small
sensor chip with pins: Vs, GND, and Vo. Vs is connected to +3.3V, GND is connected to sys-
tem ground, and Vo is the analog output voltage. The temperature in degrees Centigrade
is given by:
● 235
Learning Python with Raspberry Pi
CS, Dout, CLK, and Din pins of the ADC are connected to the SPI pins CE0, MISO, SCLK,
and MOSI pins of the Raspberry Pi 3 respectively.
Program Listing: Figure 13.10 shows the program listing (program: tmp36.py). Function
get_adc_data is used to read the analog data, where the channel number (channel_no)
is specified in the function argument as 0 or 1. Notice that we have to send the start bit,
followed by the SGL/DIFF and ODD/SIGN bits and the MSBF bit to the chip.
It is recommended to send leading zeroes on the input line before the start bit. This is often
done when using microcontroller-based systems that must send 8 bits at a time. The fol-
lowing data can be sent to the ADC (SGL/DIFF = 1 and ODD/SIGN = channel_no) as bytes
with leading zeroes for a more stable clock cycle. The general data format is:
For channel 0: 0000 0001 1000 0000 0000 0000 (0x01, 0x80, 0x00)
For channel 1: 0000 0001 1100 0000 0000 0000 (0x01, 0xC0, 0x00)
Notice that the second byte can be sent by adding 2 to the channel number (to make it 2
or 3) and then shifting 6 bits to the left as shown above to give 0x80 or 0xC0.
The chip returns 24 bit data (3 bytes) and we must extract the correct 10 bit ADC data from
this 24 bit data. The 24 bit data is in the following format ("X" is don't care bit):
● 236
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
Assuming that the returned data is stored in 24 bit variable ADC, we have:
Thus, we can extract the 10 bit ADC data with the following operations:
Adding the low byte and the high byte we get the 10 bit converted ADC data as:
DD DDDD DDDD
The module spidev must be imported at the beginning of the program before any of the
above functions are called. Also, you must enable the SPI interface on your Raspberry Pi 4
in the configuration menu. The steps are:
At the beginning of the program, modules RPi.GPIO and spidev are imported to the pro-
gram and an instance of the SPI is created. Function get_adc_data reads the temperature
from sensor chip MCP3002 and returns a digital value between 0 and 1023. This value is
then converted into millivolts, 500 is subtracted from it, and the result is divided by 10 to
find the temperature in degrees Centigrade. The temperature is displayed on the monitor
every second.
#---------------------------------------------------------------
#
# ANALOG TEMPERATURE SENSOR
# =========================
#
# In this project a TMP36 type analog temperature chip is used
# to measure the ambient temperature. The temperature is read
● 237
Learning Python with Raspberry Pi
GPIO.setmode(GPIO.BCM)
#
# This function returns the ADC data read from the MCP3002
#
def get_adc_data(channel_no):
ADC = spi.xfer2([1, (2 + channel_no) << 6, 0])
rcv = ((ADC[1] & 15) << 6) + (ADC[2] >> 2)
return rcv
#
# Start of main program. Read the analog temperature, convert
# into degrees Centigrade and display on the monitor every second
#
while True:
adc = get_adc_data(0)
mV = adc * 3300.0 / 1023.0 # convert to mV
Temp = (mV - 500.0) / 10.0 # temperature in C
print("Temperature = %f " %Temp) # display temperature
time.sleep(1) # wait one second
● 238
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
Aim: The aim of this project is to show how the serial ports of the Raspberry Pi can be
accessed from Python.
Background Information: By default, pin 8 and pin 10 of the Raspberry Pi are the serial
TXD and RXD ports respectively. In this case study, pin 8 is connected to pin 10 through a
2K current limiting resistor (this is necessary to protect the RXD pin from short circuit as
both pins may have been set as outputs with one at 0 and the other one at 1). Figure 13.13
shows the serial loopback used in this case study.
● 239
Learning Python with Raspberry Pi
The best way to test the serial port on Raspberry Pi is to use the minicom program. This
can be installed as follows:
By default, the Raspberry Pi's serial port is configured to be used for console input/output.
To be able to use the serial port to connect and talk to other serial devices, the serial port
console login needs to be disabled. After disabling the console logins, the only way to log in
to our Raspberry Pi will be via SSH using the Putty terminal emulator.
• Select P6 Serial
• Select Yes to Would you like the serial port hardware to be enabled?
Don't forget to go back and enable serial logins after you finish working with the serial port.
To test the serial port, enter the following command to start minicom on your Raspberry
Pi 4:
here, -b means that the next item is the Baud rate, -o means that the mode should not
be initialized (there is no modem), and –D means that the device name is the next item.
● 240
Chapter 13 • Accessing Raspberry Pi 4 Hardware and PeripheralDevices From Python
You should now see the Mincom screen. Whatever you type through the keyboard will be
echoed back on the keyboard as shown in Figure 13.14.
To exit from minicom, enter Cntrl+A followed by X. To clear the screen enter Cntrl+A
followed by C. To display the minicom help screen enter Cntrl+A followed by Z.
Note: you will have to replace /dev/ttyS0 with /dev/ttyAMA0 if you are using earlier
than Raspberry Pi 3.
Program Listing: Python on Raspberry Pi supports the following serial port commands:
You may have to install the serial module for the above commands to work:
The program listing is shown in Figure 13.15 (program: serialport.py). This program
opens the serial port at 9600 Baud. Text Testing serial port is sent to serial port. This text
is then read and displayed on the screen.
13.7 Summary
In this chapter, we have learned how to program using Python to access the peripheral
devices connected to our Raspberry Pi. In the next chapter, we shall be looking at how to
use Python to develop programs using Wi-Fi so that we can communicate with the external
world.
● 241
Learning Python with Raspberry Pi
14.1 Overview
In the last chapter, we learned how to access peripheral devices connected to Raspberry
Pi. In this chapter, we shall be learning how to communicate with the external world over
a Wi-Fi link.
Server
• Create a socket
• Bind the socket to a port with your IP address
• Listen for connections from clients
• Accept connection to a client
• Exchange data (send and receive data) with the client
• Close the connection
Client
• Create a socket
• Connect to the server by specifying its IP address and port number
• Exchange data (send and receive data) with the server
• Close the connection
In the examples in this chapter, the server is the Raspberry Pi, while the client is a PC or a
mobile phone.
Before starting to write network-based programs, we have to know the IP address of our
Raspberry Pi Wi-Fi link. This can be obtained by entering the command ifconfig as show in
Figure 14.1. In this figure, the IP address is: 192.168.1.202
● 242
Chapter 14 • Python and the Internet on Raspberry Pi 4
14.3.1 Case Study 29 – Sending a Text Message to a Mobile Phone Using TCP/IP
Description: In this case study a TCP/IP based communication is established with an An-
droid mobile phone. The program reads text messages from the keyboard and sends to the
mobile phone.
Aim: The aim of this project is to show how TCP/IP communication can be established with
an Android mobile phone.
Raspberry Pi Program Listing: In this case study Raspberry Pi is the server. Figure 14.7
shows the Raspberry Pi program listing (program: tcpserver.py). At the beginning of the
program, a TCP/IP socket is created (sock.SOCK_STREAM) and is then bind to port 5000.
The program listens for a connection. Notice that it is possible for the server to listen to
multiple clients, but of course, it can communicate with only one at any time. When the
client makes a connection this is accepted by the server. The server then reads a message
from the keyboard and sends to the client over the Wi-Fi link.
In this case study the TCP/UDP TEST TOOL apps (V4.2) from animod is used which is
available free of charge in the Play Store (see Figure 14.3).
● 243
Learning Python with Raspberry Pi
• Run the Android apps and select TCP CLIENT, set the Target IP to 192.168.1.202
and the port to 5000 and click CONNECT to connect to the server (see Figure
14.4)
• You should see a connection message on your Raspberry Pi screen and also the
IP address of the remote Android mobile phone (Figure 14.5). Now enter a mes-
sage and press Enter key. In this example, the message HELLO FROM RASP-
BERRY PI is sent to the client. Enter n to terminate the Raspberry Pi program.
Figure 14.6 shows the message displayed on the mobile phone.
● 244
Chapter 14 • Python and the Internet on Raspberry Pi 4
#==============================================
# SEND TEXT MESSAGES USING TCP/IP
# ===============================
#
# This is the TCP/IP server program. It receives
# text messages from the keyboard and sends to an
# Android mobile phone over a Wi-Fi link
#
# Author: Dogan Ibrahim
# File : tcpserver.py
# Date : August 2019
#================================================
import socket
yn = 'y'
while yn == 'y':
msg = raw_input("Enter your message: ")
client.send(msg)
● 245
Learning Python with Raspberry Pi
Aim: The aim of this project is to show how TCP/IP communication can be established with
a PC.
Background Information: In this case study the Raspberry Pi is the server and the PC
is the client. The programs on both sides are developed using the Python programming
language. Python 2.7 is used on the PC. If you do not have Python on your PC, you should
install it from the following web site:
https://www.python.org/downloads/release/python-2715/
Figure 14.8 shows the case study setup where the Raspberry Pi and the PC communicate
over a Wi-Fi router.
Raspberry Pi Program Listing: The Raspberry Pi program is similar to the one given in
Figure 14.7. It is modified slightly by adding a few lines to send and receive messages from
the client. The Raspberry Pi program listing (program: tcpserver2.py) is shown in Figure
14.9.
#==============================================
# TCP/IP SERVER
# =============
#
# This is the TCP/IP server program on Raspberry Pi.
# The program exchanges text messages with the Python
# program running on the PC.
#
# Author: Dogan Ibrahim
● 246
Chapter 14 • Python and the Internet on Raspberry Pi 4
# File : tcpserver2.py
# Date : August 2019
#================================================
import socket
try:
while True:
msg = raw_input(“Message to send: “)
client.send(msg)
data = client.recv(1024)
print(“Received msg:", data)
except KeyboardInterrupt:
print(“\nClosing connection to client")
sock.close()
PC Program Listing: The PC program listing is shown in Figure 14.10 (program: client.
py). The program creates a socket and connects to the server. Then, messages are ex-
changed between the client and the server.
#=============================================================
# TCP/IP CLIENT
# =============
#
# This is the client program on the PC.The program exchanges
# messages with the server on the Raspberry Pi
#
# Author: Dogan Ibrahim
# File : client.py
# Date : August 2019
#=============================================================
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((“192.168.1.202", 5000))
try:
while True:
● 247
Learning Python with Raspberry Pi
msg = sock.recv(1024)
print(“Received message: “, msg)
data = raw_input(“Enter message to send: “)
sock.send(data)
except KeyboardInterrupt:
print(“Closing connection to server")
sock.close()
Note: You may find that after exiting the program you may not be able to run it again. This
is because the socket stays open for about 30 seconds and the error message saying that
the Address is already in use may be displayed. You can check the state of the port with
the following command:
If the display includes the text ESTABLISHED then it means that the socket has not been
closed properly and you will have to restart your Raspberry Pi to run the program again. If
on the other hand, you see the message with TIME_WAIT then you should wait about 30
seconds before re-starting the program.
● 248
Chapter 14 • Python and the Internet on Raspberry Pi 4
Aim: The aim of this project is to show how an LED on the Raspberry Pi can be controlled
from an Android mobile phone by sending commands using the TCP/IP protocol over an
Wi-Fi link.
Background Information: In this case study the Raspberry Pi is the server and the mo-
bile phone is a client. Figure 14.12 shows the case study setup.
Raspberry Pi Program Listing: Figure 14.13 shows the program listing (program:
serverled.py). As in the previous program, a socket is created and port 5000 is used. The
server waits for a connection from the client and then accepts the connection. It then waits
to receive a command from the client. If the command is ON then the LED is turned ON. If
on the other hand the command is OFF then the LED is turned OFF. Sending command X
terminates the server connection.
#=============================================================
# CONTROL LED FROM MOBILE PHONE
# =============================
#
# In this program TCP/IP is used where Raspberry Pi is the
# server and mobile phone is the client. An LED connected to
# Raspberry Pi is controlled from mobile phone
#
# Author: Dogan Ibrahim
# File : serverled.py
# Date : August 2019
#===============================================================
● 249
Learning Python with Raspberry Pi
import socket
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.OUT)
print("Closing connection")
GPIO.cleanup()
sock.close()
The program is tested using the Android apps TCP/UDP TEST TOOL used in the previous
project. The server program started, then the client is started. Figure 14.14 shows sending
the ON command to turn ON the LED.
● 250
Chapter 14 • Python and the Internet on Raspberry Pi 4
Server
• Create a socket
• Bind the socket to a port with your IP address
• Wait to receive data from a client
• Exchange data (send and receive data) with the client (if required)
• Close the socket
Client
• Create a socket
• Send data to the server
• Exchange data (send and receive data) with the server (if required)
• Close the socket
Note that since there is no connection, the client does not know whether the server is there
or not. The client may send data but the server may not be there to receive this data in
which case the data will be lost. If the client waits to receive data and the server is not
available to send data then the client may have to wait forever. For this reason, we usually
specify a timeout in the client software.
● 251
Learning Python with Raspberry Pi
In the examples in this chapter, the server is the Raspberry Pi, while the client is a PC or a
mobile phone.
14.4.1 Case Study 32 – Sending a Text Message to a Mobile Phone Using UDP
Description: In this case study a UDP based communication is established with an Android
mobile phone. The program reads text messages from the keyboard and sends to the mo-
bile phone.
Aim: The aim of this project is to show how UDP communication can be established with
an Android mobile phone.
Background Information: Figure 14.2 shows the case study setup where the Raspberry
Pi and mobile phone communicate over a Wi-Fi router.
Raspberry Pi Program Listing: In this case study Raspberry Pi is the server and the
mobile phone is the client. Figure 14.15 shows the Raspberry Pi program listing (program:
udpserver.py). At the beginning of the program a UDP socket is created (sock.SOCK_
DGRAM) and is then bind to port 2000. The server program then reads text messages sent
from the mobile phone and displays on the screen. Messages sent by Raspberry Pi are
displayed on the mobile phone.
#==============================================
# SEND TEXT MESSAGES USING UDP
# ============================
#
# This is the UDP server program on Raspberry Pi.
# The program exchanges text messages with an Android
# mobile phone
#
# Author: Dogan Ibrahim
# File : udpserver.py
# Date : August 2019
#================================================
import socket
try:
while True:
data, addr = sock.recvfrom(1024)
print(“Received msg:", data)
msg = raw_input(“Message to send: “)
sock.sendto(msg, addr)
except KeyboardInterrupt:
● 252
Chapter 14 • Python and the Internet on Raspberry Pi 4
The program is tested using the Android apps TCP/UDP TEST TOOL and selecting UDP.
The steps to test the program are as follows:
• Start the mobile phone apps and set the target IP to 192.168.1.202, target port
to 2000, and local port to 5000.
• Write a message on mobile phone apps and click SEND. The message will be
displayed on the Raspberry Pi screen.
• Write a message on Raspberry Pi and this message will be displayed on the mo-
bile phone
Figure 14.16 and Figure 14.17 show example displays on the mobile phone and Raspberry
Pi respectively.
● 253
Learning Python with Raspberry Pi
Aim: The aim of this project is to show how an LED on the Raspberry Pi can be controlled
from an Android mobile phone by sending commands using the UDP protocol over a Wi-Fi
link.
Background Information: In this case study the Raspberry Pi is the server and the mo-
bile phone is a client. Figure 14.12 shows the case study setup.
Raspberry Pi Program Listing: Figure 14.18 shows the program listing (program: ud-
pled.py). As in the previous program, a socket is created the server waits to receive com-
mands from a client to control the LED. If the command is ON then the LED is turned ON.
If on the other hand, the command is OFF, the LED is turned OFF. Command X terminates
the server program.
#=============================================================
# CONTROL LED FROM MOBILE PHONE
# =============================
#
# In this program UDP is used where Raspberry Pi is the
# server and mobile phone is the client. An LED connected to
# Raspberry Pi is controlled from mobile phone
#
# Author: DOgan Ibrahim
# File : udpled.py
# Date : August 2019
#===============================================================
import socket
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.OUT)
● 254
Chapter 14 • Python and the Internet on Raspberry Pi 4
sock.bind(("192.168.1.202", 2000))
print("Closing connection")
GPIO.cleanup()
sock.close()
The program can be tested using the TCP/UDP TEST TOOL apps on the mobile phone as
in the previous case study.
14.5 Using Flask to Create a Web Server to Control Raspberry Pi GPIO Ports
From the Internet
Flask is a simple micro-framework written in Python for Python. It is free of charge and can
be used to create a web server on Raspberry Pi to control its GPIO ports over the internet.
The nice advantage of Flask is that it does not require special tools or libraries, has no da-
tabase or any other third party libraries.
Flask should already be available in Python on your Raspberry Pi, but if not, it can be in-
stalled on Raspberry Pi with the following command:
It will be a good idea to create a new folder on your Raspberry Pi and store all of your flask
related documents there. Let's create a folder called MyFlask under our default directory
/home/pi:
pi@raspberrypi:~ $ cd MyFlask
We are now ready to create our first web server application using Flask. Use the nano editor
and create a file called test.py with the following lines in it:
● 255
Learning Python with Raspberry Pi
@app.route('/')
def index(): # run index when called
return 'Hello from Flask' # msg to display when run
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0') # listen on port 80
You should see messages similar to the ones shown in Figure 14.19.
Now, open a web browser from a computer connected to the same Wi-Fi router and enter
the IP address of your Raspberry Pi, in this example 192.168.1.202. You should see the
Hello from Flask message appear on a web page as shown in Figure 14.20.
We can now create an HTML page and pass variables from a Python program. create a
folder called templates under MyFlask, move to directory templates and create a file
called index.html with the following lines (notice that the variables inside the double curly
brackets will have data passed to them from the Python program):
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello from Flask</h1>
<h2>The time on the server is: {{ time }}</h2>
</body>
● 256
Chapter 14 • Python and the Internet on Raspberry Pi 4
app = Flask(__name__)
@app.route('/')
def index():
now = time.ctime()
DataToPass = {
'title' : "TESTING FLASK",
'time': now
}
return render_template('index.html', **DataToPass)
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0') # listen on port 80
Current date and time are obtained using function call time.ctime() and is stored in vari-
able now. Then, a dictionary called DataToPass is created and values of title and time are
stored in this dictionary. These values will be passed to the items in double curly brackets in
web page defined by index.html. When the function returns, variables inside the dictionary
are returned to the web browser through the dictionary.
Now, run program test.py, go to a web browser and enter the IP address of your Raspberry
Pi. You should see a display similar to the one shown in Figure 14.21.
Now that we have learned how to pass variables from a Python program to a web page we
can monitor the status of a GPIO pin, or control a GPIO pin from a web page.
Aim: The aim of this project is to show how an LED on the Raspberry Pi can be controlled
from web pages using Flask.
● 257
Learning Python with Raspberry Pi
HTML Template Program Listing: The HTML template index.html in folder /home/
pi/MyFlask/templates is simple and it consists of a title and two buttons: ON and OFF.
The title is in double curly brackets and therefore it expects data to be passed to it from
Python. Two buttons are defined called LED ON and LED OFF with green and red colours
respectively, the LED ON button having reference /LED/on and LED OFF having refer-
ence /LED/off. Figure 14.22 shows the program listing.
<head>
<title>{{ title }}</title>
</head>
<body>
<h3>
<a href="/LED/on"><button type="button"><font color="green">LED ON</
button></a>
<a href="/LED/off"><button type="button"><font color="red">LED OFF</
button></a>
</h3>
</body>
Raspberry Pi Program Listing: Figure 14.23 shows the Python program listing on Rasp-
berry Pi in folder /home/pi/MyFlask (program: test.py). The program has the basic
Flask type template as shown earlier with some additional code. Port pin GPIO 2 is config-
ured as an output and the LED is turned OFF at the beginning of the program. The title to
be passed to index.html is named LED CONTROL and function index is used to pass this
string. Notice that another app.route is created with parameters device and action. In
this example, the device is LED and its actions are on and off. Function action checks the
device and if it is LED then the actuator is set to LED. For every actuator, we must have
an action. If the action is on, the LED is turned ON by the statement GPIO.output(actu-
ator, GPIO.HIGH), otherwise, if the action is off, the LED is turned OFF.
#========================================================
# CONTROLLING LED FROM WEB PAGE
# =============================
#
# This program turns the LED ON or OFF from a web browser
# activated from any computer on the same Wi-Fi router as
# the Raspberry Pi. The LED is controlled by clicking
# buttons when the web page is started
#
# Author: Dogan Ibrahim
# File : test.py
# Date : August 2019
#=========================================================
● 258
Chapter 14 • Python and the Internet on Raspberry Pi 4
app=Flask(__name__)
#
# Define GPIO2 as output and turn OFF LED at beginning
#
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED = 2
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, 0)
@app.route('/')
def index():
DataToPass = {
'title': "LED CONTROL"
}
return render_template('index.html', **DataToPass)
@app.route("/<device>/<action>")
def action(device, action):
if device == "LED":
actuator = LED
if action == "on":
GPIO.output(actuator, GPIO.HIGH)
if action == "off":
GPIO.output(actuator, GPIO.LOW)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, port=80,host='0.0.0.0')
To run the program you should follow the steps given below:
• You should see a screen similar to the one shown in Figure 14.19
● 259
Learning Python with Raspberry Pi
• Activate a web browser from a computer connected to the same Wi-Fi router and
enter the IP address of your Raspberry Pi. As shown in Figure 14.24, you should
see two buttons to control the LED. Clicking the buttons turns the LED ON or OFF.
Modified Program
You could remove file index.html from the case study and use only test.py to control the
LED. The modified program (test2.py) is shown in Figure 14.25. To control the LED, you
should enter the following web commands after starting test2.py:
#========================================================
# CONTROLLING LED FROM WEB PAGE
# =============================
#
# This program turns the LED ON or OFF from a web browser
# activated from any computer on the same Wi-Fi router as
# the Raspberry Pi. The commands are (assuming that the IP
# address of Raspberry Pi is: 192.168.1.202):
#
# 192.168.1.202/LED/on turn LED ON
# 192.168.1.202/LED/off turn LED OFF
#
# Author: Dogan Ibrahim
# File : test2.py
# Date : August 2019
#=========================================================
from flask import Flask,render_template
import RPi.GPIO as GPIO
app=Flask(__name__)
#
# Define GPIO2 as output and turn OFF LED at beginning
● 260
Chapter 14 • Python and the Internet on Raspberry Pi 4
#
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED = 2
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, 0)
@app.route("/<device>/<action>")
def action(device, action):
if device == "LED":
actuator = LED
if action == "on":
GPIO.output(actuator, GPIO.HIGH)
return "LED turned ON"
if action == "off":
GPIO.output(actuator, GPIO.LOW)
return "LED turned OFF"
if __name__ == '__main__':
app.run(debug=True, port=80,host='0.0.0.0')
The modified program displays messages LED turned ON and LED turned OFF. Figure 14.26
shows the web command to turn ON the LED.
14.6 Summary
In this chapter, we have learned how to develop programs to communicate with the exter-
nal world over Wi-Fi. We have also learned how to control the GPIO from a web page. In the
next chapter, we shall be looking at the Bluetooth and see how we can develop programs
to communicate using Bluetooth.
● 261
Learning Python with Raspberry Pi
Chapter 15 • B
luetooth Communication on Raspberry Pi 4
Using Python
15.1 Overview
In the last chapter, we have seen how to communicate with the external world using Wi-
Fi. In this chapter, we will learn how to develop Python programs to communicate using
Bluetooth on our Raspberry Pi 4.
Bluetooth is commonly used to communicate with other devices. All smartphones nowa-
days support communication through Bluetooth. Bluetooth operates at 2.4GHz with data
rates lower than that of Wi-Fi. Bluetooth is not as secure as Wi-Fi but it is easier to use. The
power consumption of Bluetooth is lower compared to Wi-Fi and also it also has a shorter
range.
The following commands can be sent from the Android mobile phone to control the LED:
Aim: The aim of this project is to show how the Bluetooth of the Raspberry Pi 4 can be
used in a Python program.
Background Information: Figure 15.1 shows the project setup. An LED is connected to
GPIO 2 through a current limiting resistor.
In this case study, we shall be sending commands from an Android mobile phone to our
Raspberry Pi 4. We must, therefore, first of all, enable Bluetooth from the Settings menu
on our Android device.
● 262
Chapter 15 • Bluetooth Communication on Raspberry Pi 4 Using Python
There are two ways you can enable Bluetooth on the Raspberry Pi 4: using graphical desk-
top (GUI mode), or using the command mode.
• Start the VNC server on your Raspberry Pi 4 and login using the VNC Viewer.
• Click on the blue Bluetooth icon on your Raspberry Pi 4 screen at the top right-
hand side, and turn Bluetooth ON, if it is not already ON. Then, select Make
Discoverable. You should see the Bluetooth icon flashing.
• You should now see the message Connected Successfully on your Raspberry
Pi 4
• Start the Bluetooth tool on your Raspberry Pi 3 from the command mode:
pi@raspberrypi:~ $ bluetoothctl
● 263
Learning Python with Raspberry Pi
[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# discoverable on
• Scan for nearby Bluetooth devices, you may have to wait several minutes:
[bluetooth]# scan on
• Enter command devices to see nearby Bluetooth devices (see Figure 15.3).
Make a note of the MAC address of the device you wish to connect to (Android
mobile phone in this case study) as we will be using this address to connect to
the device. An example is shown in Figure 15.3:
[Bluetooth]# devices
In this example our mobile phone is MyAndoid and the Bluetooth MAC address
is: B4:CD:27:15:68:7B
● 264
Chapter 15 • Bluetooth Communication on Raspberry Pi 4 Using Python
You can find the Bluetooth MAC address of your Raspberry Pi 4 by entering the
following command:
You can change the Bluetooth broadcast name by the following command:
You can find the Bluetooth MAC address of your Android phone as follows:
• Add –C at the end of the ExecStart= line. Also add another line after the Exec-
Start line. The final two lines should look like:
ExecStart=/usr/lib/bluetooth/bluetoothd -C
ExecStartPost=/usr/bin/sdptool add SP
● 265
Learning Python with Raspberry Pi
• Reboot Raspberry Pi 4:
Program Listing: Figure 15.5 shows the program listing of the project (program: blue.
py, do not call your program Bluetooth.py!). The Bluetooth code is similar to TCP/IP code.
At the beginning of the program modules socket, RPi.GPIO, and Bluetooth are imported to
the program. The LED port is defined and configured as output. The program then creates
a Bluetooth socket, binds and listens on this socket, and then waits to accept a connection.
The remainder of the program is executed in a loop where the program issues statement
ClientSock.recv and waits to read data from the mobile phone. The received data is de-
coded and the LED is turned ON or OFF as requested.
#=======================================================
# LED CONTROL BY BLUETOOTH
# ========================
#
# In this Case Study an LED is connected to GPIO 2.The
# LED is controlled by sending commands from an Android
● 266
Chapter 15 • Bluetooth Communication on Raspberry Pi 4 Using Python
#
# LED is on GPIO 2, configure as output and turn OFF
#
LED = 2
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, 0)
#
# Start of main program loop.Configure Bluetooth, create a
# port, listen for client connections, and accept connection
#
port = 1
ServerSock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
ServerSock.bind(("", port))
ServerSock.listen(1)
ClientSock, addr = ServerSock.accept()
#
# Now receive comamnds and decode
#
while True:
data = ClientSock.recv(1024) # receive command
if data[0] == 'L': # first char L?
if data[1] == '1': # second char 1?
GPIO.output(LED, 1) # turn ON LED
elif data[1] == '0': # second char 0?
GPIO.output(LED, 0) # turn OFF LED
● 267
Learning Python with Raspberry Pi
To send command L1, enter L1 and click Send ASCII as shown in Figure 15.6. Notice that
you must start the Raspberry Pi 4 program before starting the mobile application.
You could enter the program name in the following format inside file /etc/rc.local so that
the program starts automatically every time the Raspberry Pi 4 re-starts:
When you finish your project don't forget to remove the above line from file /etc/rc.local,
otherwise the program will run every time your Raspberry Pi 4 is re-started. You should
also shut down your Raspberry Pi 4 orderly instead of just removing the power cable. The
command to shut down orderly is:
15.3 Summary
In this chapter, the use of the Raspberry Pi 4 Bluetooth module from a Python program
has been described with a simple case study. Readers should find it easy to expand this
program for their own needs
● 268
Appendix A • Using wxPython Graphical User Interface
There are several graphics packages that can be used with the Python programming lan-
guage. The most important ones are Tkinter, wxPython, and PyQt. We have seen in an
earlier chapter how to use the Tkinter in graphics-based applications. In this Appendix we
shall be looking briefly at the details of wxPython with some simple examples. Interested
readers can get further information on wxPython from the following web site. There are also
many example codes and tutorials on wxPython on the internet.:
www.wxpython.org
wxPython is an easy to use Graphical User Interface package that supports buttons, win-
dows, slides, spinboxes, paintboxes, and many other widgets. wxPython is basically a Py-
thon wrapper that was released in 1998, so it is well established and has been around for
very long time. wxPython includes large number of widgets. Interested readers can find out
about the various widgets in the following link:
https://wxpython.org/Phoenix/docs/html/gallery.html
In this Appendix, we will be using wxPython version 4, also known as the Phoenix release.
Earlier versions of wxPython were built for Python version 2, but version 4 is compatible
both with Python 2 and Python 3. To install wxPython on your Raspberry Pi, enter the
following command (Depending on your processor power, it may take a long time for this
command to complete):
import wx
class Interface(wx.Frame):
def setup(self):
● 269
Learning Python with Raspberry Pi
self.SetTitle("wxPython Application")
self.SetBackgroundColour('white')
self.Centre()
self.SetSize(300,400)
#
# Put your own Code here
#
if __name__ == '__main__':
app = wx.App()
Interface(None)
app.MainLoop()
Now that we have a template, we can create some example GUI based programs with
wxPython.
Solution 1
The program listing is shown in Figure A3 (program stext.py). The template is used and
our code is placed after the comment Put your own code here.
● 270
Appendix A • Using wxPython Graphical User Interface
wx.ALIGHN_LEFT
wx.ALIGHT_RIGHT
wx.ALIGN_CENTER
wx.ST_NO_AUTORESIZE
Here, the message is displayed at position (50, 50), in 10 point, Roman characters, Normal
style, and BOLD. Font has the following parameters:
import wx
class Interface(wx.Frame):
def setup(self):
self.panel=wx.Panel(self)
self.SetTitle("wxPython Application")
self.SetBackgroundColour('white')
self.Centre()
self.SetSize(300,300)
#
# Put your own Code here
#
text = wx.StaticText(self, label="Hello from wxPython",pos=(50,50))
font = wx.Font(10, wx.ROMAN, wx.NORMAL, wx.BOLD)
text.SetFont(font)
if __name__ == '__main__':
● 271
Learning Python with Raspberry Pi
app = wx.App()
Interface(None)
app.MainLoop()
Solution 2
Figure A.5 shows the program listing (program: button.py). In this program, the same
template as before is used but the background colour is set to yellow. When the button is
clicked, function OnClicked is called. This function implements a Static Text which dis-
plays the message I am clicked as shown in Figure A.6.
import wx
class Interface(wx.Frame):
def setup(self):
● 272
Appendix A • Using wxPython Graphical User Interface
self.panel=wx.Panel(self)
self.SetTitle("wxPython Application")
self.SetBackgroundColour('yellow')
self.Centre()
self.SetSize(400,400)
#
# Put your own Code here
#
butn = wx.Button(self, label = "Click Me", pos=(80,80))
butn.Bind(wx.EVT_BUTTON, self.OnClicked)
if __name__ == '__main__':
app = wx.App()
Interface(None)
app.MainLoop()
Example 3 – Slider
Write a program to display a slider between 1 and 100.
Solution 3
Figure A.7 shows the program listing (program: slider.py). A slider can be Horizontal or
Vertical. For example, a Horizontal slider has the following parameters:
● 273
Learning Python with Raspberry Pi
The style parameter can have the values shown in Table A.1.
If set, the slider will display tick marks across it. The spacing is governed
wx.SL_AUTOTICKS
by the setter method SetTickFreq.
If set, the slider will display labels for the minimum and maximum value,
wx.SL_LABELS and a read-only display of the current value. The current value might not
display on all platforms.
wx.SL_LEFT For a vertical slider, the ticks will be on the left of the slider.
wx.SL_RIGHT For a vertical slider, the ticks will be on the right of the slider.
wx.SL_TOP For a horizontal slider, the ticks will be on top of the slider.
import wx
class Interface(wx.Frame):
def setup(self):
self.panel=wx.Panel(self)
self.SetTitle("wxPython Application")
self.SetBackgroundColour('white')
self.Centre()
self.SetSize(300,300)
#
# Put your own Code here
#
slider = wx.Slider(self, 100, 25, 1, 100,
pos=(20,20),size=(250,-1),style=\
wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)
if __name__ == '__main__':
app = wx.App()
Interface(None)
app.MainLoop()
● 274
Appendix A • Using wxPython Graphical User Interface
We can bind an event to a slider and get the value of the slider in this event. This is shown
in the next example.
Solution 4
Figure A.9 shows the program listing (program: sliderevent.py). Function GetValue re-
turns the slider values (it actually returns the current slider value) as shown in the pro-
gram. An example display is shown in Figure A.10 where the slider positions are displayed
as the slider arm is moved.
import wx
class Interface(wx.Frame):
def setup(self):
self.panel=wx.Panel(self)
self.SetTitle("wxPython Application")
self.SetBackgroundColour('white')
self.Centre()
self.SetSize(300,300)
#
# Put your own Code here
#
slider = wx.Slider(self, 100, 25, 1, 100,
pos=(20,20),size=(250,-1),style=\
wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)
slider.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
● 275
Learning Python with Raspberry Pi
val = obj.GetValue()
print(val)
if __name__ == '__main__':
app = wx.App()
Interface(None)
app.MainLoop()
Description: In this case study, the CPU temperature of Raspberry Pi 4 is read every 5
seconds and is displayed on a graphical screen using wxPython.
Aim: The aim of this project is to show how an item (temperature in this case) can be dis-
played and updated at frequent intervals on a wxPython widget.
Background Information: There are several ways that the Raspberry Pi 4 CPU tempera-
ture can be obtained (e.g. see case study 12, chapter 8.4). In this case study, we will obtain
the CPU temperature using the following simple statements:
● 276
Appendix A • Using wxPython Graphical User Interface
Program Listing: In this program, we will create a timer that invokes a function called
GetTemperature every 5 seconds. The temperature is read, converted into string, letter
C added, and displayed by a Static Text widget. In addition, the heading CPU TEMPERA-
TURE: is displayed using another Static Text widget. Figure A.11 shows the program listing
(program: tempwidget.py). The output of the program is shown in Figure A.12.
import wx
from gpiozero import CPUTemperature
class Interface(wx.Frame):
def setup(self):
self.panel=wx.Panel(self)
self.SetTitle("RPI 4 CPU TEMPERATURE")
self.SetBackgroundColour('white')
self.Centre()
self.SetSize(400,450)
#
# Put your own Code here
#
# Create a timer, bind it to function OnTimer, and start the timer
# at every 10 seconds
#
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(5000)
#
# Create a Static Text to display a heading
#
t = wx.StaticText(self, label="CPU TEMPERATURE:", pos=(110,120))
fnt = wx.Font(10,wx.DECORATIVE, wx.NORMAL, wx.BOLD)
t.SetFont(fnt)
#
# Create a Static Text to display temperature
#
self.text = wx.StaticText(self, label='', pos=(100,150))
font = wx.Font(24, wx.ROMAN, wx.NORMAL, wx.BOLD)
self.text.SetFont(font)
● 277
Learning Python with Raspberry Pi
cpu = cpu.temperature
temp = str(cpu) + " C"
self.text.SetLabel(temp)
if __name__ == '__main__':
app = wx.App()
Interface(None)
app.MainLoop()
● 278
Appendix B • Object-oriented Programming
Traditional programming is procedural where programs are developed using block of state-
ments to manipulate the data. The new generation of programming is called object ori-
ented programming where data and functionality are combined and wrapped inside called
objects. Although procedural programming is still widely used, writing large programs is
easier and better suited to the object-oriented programming (OOP) techniques.
In OOP, classes and objects are the main concepts. Classes create new types, where ob-
jects are the instances of the classes. Classes can have functions called methods of the
class. Variables belonging to a class are called fields. The fields and methods of a class are
referred to as the attributes of that class.
Python supports both procedural and object-oriented programming. In this book, we have
programmed using only procedural techniques. In this appendix, we will be learning the
basic principles of OOP with Python. Interested readers can find many tutorials, books, and
articles on the internet.
class Car:
Methods are just like functions, except we have the additional variable called self. An ex-
ample is shown below:
class Car:
def msg(self):
print("Hello from class")
c = Car()
c.msg()
Initialization
We may want to initialize some variables when a class is created. This is done using double
underscores at the beginning and end of the name init and specifying the variable to be
initialized. An example is given below where model takes the value Mercedes. Notice in
this code that we do not call function init, this is done automatically:
● 279
Learning Python with Raspberry Pi
class Car:
def __init__(self, model):
self.model = model
def msg(self):
print("My car is: ", self.model)
c = Car("Mercedes")
c.msg()
Car("Mercedes").msg()
B.2 Variables
Variables in OOP can be class variables or object variables. Class variables are shared by all
instances of the class. Object variables, on the other hand, are local to each method in the
class. An example is given below:
class Car:
count = 0
def dec(self):
print("My car is: ", self.model)
Car.count -= 1
print(CAR.count)
def zero(self):
Car.count = 0
print(Car.count)
c = Car("Mercedes")
c.dec()
c.dec()
c.zero()
● 280
Appendix B • Object-oriented Programming
In this example, count is a class variable and is accessible from all methods of the class.
Running the program given the following display:
1
0
-1
0
B.3 Inheritance
OOP has the advantage that code can be re-used through what is called inheritance. Sup-
pose you want to write a program to keep track of professional employees and secretaries
in a firm. These people may have some common characteristics such as name, age, and
address. There are also some specific characteristics such as their salaries, training courses
they attended, etc. One way will be to write two independent classes and adding common
characteristics. Instead of this, we could create a common class and then have the profes-
sional employee class and secretaries class inherit from this common class. The advantage
of using this method through inheritance is that any changes to the common class will be
automatically reflected in both classes.
Example 1
Write an OOP to have two classes called Shape and Rectangle. Class Shape will accept
the sides of a polygon type shape from the keyboard as floating-point numbers. Class
Rectangle will inherit the sides from class Shape and calculate and display the area of a
rectangle.
Solution 1
Figure B1 shows the program listing (program: inheritoop.py). Class Shape has 2 meth-
ods: GetSides and DisplaySides. Method GetSides reads the sides of the shape, while
DisplaySides displays the sides of the shape. Class Rectangle inherits the sides as a and
b and calculates the area by multiplying a with b. The area is then displayed on the screen
as shown in Figure B.2.
class Shape:
def __init__(self, number_of_sides):
self.no = number_of_sides
self.sides = [0 for i in range(self.no)]
print("Number of sides=%d" %(self.no))
def GetSides(self):
for i in range(self.no):
x = float(raw_input("Enter side %d: " %(i+1)))
self.sides[i] = x
def DisplaySides(self):
● 281
Learning Python with Raspberry Pi
for i in range(self.no):
print("Side %f: " %(self.sides[i]))
class Rectangle(Shape):
def __init__(self):
Shape.__init__(self, 2)
def Area(self):
a, b = self.sides
area = a * b
print("Area of rectangle=%f" %area)
r=Rectangle()
r.GetSides()
r.DisplaySides()
r.Area()
● 282
INDEX
INDEX
A Expression operators 55
Active filter 214
Array operations 155 F
Array multiplication 156 Files 140
Attenuator design 100, 103 Flask 255
float 54
B for statement 66
Bar chart 129 frequency response 146
Bitwise operators 55
Blank lines 52 G
Bluetooth 262 GPIO 222
BJT transistor 203 Grid 180
break statement 69
Button 173 H
head 38
C HDMI 14
cal 36 High-pass filter 219
Check box 185
chmod 33 I
Collector feedback biasing 203 I2C 229
comments 52 Ifconfig 23
continue statement 68 Indentation 53
Copying arrays 157 Inductance 200
cp 36 int 54
CPU fan 16
CPU temperature 148 K
Critically damped mode 136 Keyboard input 64
CSI 14 Keyboard interrupt 109
D L
Data types 53 Label 170
date 36, 113 LCD 230
df 42 Linear algebraic equations 157
Dialogs 187 List variables 61
Dictionary variables 63 Logical operators 65
dpkg 40 long 54
DSI 14 low-pass active filter 214
ls 30
E
echo 37 M
Entry 179 man 35
Escape sequences 59 matplotlib 117
Ethernet 14 Matrix operations 155
Exceptions 106 Mathematical functions 55
● 283
Learning Python with Raspberry Pi
R V
Radio button 181 Variable names 51
RC transient circuit charging 130 vncserver 28
RC transient circuit discharging 132 Voltage divider biasing 205
Recursive functions 105
Resonance 196 W
Remote access 24 Web server 257
Reserved words 52 while statement 68
Resistive potential divider 76 whoami 39
Resistor colour code 70, 72 wxPython 269
RLC transient circuit 136
rm. 37 Z
rmdir 37 Zener diode 108
S
Series and parallel resistors 74
Serial port 238
SPI 233
Slider 190
SSH 24
● 284
For Electronics Engineers
Learning Python with
Raspberry Pi
Full program listings of all the programs used in the book are
available at the Elektor website of the book. Readers should be
able just to copy and use these programs in their Raspberry Pi
Elektor International Media BV
projects without any modifications.
www.elektor.com
● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEA
IGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● D
HARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN
N ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEA
SIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● D