Coding Python
Coding Python
Authors
Author
Larry Lutz
© Copyright 2018 - All rights reserved.
If you would like to share this book with another person, please purchase an additional copy for each
recipient. Thank you for respecting the hard work of this author. Otherwise, the transmission,
duplication or reproduction of any of the following work including specific information will be
considered an illegal act irrespective of if it is done electronically or in print. This extends to creating a
secondary or tertiary copy of the work or a recorded copy and is only allowed with an express written
consent from the Publisher. All additional right reserved.
INTRODUCTION TO PYTHON
UTILITIES OF PYTHON
CONFIGURING PYTHON ENVIRONMENT
BASICS OF PYTHON
VARIABLES, STRING AND OPERATORS
MATHEMATICAL ASPECTS
DATA TYPES
LISTS AND TUPLES
DICTIONARIES
CONTROL STATEMENTS
FUNCTIONS AND MODULES
FILE INPUT-OUTPUT
OBJECT-ORIENTED PROGRAMMING
CODE OPTIMIZATION
USEFUL PYTHON LIBRARIES
RASPBERRY PI
CHAPTER 1
INTRODUCTION TO RASPBERRY PI
CHAPTER 2
GETTING STARTED WITH THE RASPBERRY PI
CHAPTER 3
INTRODUCTION TO EMBEDDED LINUX
CHAPTER 4
WORKING WITH ELECTRONICS
CHAPTER 5
PROGRAMMING A RASPBERRY PI
CHAPTER 6
INPUT AND OUTPUT ON A RASPBERRY PI
CHAPTER 7
INTRODUCTION TO COMMUNICATION PROTOCOLS
CHAPTER 8
PYTHON PROGRAMMING FOR THE RASPBERRY PI
CHAPTER 9
FINAL PROJECT
Index
v Chapter 1: Introduction to Python
Introduction
History
Script Language
Advantages
Disadvantages
An algorithm can be considered as the logic of the program. Each program is written with some
type of algorithm. After the development of the program, program testing is done to measure the
performance of the program for different inputs. Proper documentation is done with the development of
each program for future reference.
To develop any program in the software industry, there are mainly seven stages to follow:
Requirement Gathering
Analysing problem
Decide Input and Output
Developing Algorithm
Program implementation
Testing and Debugging
Documentation
To find a solution to any software problem, design approaches play a very important role. It is
essential to represent the solution for large complex systems. There are various design approaches
evolved over the time in the software domain.
Top-Down Approach:
The system consists of various components in a proper hierarchy. In this design approach,
designing is done from top-level components to bottom level components.
This is the reverse designing approach to Top-down approach. Bottom Level components are
designed first and then move to top-level components. Bottom level components are also called base
components of the system.
Modular Approach:
This approach is aimed at segregating the whole system into different modules. Each module is
implemented differently using a program. Modules are well defined in terms of input and output, it
provides flexibility to modify in future and independent testing. Every language is designed on the
basis of its requirement and purpose. Like FORTRAN was developed to solve problems related to
science and mathematics, COBOL was developed to find solutions related to business applications.
Python interpreter development was started by Guido van Rossum as his hobby project as a
successor to ABC Language, but today because of its simplicity and pseudo code characteristics, it has
a million users all around the world. Python interpreter is not only able to solve complex programming
problems, but able to target problems of the 21 st century in the field of automation, web development,
desktop application, and many more.
History:
Python was one of the hobby projects for Guido van Rossum after his regular job in the late
1980s. The irrelevant project name was because of his fondness towards Monty Python's Flying Circus.
His intention was to develop a simple and readable code interpreter. Guido released the first version of
Python interpreter in the year 1991. Today, there are many python versions available in the series
names of 2.X to 3.X and still, latest version are releasing every year.
The major features included were Unicode support and Memory Management with a cyclic-
detection garbage collection system. In the year 2008, Python 3.0 was released with major
functionalities backward compatibility with python 2.6 and python 2.7 version.
Scripting Language:
Python is a high level and general purpose programming language.
You might have seen people considering it as a scripting language because they understand
script and program as the same.
They often use the word “Script” instead of “Program.” Python has become the tool for
many people around the world because of it's easy to use characteristics. Sometimes Python
users also infer “python file” by using the term “script.”
Commonly, Python is an Object-oriented programming language that inherits all the
advantages of OOP and dividing a program into procedures, modules, and functions. Its
object-oriented orientation makes it useful for the scripting purpose.
Advantages:
Python language is widely used all over the globe. Its popularity is because of its characteristics
and many advantages attached to it. Some of the major advantages are as follows:
Python’s design philosophy focusses more on the readability of the code. Its pseudo code nature
makes it easy-to-learn for beginners who want to learn to programme.
Any non-computer science background can understand by reading the code because of its simple
English words used as Keywords. Python's code is also very easy-to-maintain.
Python's package is available with many standard libraries, which are an aid in solving diverse
programming challenges. These libraries are also cross-platform compatible. It allows you to port your
Python code to any platform such as Windows, Mac, and Linux.
Python Interactive is very popular and a quick Python interpreter. It helps you to test and run code
snippets pretty quick. When you are in the middle of a large program and need to test some code, you
just need to run Python interpreter and run into it.
Python avails many libraries for the development of GUI such as Tkinter, Wx, and PyQt, etcetera.
These libraries support system calls and cross-platform compatibility.
Python also allows you to include low-level programming modules like C, C++, and Java in your
code that aid in the development of efficient and fast solutions. Because of its extendable nature, you
can have all the advantages of a low-level programming language with quick development.
Disadvantages:
With the numerous advantages of using the Python language over the year in various fields.
there are also some downsides of using it for some applications.
Python is a high-level language, so its execution speed is not as fast as compared to C and
C++. But over time, Python libraries are optimized to use it in applications where timing is
the important aspect.
For GUI programming, Python libraries are optimized enough to provide service almost as
fast as C and C++.
Exercise
Python’s source code is available to use under GNU General Public License. Today, Python
package comes pre-installed with Macintosh and Linux operating system. Because of its various
impactful characteristics, Python is used in many software solutions and applied to solve real-time
problems with profit generating solutions.
Big giants like Google, Netflix, and Dropbox have used the Python language in many ways. The
backend process of Google web search engine is written in Python. The world's largest collection of
videos, Youtube, is completely developed in Python. The Dropbox used Python in storage services and
for its desktop applications.
Utilities:
Besides the well-designed characteristics of Python, Python is used to solve many real-world
problems in the various domains. Programmers also use it for solving their day-to-day life problems. In
fact, Python applications are nearly unlimited as it can be used from simple gaming applications to
high-end complex aerospace and robotics solutions.
Some of the present and emerging applications as described in the following sections:
Python has a rich set of GUI libraries that could be used developing front-end for applications.
These GUIs are supported by Macintosh, Windows, and Linux distributions. Tk library is included
automatically with Python 2.0 named Tkinter. This library could also be extended by PMW library to
use enhanced widgets in front-end. Qt GUI library is also available with name PyQt and Swing GUI
with name Jython. These GUIs are not only available limited to computer applications, but also in
embedded applications.
Web-Scripting:
Python has made the complex client-server programming really very simple by the use of
standard libraries available with it. These modules let programmers to implement networking task
pretty quick. Python scripts also help in creating sockets and data communication over it. File
transferring using FTP and parsing XML data is easy-to-implement. There are available methods for
network communications for sending, receiving, parsing, and creating e-mails.
Database Programming:
For the demand of accessing the data from the database traditionally, Python also avails features
of database accessing and programming for the commonly used databases like MySQL, Oracle, ODBC,
and Sybase. It is also considered as the portable database API as it provides the code portability for
database just by changing vendor interface.
Python is able to target problems of complex math as well as scientific domain that has not been
targeted by any programming language traditionally. NumPy is the very popularly used numeric
library, which allows the programmer to solve quick numeric problems in programming application. It
is one of the Python's compelling utilities.
There are many more standard libraries available for numeric computations and representation
of numeric data in 3-D plot models. SciPy and ScientificPython are popular libraries used as scientific
tools that differentiate Python from the other traditional programming languages. These are well
optimized in terms of processing the complex algorithms and math. Due to this reason. NumPy is the
Gaming Application:
Gaming software industries also take advantage of Python libraries such as PyGame, PySoy,
Pyglet, and others. Some libraries also include multimedia functionalities with it.
Embedded Applications:
Image processing and Data-mining are the emerging fields in the 21 st century. There are various
interfaces available that are being used for image processing applications like PyOpenGL, OpenCV,
and Maya. Data-mining deals with the large set of data and applying mathematical calculations for
generating results, and Python is a great tool for the same. Matplotlib and Mayavi are the common
interfaces available modules for data mining and visualization.
Exercise
Answer:
Shallow copy : When creating a new instance type, use shallow copy and keep
the value copied to the new instance. Shallow copies are used to copy
reference pointers in the same way as copy values. These references point to
the original object, and changes to the members of the class will also affect
the original copy. Using shallow copies reduces program execution time and
depends on the size of the data used.
Deep copy: Deep copy is used to store the copied values. With deep copy,
reference pointers to objects are not copied. It contains a reference to an
object and a new object pointed to by another object. Changes made to the
original copy do not affect the use of other copies of the object. Deep
replication slows program execution because copies of each invoked object
are created.
Corel
D-Link
Eve – Online
Forecast watch
Frequentis
HP
Honeywell
Configuring Python Environment
Before you start with the Python programming, you need Python on
your computer. You can check whether Python is already installed on your
computer or not. Open your command line windows and type "python" and
hit enter, if it displays any response from Python interpreter with the version
number then you don't need to download Python on your system.
Getting python:
The most up to date and previous version of Python is available on the
official Python website with source code, binaries, and all preferable
documentation. You can visit the official Python website at
https://www.python.org/ .
Installing Python:
Python is available for wide variety of platforms. You need to
download the binary file of Python version according to the platform and
then install Python on your computer.
If the binary code is not available for your platform, then you can use a
C compiler to compile the source code manually. Compilation of source code
gives more flexibility in terms of choice of features.
Windows Installation:
Python interpreter is not pre-installed in Windows, but it does not mean that
Windows users won't find a useful, flexible programming language.
However, installing the latest version of Python is not a trivial matter, so you
make sure to find the right tool for the task.
Python 2 Installation:
You can install Python 2 version from the official Python site
https://www.python.org/downloads/ . The latest version is also available but
if you want to download an older version then you can do it by downloading
its binary code. Click on Download Python 2.7.14 so it will start
downloading binary code on your computer automatically.
While downloading, the installer will set a path variable for you.
Download and Run the installer.
Select Install for all users and click on Next button.
You can install and work on both Python version 2 and 3 simultaneously on
your system. But when you type "Python" at the command prompt, it will
point to Python 2.7.
To remove it, you can change the name of Python folder, "python" for Python
2 and "python3" for Python 3 in the directory where you have installed
Python on the computer. After changing the name in the installed directory
you can check version in the command line.
If you are not satisfied with this solution, then you can reorder the
environment variable and use Python version according to the need of your
project.
Linux Installation:
You can install and setup Python by using Terminal, which is non-graphical.
Instead of selecting options from GUI screen and click on buttons, you need
to write commands and receive feedback from your computer.
Ubuntu 16.04 comes with the Python 2 and Python 3 pre-installed. To make
sure that you have the latest version of Python or not, you can update and
upgrade your computer with apt-get command.
The -y flag will confirm that you are installing all the projects in the system,
but depending on your Linux version, you need to select additional prompts
during system updates and upgrades.
If you are using an older version of Ubuntu and other Linux based operating
systems in which Python is not pre-installed, then you can use the following
command for installing Python:
You can check the version of installed Python by typing the command:
$ python2.7 –V
You will receive output with the Python version in the terminal window. The
output will look like this:
Python 2.7.14
Macintosh Installation:
The installation process of Python is somewhat similar in the Linux and
Macintosh. Macintosh comes with the pre-installed Python version. You can
check the version of Python by typing:
$ python –V or
$ python --version
If you are installing Python again or need to install the latest version of
Python, then you need to type the following command:
Python IDEs:
There are many Python IDE (Integrated Development Environment) that are
useful for you to work on a Python project. IDE can easily handle big
projects that have hundreds of small modules. The main focus while working
on IDE is on simplicity and ease of use. It provides a graphical interface to
the programmer for their ease. Some of them are very lightweight and fast
while working on Python projects. Here is the list of IDEs which are
compatible with Windows, Linux, and Mac:
IDLE
PyDev
Eric
LiClipse
NetBeans
Pycharm
Pyscripter
Spyder
Python tools for Visual Studio
There are some of the IDEs which comes with the integrated GUI builder. It
is useful when you are working on any Python based GUI projects. They are:
MonkeyStudio
Xcode
Visual Python
PythonCard
Exercise
You can either use Python Interactive Mode to write your first Hello, World
program and it will provide a prompt output or by using the traditional
method for writing program in a text editor. Here both ways have been
explained:
Let’s get started,
Open any of your favourite text editor such as Notepad, VI editor, or VIM
etcetera. Write the following program in it and save it with the name
“helloWorld.py”.
To run the program, you need to open Terminal (in Linux) or Command line
window (in Windows). Change your current directory to the program file
folder and run following command:
$ python helloWorld.py
Let’s start with it. Open Terminal in your system and Type following:
$ python
With this command, you are calling Python interpreter to run in
interactive mode. Write following one line Hello, World program and then
press Enter.
This method of running your Hello, World program is just for your
experience with Python Interactive. To write any further programs, we will
be using traditional text editor method.
Let’s understand more in-detail about the steps and the program that we
have run.
To get a brief of the one-liner program. Break it into two parts: one is
print and the other one is "Hello, World." Print is a function call, similar to
the printf function in C. It displays data to output screen in string form and
"Hello, World" is a string which is an argument to print function. As of now,
you should not think too much about strings and function. These are
explained well in the following chapters.
Python Interactive:
The interactive window of Python is simple and also very useful for the
programmer during the development of Python code. It is similar to sitting in-
front of Python interpreter and getting results for each Python expression.
This aids programmers in experimenting and testing of code snippets.
To wake up Python interactive mode in your system, you just need to type
Python and hit enter in Terminal. It will next display a few lines with details
of python interpreter like version number and others and prompt your for
input with “>>>” As showing in the following:
When you work with Python interactively, it will give the result of each
expression in the next line as you type it and press Enter key. Due to this, it is
not required for you to put a print command in Python interactive mode. Here
in the following expression: x = 10, which represents x is assigned with
integer value 10 and on pressing Enter key, its value is being displayed.
Similarly for str = "Hello, World". The string "Hello, World" is assigned to
str variable.
Now It is certainly clear the reason behind the use of Python interactive
mode. Being a smart programmer, you can experiment with a few lines of
Python commands to see the behaviour of Python when working with large
programs.
1. raw_input() or input() :
This function is similar to the scanf function in C. It is used
to take input from the user.
2. print():
This function is useful for printing the data to the output
windows in string form.
3. len():
This function is used to get the length of the object. Here the
object can be a string, a tuple, or a list and the object is
passed as an argument in the len function.
4. str():
This function is useful for converting the type of object.
Object version is changed to string type.
5. abs()
This is a mathematical function and it is same as the absolute
maths function. It provides the absolute value of the object.
6. help()
This function is very useful for getting information of any
function, method or keyword. If no object is passed in the
function, It will prompt to a Python help window, and if any
string is passed through it as an object, then it will search for
that string in the documentation and shows relevant function
or data.
7. min():
This function gives the smallest element in an iterative
object or it will give the smallest element when multiple
objects are passed.
8. max()
this function gives the largest element in an iterative object
or it will give the largest element when multiple objects are
passed.
9. all()
This function returns a Boolean value that is either True or
False. It gives True as the return value when all the elements
in the iterative object elements are true.
10. any():
This function also returns a Boolean value. It gives True as a
return value when any of the elements in the iterative object
elements are true.
Exercise
Code:
Output:
2. Create a python program to take input string from the user and
display it on output window.
Code:
Output:
Variables, String and Operators
Variables are the identifier which reserve location in the memory to
store values. It means when you are creating any variable, it is creating some
space in the memory.
The interpreter will allocate memory based on the data type of variable,
and data type defines the type of value the variable holds. The variables can
hold integer, character, string, and other data types
Variables(Values):
A value is a small unit of the program like letter and number, which is
used while assigning to the variable. We don't need to declare a variable
before assigning value. Python interpreter will automatically assign the type
of data while assigning the value to that variable.
The = sign is used for assignment. The left part of the equal sign is a
variable and right part of the equal sign is a value which is assigned to that
variable.
Code:
Output:
In the above code, the variables are "name”, “age", and "height" and we
are assigning the values to each variable. The variable name is storing the
character values, age is storing integer value, and height is storing the float
value. We don't need to declare the data type of variable; it will automatically
assign data type according to the assigned values.
Data Types:
A variable can hold different types of data in the memory. For storing a
name, a string is used, age in numeric value, height in float value. There are
some standard data types in Python programming language that you can use
for storing data in the memory.
String
Tuple
Dictionary
Numbers
List
Strings:
In the Python language, a string is a sequence of text and bytes. A string
starts with a single and double quote. You can also use single quotes within
double quotes and vice versa.
Python provides us the very simple method to cut the substring from a
string. It is known as string slicing. You can separate two indices by the
colon (:).
Code:
Output:
Update String:
Reassigning an existing string with new string will give you updated
string. The new string can be related to the previous string or completely new
string.
Code:
Output:
Escape Character:
Tuples:
A tuple is another type of data type which consists of series of comma-
separated values. Like strings, tuples are also immutable and enclosed in the
parenthesis with holding mix data type. Like strings, tuples can also be sliced.
When we slice tuple, it will create a new tuple, but it does not change the
original tuple. Addition(+) Operator is used to create a new tuple that is
concatenation of more than two tuples. We use * operator to repeat a tuple.
Code:
Output:
Dictionary:
In the Python language, dictionary data type is like a hash table. It
works like an associative array and hashes similar to Perl. Basically, it
consists of key-value pairs. A dictionary key is generally a number and a
string but it can be of any Python data type. The values can be like arbitrary
Python object.
Code:
Output:
Numbers:
The Number data type is used to store numerical values like 1, 2,
etcetera. It is used when programmers need to assign a numeric value to the
variable. For example,
age = 25
height = 6
Del is used when you want to delete a single or multiple objects. For
example,
del age
Generally, there are four types of numeric value that you can use in python :
Basic Operator:
The operators are symbols which are used to perform mathematical and
logical operations. Operands are the values on which the operator is applied
while operations.
Types of Operators:
Assignment operator
Logical operator
Arithmetic operator
Relational operator
Bitwise operator
Identify operator
Membership operator
Arithmetic Operator:
Symbol Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponent
// Floor Division
Logical Operator:
Symbol Operator Name
or Logical OR
and Logical AND
Not Logical NOT
Assignment Operator:
Symbol Operator Name
= Equal
+= Add AND
-+ Subtract AND
*= Multiply AND
/= Division AND
%= Modulus AND
**= Exponent AND
//= Floor Division AND
Relational Operator:
Symbol Operator Name
== Double Equal
!= or <> Not Equal To
> Greater Than
< Less Than
<= Less Than Equal To
>= Greater Than Equal To
Bitwise Operator:
Identity Operator:
Symbol Operator Name
Is Is
Is not Is not
Membership operator:
Symbol Operator Name
In In
Not in Not in
Exercise
Code:
Output:
Code:
Output:
Types of Operators:
Assignment operator
Logical operator
Arithmetic operator
Relational operator
Bitwise operator
Identify operator
Membership operator
Mathematical Aspects
Introduction:
Mathematics is one of the integral parts of programming. Be it a simple
maths operation or writing a complex mathematical algorithm for software,
python is always ahead in terms of its speed and quick coding practices.
Mathematical data is taken as the data object in the Python language. In fact,
objects are the building block of Python programming. We will be learning
the usage of basic mathematical functions which are frequently used during
Python programming. There are many popular and optimized mathematics
and scientific libraries available, which are either built-in or can be imported
into your Python code to use.
Code:
Output:
In the following sections, we will look more into its usage and prototype:
1. Numeric-theoretic Functions:
This module already comes with a built-in Python version
2.7. It is similar to C math library. These functions take one
or two objects as data, but it does not take any complex
number as objects. Cmath is another Python librarycmath,
which is available for complex number math operations.
math.copysign(a, b): This function is used to change the sign of the number.
It returns data of 'a' with the sign of 'b'.
Code:
Output:
Code:
Output:
Trigonometric:
math.sin(a)
math.cos(a)
math.tan(a)
Hyperbolic:
math.sinh(a)
math.cosh(a)
math.tan(a)
Code:
Output:
4. Special Functions:
Other than the standard maths functions, Python also provides special
mathematical functions. They are as following:
math.gamma(a):
math.lgamma(a):
math.erf(a):
math.erfc(a):
Till now, we have discussed the basic mathematics function. Python is also
rich with its advanced mathematical capabilities. Its richness also attracted
people from research and scientific backgrounds. NumPy, SciPy, and
Matplotlib are very well contained and optimized libraries. Every Python
programmer must be well versed with these libraries to enhance their Python
programming skills. We will learn more in-depth about these libraries and its
utilities.
NumPy Library :
NumPy is a short name for Numeric or Numerical Python and developed as
the open source project by Travis Oliphant. The key idea behind the
development of this library was to handle multi-dimensional data (array) in
Python. It was developed by merging two predecessor libraries, one is
Numeric and another is Numarray.
There are following methods and functions which are available in NumPy
library.
1. Numpy.zeros(a,b,c)
The function creates a new array with all elements entries as
zero. Where
2. Numpy.ones(a,b,c)
This function creates a new array with all elements entries as
one and data objects are same as of zeros function.
3. Numpy.full(a,b,c,d)
This function returns a newly created array and provides
shape and value where
Code:
Output:
SciPy Library :
SciPy name stands for Scientific Python. It is an extension of Python NumPy
library to enhance its processing and algorithmic capabilities. As NumPy
provides methods for creating multi-dimensional data and its processing in
Python, SciPy is one step ahead. It is specifically built for implementation of
scientific processing like writing mathematical algorithms application.
Because of it, Python is a perfect language if you are programming for niche
applications such as scientific, web, and desktop applications.
For installing SciPy in your system, you need following commands in your
Terminal window.
It is time to go deep into the SciPy library, We will understand some basic
functions one-by-one and quickly program it. Let’s get started:
Code:
Output:
Matplotlib Library:
With the enhanced capabilities of Python using NumPy and SciPy. Matplotlib
is one of the alternatives of MATLAB software for representation of data and
its analysis. With open-source nature Python, these libraries are well used
among data scientist and researcher.
You can use Matplotlib for plotting 2-dimensional and 3-dimensional data. It
also includes error charts, histogram and bar charts in just a few lines of
codes. It makes hard and complex data analysis very easy.
Exercise
where a = 10 and b = 5
Code:
Output:
2. Take an input array from the user and find its Fast-Fourier
transformation.
Code:
Output:
Output:
Data types
In Python, data takes the objects of different types of form – they are
either built-in objects provided by the Python language or created by the
programmer using Python classes or external language tools. Objects are just
pieces of memory used for storing values and set operations on that variable.
In the Python language, most of the work goes away as you don't need
to do object implementation before you start solving problems. It is always
best way to use built-in object instead of implementing your own object.
Built-in Objects:
Numbers:
Python object also includes the numbers and it contains integer,
floating-point numbers, complex numbers, decimal, rational numbers. It
supports mathematical operation. For example, plus sign (+) is used for
addition, star (*) is used for multiplication, and two stars (**) are sued for
exponentiation operation.
Code:
Besides the expression, you can also use numeric modules, which are
shipped with Python-modules. They are just Python packages that you can
import and add to your program for ease.
Code:
Strings:
Strings are usually used to represent both textual and arbitrary
information. String supports an operation that includes positional ordering
among items. For example, if you want to calculate the length of a string
which is inside quotes, you can use built-in len function and calculate its
length.
In Python, indexes are coded as offset and it start from 0: the first item
which is at first place is index 0, second is index 1, and so on. In Python, you
can also use of index backward from the endpoint. Positive indexes are
counted from the left-hand side and negative numbers count from the right-
hand side.
Every string operation which we have used untill now is like a sequence
operation and it can also be used in other Python sequences such as lists and
tuples.
>>>Var = “””python””programming”””
Code:
The above example searches for the word “Hello” followed by zero or
more tabs or spaces, then any character is saved as a match group ending
"world". If you find such a substring that matches partial patterns enclosed in
parentheses, they are the available group.
1. What is a Datatype?
Answer: The type of data in programming that specifies, what type of
value a variable can store such as integer, boolean, string, etcetera.
Numbers
Boolean
String
Tuples
Lists
Dictionary
Lists and Tuples
Till now, we have learned about different data types and discussed in-
details of numbers and strings, which are only two data types in the Python
language. Now, we need to understand some more such as Lists and Tuples
in detail.
Lists:
The Lists are a more flexible ordered collection data type in Python.
Unlike strings, lists can contain all type of data such as numbers, strings, and
even other lists, too. Lists are mutable in nature so you can change it while
assigning and slices.
Properties of Lists:
Collection of arbitrary objects:
Lists are the entity where you can collect other objects and treat them
as an ordered group. Lists maintain items in left to right positional
ordering.
Accessed by offset:
Mutable:
You can change lists at any place and it responds to all
operations, which are performed on lists like slicing,
indexing, and concatenation. It will give result in new lists
instead of the new string even if you are changing in a
string.
Object reference:
Python lists contain zero or more than zero references to the
other objects. Whenever you use reference, Python always
prefers a reference to an object. For example, you are
assigning an object to the data structure component and
variable name, then Python will store a reference to the same
object name. It will not store the reference to the copy of that
object.
Create Lists:
When you want to build a list, you just need to write the number of
expressions in square bracket.
Syntax:
lst_1 = [ ]
lst_2 = [expression1, expression2, ………. , expression N]
For example:
Lists len(L) always returns the number of items which is present in the list
and L[i] represents the items which is at index i and L[i:j] returns a new list
which contains objects between "I' and "j".
Code:
Output:
Update Lists:
You can add and update single and multiple elements in a list at a time.
Code:
Output:
Syntax:
Del list_name[index_val];
Code:
Output:
If you want to concatenate string and lists, then you need to convert the
lists to string to vice-versa.
Code:
If you want to check all sequence operation you have performed in the
string, you will see that lists are responding to all sequence operation.
Code:
In lists, indexing and slicing work the same as the string because the list
is also a sequence. The result of indexing depends on the type of object,
which is specified by the programmer at the offset, while slicing always give
a new list.
Code:
Lists always support the operation which changes the place of the
object. Python deals with the object references. The creation of new object
and change in place always matters while dealing with a reference because it
can impact more than one reference.
While using list, you can change its content by assigning it to the offset
or slice.
Code:
Both index and slice assignment modify the subject list while dealing with in-
place. It will not generate a new lists object. Python list support type-specific
method calls. Methods are the function, which is associated with and act
upon particular objects. It provides type-specific tools which are generally
available for lists.
Tuple:
In the Python language, a tuple is a data type which constructs simple
group of objects. You cannot change tuples in place and they are written as a
series of items in parentheses, not square brackets.
Properties:
Access by Offset:
Immutable:
Like string, tuples are also immutable. It supports many of
the same operations like string and lists. It will not support
any in-place change operation, which is applied to the lists.
Object references:
Tuple storage access point to other objects and the index
tuples are relatively fast.
Create Tuple:
For example,
Code:
Output:
Updating Tuples:
Code:
Output:
Delete Tuple:
Code:
Output:
You can operate indexing and slicing similar to string because of its
ordered set of the element.
If you want to compare elements of two tuples, then you can use ‘cmp’.
Syntax:
Cmp(tuple_1, tuple_2)
Description:
If you are comparing elements of the same type, it will give you a direct
result, but if you are comparing different types of elements, then you need to
cross-check whether it is a number or not. If it is a number, then first perform
numeric coercion and then compare them. If they are a string, then it will
sorted alphabetically.
Code:
Output:
If you want to find the length of tuple, then you can use “len()”. It will
return the number of element in the tuple.
Syntax:
len(tuple)
Description:
Code:
Output:
Exercise
Code:
Code:
Dictionaries
After string, list, tuple, and numbers, dictionaries is a popular used data
type in the Python programming language. It is the last data type to
understand in this material. Dictionaries are completely different from other
data types. They are not in sequence at all, but still, it is known as mapping.
Properties:
Access by keys: Dictionaries associate a key, so you can fetch an
item using the keys from the dictionary. Indexing operation is the
same as the list to get component in a dictionary, but the difference
between them is it takes the form of the keys and does not use a
relative offset.
Unordered collection of object: Items stored in dictionaries are not
in order, unlike a list. Keys provide a location of items in a
dictionary, but it provides the only symbolic location. It does not
provide a physical location, too.
Variable length and nesting: Dictionaries can contain any type of
objects and it supports nesting to any depth, too. There can be only
one key per key value, but if necessary, the value can be a collection
of multiple objects, and a given value can be stored under any
number of keys. Dictionaries can grow and shrink without new
copies.
Mutable: Dictionaries can be modified by assigning value to indexes,
but it does not support sequence operation unlike string and lists
because dictionaries are an unordered collection.
Object references: Dictionaries are an unordered table of object
references that support access by keys. It is implemented similarly to
a hash table, which starts small and grows as per the need. Python
uses a optimization hash table algorithm to find the keys — it helps
to retrieve data quickly. Like lists, dictionaries also store object
references.
Dictionaries Usage:
You can use an arbitrary object such as the standard object or user-defined
object in dictionary values. Its values don't have any restrictions on using
Python objects, but you cannot use all Python objects with the keys.
There are some points you need to remember about dictionary keys:
You cannot do more than one entry per key. It means you cannot use
a duplicate key. If duplicate keys are encountered during assignment,
it takes the last assignment into consideration
Key should be immutable, which means you can use string, tuples,
etc. as dictionary keys, but you cannot use ‘key’.
If you want to access elements in the dictionary, you can use the square
bracket with the key.
Code:
Output:
If you are trying to access elements which are not present in the dictionary,
then it will show you an error.
Code:
Output:
Update Dictionary:
You can update a dictionary by adding a new entry, or you can modify or
delete an existing entry.
Code:
Output:
Delete Dictionary Element:
Code:
Output:
Dictionary Functions:
1. cmp(dictionary1, dictionary2)
2. len(dictionary)
3. str(dictionary)
4. type(variable)
cmp(dictionary1,dictionary2):
Syntax:
cmp(dictionary1, dictionary2)
Parameters:
Code:
Output:
len(dictionary):
This method gives the length of the dictionary. It counts the number of items
and gives the result as a length of the dictionary.
Syntax:
len(dictionary)
Parameters:
Output:
str(dictionary):
This method is used to produce a printable string which can represent the
dictionary.
Syntax:
str(dictionary)
Parameters:
Dictionary: It is a dictionary.
Code:
Output:
type(dictionary):
This method is used to return the type of variable that you are passing. If
passing variable is dictionary then its return type is of dictionary data type.
Syntax:
type(dictionary)
Parameters:
Dictionary: It is a dictionary.
It returns the type of variable that you are passing to the dictionary.
Code:
Output:
Sorting keys:
Dictionaries are not in sequence, they don't maintain any left to right
order, so when you are printing it, it may come with the different order. If
you want all of the dictionary items in proper order, than you can use the
dictionary key method to get the key list, sort them by sort method, then
iterate through the results in Python for loops. The sorted call returns the
result and sorts the various object types sorted in the case dictionary key
automatically.
Exercise
1. What is Mapping?
Answer: Mapping is considered a collection of other objects, but it stores
them with keys instead of their position. Mapping doesn't follow any left
to right order like tuple, it directly maps keys to associated values.
There are some points which you need to remember about dictionary keys:
You cannot do more than one entry per key. It means you cannot
use duplicate key. If duplicate keys have encountered during
assignment, then it takes last assignment into consideration
1. If-else
2. Switch-case
For the iterative execution of the code, Python provides:
1. While loop
2. For loop
3. Nested loop
For jumps in the program, Python has rich features of break and
continue. Let’s discuss all there feature in detail:
If-else :
This is the most common and powerful feature to implement condition
If expression:
Statement1
Else:
Statement2
In the above syntax, Python interpreter evaluates the expression, also called if
condition. If the expression results in true (non zero) then statement1
executes. Otherwise, statement2 execution takes place. The following
flowchart is suitable for the better understanding of its bidirectional nature:
Flowchart
Code
Output
If expression:
Statement1
Statement2
Else:
Statement3
Statement4
FlowChart
Code
Output
Else part of the syntax is not compulsory. You can skip it, according to
the need. The syntax and flowchart are as following:
If expression
statement1
Flowchart3
Code
Output
Nested if-else:
The Python language also allows the nesting of if-else where one if-else
If expression1:
If expression2:
Statement1
Else
Statement2
Else
If expression3:
Statement3
Else:
Statement4
Flowchart
Code
Output
Else-if Ladder:
The else-if ladder is one type of multi-way decision-making statement in
Python. There is an if-else statement for every else part of if statement and
If expresion1:
Statement1
Elif expression2:
Statement2
Elif expression3:
Statement3
Else:
Statement4
In the else-if ladder, Python interpreter evaluates every if condition
sequentially one-by-one, and when it resolves into true, it executes the
corresponding statement and then controls comes out without checking
remaining condition.
Flowchart
Code
Output
Loops:
In any programming language, loops are used when we want to execute
a part of program multiple times. It is always easy to optimize the program
using Loops. For example, if you want to print a string “Welcome to Python”
ten times on the output string, instead of writing print statement ten times,
you can use one of the loops (while or for) to implement it. Every Loop in the
Python language requires a counter variable, condition check, and increment
or decrement operation.
Counter variable keeps track of the number of times the loop has
executed. Increment and decrement operation is implemented on the counter
variable, and condition check is required for termination of the loop.
Each loop has its own requirement and significance during programming.
Let’s understand them in detail:
While Loop:
The syntax of while loop is as following:
While expression:
Statement1
Statement2
In the above syntax, the expression is evaluated by the interpreter first,
and if it resolves into true, then the body of the while loop (Compound
Statements) executes. Otherwise, it comes out of the loop. After the execution
of the body again, it evaluates the expression and executes the body. The
body of loop will execute until the expression in the results into false. This
process can be better understood from the below flow chart.
Flowchart
In the programming, you can use the following type of convention for more
productive code.
Initialization statement
While condition:
Statement
Increment/decrement statement
You will get a clear idea for above convention with the following
programming challenge.
Code
Output:
For Loop:
The for loop is frequently used out of all the loops because of its easy
syntax, which is as follows:
Statements
Flowchart
When you need to iterate through the sequence, there are two ways you can
iterate using for loop. Let’s understand them in brief:
Statements
Code
Output
Statements
Code
Output
Nesting of loops is also possible by using one loop inside the body of
another loop. Application of nested loops can be in the array of sequence and
for handling huge data.
Infinite Loop:
The loops that execute its body infinite times are known as the infinite
loop. You can implement this type of loop deliberately or by mistake, which
puts your program running into continuously. To implement infinite loop,
you can use the following approach:
While True:
Statement
The termination of an infinite loop can be controlled by using break and goto
statement inside the body of the loop. These statements are explained in the
further topics of this chapter.
Continue
Code
Output
The break statement is similar to the continue, but when it is used inside
the loop, it terminates the loop and control is transferred to the next statement
after the loop. Let’s understand it with following program.
Code
Output
Exercise
Answer:
For loop
While loop
Infinite loop using for and while loop
Functions and Modules
Introduction:
Throughout the previous chapters, we have discussed the different features
of Python interpreter that will help you to create your Python program. It's
time to move to the design approaches for your programs and without an
understanding of the functions and modules, it would be impossible to create
a properly designed program. Functions and Modules give you the freedom
to cut your program into small parts and implement it with an easy-to-design
philosophy.
Functions are like devices that have the capability of taking input parameters
and provide output. Output of the function can be either a data or operation
on the parameter passed in it.
Before we dig deep into the syntax and programming with functions, let's
understand a bigger picture for the use case of functions. Functions are
generally giving a structure to your Python program. Sometimes they are also
called procedures and sub-routines in other programming languages.
Primarily, there are following philosophy for the use of functions in any
python program:
2. Well-structured programming:
The function gives you a tool to divide your big programming task
into multiple well-defined procedures and allow you have a well-
structured program for the same. Let's consider a programming
scenario where you want to calculate average salary of the employee
in any organization. You can divide the task into procedures likes
taking the input of the employee data, calculating an average, and
displaying the average value. The function can be written for each of
the procedures and call them to have the well-structured program.
Function Syntax:
In Python programming, the general syntax of writing function is as follows:
Statements
Return val
Let’s get into the Python programming to get more use out of case of
functions and its implementation:
Code
Output
Code
Output
1. Import:
It allows you to load complete module as a whole in your
Python program.
2. From:
It allows you to load specific names from any module in
your Python program.
As any particular module is being loaded inside your Python program, it lets
you use all the self-contained program codes from the modules. Because of
the use of modules inside Python programming, it provides you with a bigger
picture with the use of existing modules without any conflicts between
attributes and methods.
1. Code – reuse:
When you are loading any of the modules in your Python using
import statement, you can use all the methods and functions present
in the particular module. After importing, it can be referenced
multiple times to reduce the lines of code. Modules always help to
visualize a bigger picture of the program. Unless you are using
Python interpreter, you can import modules just by using its name.
2. Separate Namespaces:
As modules are a self-contained program code, being a programmer,
their parameters are isolated from your main Python code. It helps
you to write your Python code in a well-organized manner, keeping
top-level organization in mind.
Whenever you are working with Python programming, you will need to
import and link libraries with your main top-level program. Libraries are
present inside the module files, which act as a tool to perform programming
tasks.
Let’s understand the concept of modules and its use with programming
examples. There are following files with their Python code:
Print text
The top-level files include an import statement that loads the modules into the
main file. After fetching modules, it can be referenced using the attributes of
it.
Exercise
Functions are like devices that have the capability of taking input
parameters and provide output. The output of the function can be
either a data or operation on the parameter passed in it.
File Input-Output
Each program is a combination of program statements to perform some
task or logic. These logics may or may not require inputs to provide the
output, hence inputs that are outputted are part of every program. You need a
file to store everything for storage on the computer, which is managed by OS.
Although variable provides us a way to store the data while a program is
running, we must save it to a file if we want to keep the data after the
program has ended.
The built-in open method is used to create a Python file object that
provides a connection to the files, which resides on the programmer's
machine. After calling an open function, the programmer can transfer the data
string to and from an external file residing in the machine.
You can produce output by using the “print” statement where you can
pass expression separated by commas. This function converts the expression
which you are passing into a string and writes the result to standard output.
Code:
Output:
Read Input:
You can read a line of text from standard input, which will come from the
keyboard by using two built-in functions.
raw_input
input
raw_input function:
The raw_input function reads one line from standard input and
returns output as string.
Code:
Output:
input function:
The input function assumes that the input is a valid Python
expression and it will return the evaluated result to you.
Code:
Output:
Open Function:
You need to open file before you start reading and writing any file.
Python has a built-in function that is used to open file i.e. open(). This
function will create a file object, which is utilized to call other methods
associated with it.
Syntax:
File object = open(file_name[, access_mode][, buffering])
Parameters:
Different Modes:
Modes Description
rb+ Open file for both read and write in a binary format
wb+ Open file for both read and write in a binary format
ab+ Open file for both appending and reading in binary format
Close Function:
The close () method of the file object refreshes any unwritten information and
closes the object file and the object cannot be written later.
Python closes the file automatically when the file is reassigned to another
file.
Syntax:
fileObject.close();
Code:
Output:
You can write any string to an open file by using write () function. It is
really important that Python string contains binary data and not just text. It
does not add a new line character to the end of the string.
Syntax:
fileObject.write(string);
Code:
Output:
The above method will create .text file and writes content in the file, and after
execution, it closes the file.
Read Function:
You can read a string from an open file by using read () function.
Syntax:
fileObject.read([count]);
Parameters:
Code:
Output:
File Position:
If you want to check current position with the file, then you can use tell
() function. The next read and write will occur after the number of bytes
returned from the tell () function from the beginning of the file.
The seek (offset [, from]) is used to change the current file position. The
offset indicates the number of bytes to move. The from is used to specify the
reference position from which you want to move the bytes.
Output:
Rename function generally takes two arguments i.e. current filename and new
filename.
Syntax:
Remove Function:
You can delete files by giving the name of the file as an argument in the
remove () function.
Syntax:
os.remove(file_name)
Code:
File Flush:
Python automatically flushes the files when it is closed. But if you want
to flush the data before closing the file, then you can use flush () function.
This method is used to flush the internal buffer.
Syntax:
fileObject.flush();
Code:
Output:
File next:
Using the next () method with other file methods such as readline () is
not correct. However, using seek () to relocate the file to an absolute position
refreshes the read-ahead buffer.
Syntax:
fileObject.next();
Code:
Exercise
The negative index begins with '-1', indicating the last index in the
sequence, '-2' as the penultimate index, and the sequence going
forwards like a positive number.
Object-oriented Programming
Introduction:
The secondary philosophy behind the development of the Python language
was to create an easy-to-code object-oriented programming language that has
the capability of less development time with all the advantages of object-
oriented. Though using Python's object-oriented way of programming is
optional, but it is a good practice over procedural programming.
You can certainly use procedural programming practice with Python, which
allows you to develop pretty quickly. In practice, Object-oriented
programming requires a lot of pre-planning in the actual development of the
solution, hence it is used for the large projects. When the time for the solution
development is less, then top-bottom approach in writing Python scripts are a
better option. In some situations, if the pre-planning and program modelling
strategies are properly formed for larger projects, then development time
could be significantly reduced.
1. Class:
The class is a prototype, which is user-defined and specifies
a standard set of attributes. These attributes are methods,
instance variables, and data variables.
2. Class Variable:
Class variables are the object or variables which are shared
in a particular class. These variables are declared and
defined inside the body of a class, but outside of method
present in the class. Generally, these types of variables are
less commonly used than instance variables.
3. Instance:
A specific object class is called an Instance of that particular
class.
4. Instance Variable:
The variables which are declared and defined inside the body of the
class method and its scope are only inside the method body.
5. Object:
An object is the basic building block of any object-oriented
programming language. It is a particular instance of the data
structure that is defined by its class. The object includes
methods instance variables and class variables.
6. Method:
The method is a small function or procedure defined inside a
class. These are the building blocks of any class that
implements certain logic.
7. Inheritance:
Inheritance is one of the popular advantages of using an
object-oriented programming language. It is a process in
which the characteristics of a class is transferred to the other
class. The new class, which is derived from the former class,
is also known as the child class.
Creating a Class:
Classes are the user-defined prototypes with its attributes. To create a class in
the Python language. The following syntax is used:
class ClassName:
“Class Documentation string”
classAttributes
In the above syntax, the class is a statement that creates a class with
class name as className. The next line after the colon is for documentations
of class. The documentation string contains all the information about the
class in the double inverted comma. The class body has classAttributes and it
comprises of class variables, instance variables, and methods.
Example of Class
Code
Output
In the above example, Employee class can have multiple attributes such as
Employee name, Employee salary, and their count, hence class allows the
programmer to specify the entity with its features. displayCount and
displayEmployee are the methods of the Employee class. Inside the
Employee class, employeeCount variable is instance variable as its scope is
inside the class only.
The method name with __init__ inside the Employee class is called the
constructor or initialization method whenever object of Employee class is
created, then its attributes are initialized with the specified arguments.
To create an object of the class, it can be called with its name and initialized
parameter is passed. In the above program, employee1 and employee2 are
two objects of Employee class. To access the attributes of any class, it can be
used with className, dot operator, and attribute name. As you can see, to
call displayEmployee, method employee1.displayEmployee() is used.
Code:
Output:
Sort using keys: You can use the key parameter of built-in sorting,
which is a faster way to sorting
Code:
Output:
Optimize loop: You should write your code with timing parameters
in your mind, particularly when dealing with loops. Because Python
is designed to have only one way to do task.
Code:
Output:
Try multiple methods in coding: Always try multiple approaches
while creating an application because one may give you better results
than another. For the different inputs, it takes different times for
execution. For some particular set of inputs, your chosen solution
may be slow, you can decide as per your application need.
Code:
Output:
Use xrange : This function is used to display a number by looping
because it returns the generator object. This function is used to
display only particular range on demand and hence it is known as
“lazy evaluation”.
But it can save your system memory because it will yield only
integer element at a time.
Code:
Output:
Filter () –
Syntax:
Code:
Map () –
Syntax:
map (function, list)
Code:
Reduce () –
Syntax:
Code:
List: Use list instead of lengthy code. As it gives you the flexibility to
eliminate a large number of lines from the program
Code:
Optimized way:
You can look at a result and find out the area where you think
you need to improve. You can attach C profile while running script
too.
Tkinter Library:
This library is built-in present with all the Python packages, so you don't need
to install it separately on your system. As we have discussed in the chapter
“_____”. Tkinter’s name is shorthand name for interface to Tk. This is one of
the many GUI libraries for Python. To import this library into your program,
you can use the following line:
$ import Tkinter
Or
In case if you want to include only some module from it, you can use:
$ from Tkinter import moduleName
Where moduleName is any module name present in the Tkinter, the available
modules are discussed in the further sections.
Uses:
You can use it to create your Graphical User Interfaces such as forms, button,
checkboxes, and many other GUI features. Front-end designing is important
aspects when creating any application. This library helps you in it.
Modules:
tkFileDialog: To provide a dialog box to select or save the file by the user.
PyQT Library:
To import this library in your code, you need to install PyQT using pip
installer on your system.
Uses:
The uses of PyQT library are diverse. Some of the very complex applications
(including Embedded Applications) using it for the development of their
graphical user interface.
Modules:
There are hundreds of modules available from PyQT library; you just need to
use particular modules as per your applications. You can go to the link for
exploring its documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/
QtFileDialog: This module contains all the classes and function related to
selection and saving of files by the user.
Requests Library:
Requests is a very simple and quick HTTP library which was developed by
Kenneth Reitz. It is the must known library for any Python programmer. Its
beloved features attract every web Python developer.
To install it on your system and use it with your Python program, you need to
setup it using pipenv.
Uses:
This library is useful for requesting URL in an automated way. There
are various features available with it, such as network pooling, connecting to
international domains and URLs, browser type SSL verification, and
automatic decoding of content.
Modules:
Request: this method helps in sending a request to URL specified with it.
Exception:
There are many exceptions that occur while working with requests library.
Let’s understand these exceptions and there causes:
There are many advanced level database access functions available in this
module. To install this library on your system, you need to take help from pip
module.
Uses:
Modules:
SQLAlchemy has a rich set of modules in it, which gives your power to link
and access SQL data in a flexible way. Some of its modules are as follows:
Query: Query is the basic source of all the SELECT statements in the SQL
database. This method allows you to generate a query for the database.
Delete: it helps in deleting the bulk data from the query results.
RASPBERRY PI
Step-by-Step Guide To Mastering Raspberry PI 3
Hardware and Software
Richard Ray
Ó Copyright Richard Ray 2018 - All rights reserved.
If you would like to share this book with another person, please purchase an additional copy for each
recipient. Thank you for respecting the hard work of this author. Otherwise, the transmission,
duplication or reproduction of any of the following work including specific information will be
considered an illegal act irrespective of if it is done electronically or in print. This extends to creating a
secondary or tertiary copy of the work or a recorded copy and is only allowed with express written
consent from the Publisher. All additional right reserved.
TABLE OF CONTENT S
CHAPTER 1
INTRODUCTION TO RASPBERRY PI
CHAPTER 2
GETTING STARTED WITH THE RASPBERRY PI
CHAPTER 3
INTRODUCTION TO EMBEDDED LINUX
CHAPTER 4
WORKING WITH ELECTRONICS
CHAPTER 5
PROGRAMMING A RASPBERRY PI
CHAPTER 6
INPUT AND OUTPUT ON A RASPBERRY PI
CHAPTER 7
INTRODUCTION TO COMMUNICATION PROTOCOLS
CHAPTER 8
PYTHON PROGRAMMING FOR THE RASPBERRY PI
CHAPTER 9
FINAL PROJECT
Chapter 1
Introduction to Raspberry Pi
The Raspberry Pi was developed to encourage children who want to learn about computers and
programming. The Raspberry Pi is one of the most popular devices in the system-on-a-chip (SoC)
market, thanks to its rapid development and the low cost, which starts from just $5 for the Raspberry Pi
Zero model. In 2015, more than five million Raspberry Pi boards were sold. The Raspberry Pi boards
are very complex, but the ability of the Raspberry Pi to run embedded Linux makes the device both
powerful and accessible. Using Linux on embedded systems makes the development very easy,
especially if we develop applications for smart things, the Internet of Things (IoT), robotics, smart
cities, and cyber-physical systems. Thanks to the integration between Linux software and electronics,
this board represents a paradigm shift in the development of embedded systems. You can use the
Raspberry Pi not only in embedded systems development but also as a general purpose computer.
As we said before, the Raspberry PI can be used as a general purpose computing device. Because of
that reason, it may be used to introduce computer programming to its users, but most of the developers
use it as an embedded Linux platform.
Most of the Raspberry Pi models have the following features:
- Low cost, starting from $5 to $35
- Contains a powerful 1.2 GHz ARM Cortex – A53 processor which can process more than 700 million
instructions per second
- Has many models that are suitable for different applications
- They save a lot of power since they run at 0.5W to 5.5W
- If you need support for any project, you can easily find a solution thanks to the huge community of
innovators
- It can run a Linux operating system, so you can install open source libraries and many applications
directly to it
It has Hardware Attached on Top (HATs)
This actually an impressive feature because you can extend the Raspberry Pi functionality using HAT
that then connects to the GPIO header, so you can design your own HATs and attach them to your
Raspberry Pi header.
If you want to learn about electronics, programming, and the Linux operating system, you should use
the Raspberry Pi platform especially for IoT applications and robotics.
The Raspberry PI is better than other embedded Linux devices and more traditional embedded systems,
such as the Arduino, AVR, and PIC microcontrollers, is when you use Linux for your project. For
example, if we develop a smart home system using the Raspberry Pi and you want to make information
on the Internet, you can use and install the Nginx web server. After that, you can use a server-side
language like PHP, Python, Perl, or any other programming language you may prefer. Also, you may
want remote shell access, so you could install a Secure Shell without any effort by using the command:
sudo apt install sshd. This will save you time.
On Linux operating systems you will find device driver support for many USB peripherals that makes
the installation of any USB device so easy like camera, Wi-Fi adapters, and much more, instead of
complex software drivers.
The Raspberry Pi can also play HD videos because it has a Broadcom BCM2835/6/7 processor used for
multimedia applications, and it also a has a hardware implementation of H.264 MIPG-4 and MPG-
2/VC-1 decoders and encoders.
If you are going to develop applications for a real time system then the Raspberry Pi will not be a good
choice. For example, if you want to use a sensor to get some values every on millions of a second, it
will be not easy to interrupt the system, but you can connect them with real-time micro-controllers
through the buses like UART, 12C and Ethernet.
Raspberry Pi Hardware
The heart of every Raspberry Pi board is the Broadcom BCM2835, BCM2836, and BCM2837 system-
on-a-chip (SoC). Raspberry Pi models are available for example (the Raspberry Pi A+, B+, 2, 3 and
Zero), but I recommend purchasing the Raspberry Pi 3 because it has a multi-core processor.
Raspberry Pi Versions
● If you want to use the Raspberry Pi as a general purpose computer, you should consider the
Raspberry Pi 3. The 1 GB of memory and 1.2 GHz processor provides the best performance compared
to the other boards.
● For applications that interface electronics to the Internet on a network, use the Raspberry Pi 3 2 or
Raspberry Pi B+.
● If you want a small board with wireless capability , the best choice would be the Raspberry Pi Zero
F USB cable
F Micro-SD card
F Serial cable or Wi-Fi adapter
Linux has many distributions (also known as versions) of its operating system. There are many
different Linux versions such as Debian, Red Hat, or OpenSUSE that are mainly used on servers, but
versions like Ubuntu, Fedora, or Linux Mint are used for desktop users. But you should keep in mind
that they all have the same Linux kernel that was created by Linus Torvalds in 1991.
For an embedded system we will choose a distribution based on the following:
● The stability of the distribution
● The package manger
● The level of community support for the device used
● The device drivers support
● If you want to set up an SD card to boot the Raspberry Pi, just download a Linux distribution image
file from www.raspberrypi.org/downloads and write it to an SD card using any image writer.
Connect to a Network
There are two ways to connect the Raspberry Pi to a network using regular Ethernet or an Ethernet
crossover cable.
Advantages Disadvantages
You will have control You will need administrative control
over IP address settings
You can connect many You will need a source power for the
boards Raspberry Pi over Ethernet
The Raspberry Pi can The setup is more complex for
connect to the Internet beginners
without a desktop
computer
● The first thing you should do is find your Raspberry Pi on the network. By default, the Raspberry Pi
request a Dynamic Host Configuration Protocol (DHCP) IP address. This service is provided by the
DHCP server that runs on the integrated modem – router –LAN.
You can use any of the following methods to get the Raspberry Pi's dynamic IP address:
● Using a web browser: write 192.168.1.1, 192.168.0.1 or 10.0.0.1. Log in and look under the menu
"Status" for the DHCP Table. You should see an entry with the details for the IP address, the MAC
address, and the lease time remaining for a device with the hostname Raspberry Pi.
● Using a port scanning tool: Use a tool such as nmap under Linux or the Zenmap GUI version
available for Windows. You will search for an entry has an open port 22 for SSH. It identifies the range
of MAC addresses to the foundation. You can ping it to test the network connection.
Let’s use the other type which is the Ethernet crossover cable
An Ethernet crossover cable is a cable that has been modified to enable similar devices to connect
without using a switch.
Advantages Disadvantages
In case you don’t have access to When your desktop machine
the network , you can still connect has only one network
the Raspberry Pi adapter, you will lose access
to the Internet
Raspberry Pi can have Internet Raspberry Pi will need a
access if you have two network source of power
adapters and sharing is enabled
You will have a stable network You may need a specialized
setup crossover cable
Here are the steps when you use the Windows operating system
1. Plug one end of the cable into the Raspberry Pi and the other end into the laptop socket.
3. Open up the Control Panel, choose Network Connections, then select two network adapters
(wired and wireless). At the same time, right click and choose bridge connection.
4. Restart the Raspberry Pi. You can use a USB or TTL serial cable to do this, or use the reset
button directly, then your Raspberry Pi will get an IP address from the DHCP server.
After you networked the Raspberry PI, the next thing that you will need to do is communicate with the
Raspberry Pi. You can connect the Raspberry Pi using a serial connecting over USB to TTL or using a
network connection as we did before. It is a fallback communication method for when something goes
wrong with the software services on the Raspberry Pi board. You can also use it to configure wireless
networking on the Raspberry Pi.
To connect the Raspberry pi through the serial connection, you will need terminal software; you can
choose PuTTY or RealTeerm on Windows. If you are using a Linux OS, press Ctrl + Alt+T then type
gnome-terminal under Debian.
To find the port number, open the Windows Device Manager, and find where the device is. It is listed
as COMx.
Set up the connection speed; by default it will be 115,200 baud to connect the Raspberry Pi.
Then set the following values: bits = 8; Stop bits=1; Parity=none; and Flow control = XON/.XOFF.
Connecting the Raspberry PI via SSH
Secure Shell (SSH) is a useful network protocol for secure encrypted communication between network
devices. The SSH is running on port 22, and you can also use Putty to connect the Raspberry PI via
SSH.
Command Description
More/etc/issue Returns the Linux Version
pp –p $$ Returns the shell you are suing
(like bash)
whoami Returns who you are logged in as
uptime Returns how long the system has
been running
top Lists all of the processes and
programs executing
First of all, the term embedded Linux is technically not one hundred percent correct because there is no
special Linux kernel for embedded systems; it’s the same Linux kernel for any device.
When we use the term embedded Linux, we mean that we use the Linux operating system on embedded
systems, but embedded has different characteristics for the general purpose computing devices such as
the following:
- Embedded systems have specific and dedicated applications
- Have limited memory, power, and storage capability
- They are almost always part of a larger system that may be linked to sensors or actuators
- They are embedded in automobiles, airplanes, and medical devices
- Works in real time (the outputs are directly related to its present inputs)
You can see embedded systems everywhere in everyday life. They can be found in vending machines,
household appliances, smartphones, TVs, cars, parking systems, advanced driving assistance systems,
and much more).
● The Linux operating system is an efficient and scalable OS that can run on everything from low–cost
devices to expensive large servers.
● Linux has a huge number of open source applications and tools.
● Open source = free.
● Its only disadvantage is that it cannot deal with real time applications due to the operating system
overhead. So if you develop fast- response applications , like analog signal processing , embedded
Linux will not be the best choice , but in special cases it can handle the real time systems using
embedded Linux.
If you boot your desktop computer, you will see the Unified Extensible Firmware Interface (UEFI),
which provides legacy support for BIOS (Basic Input/Output System) services. The Boot menu
displays the system information and you can change the setting by pressing any key. UEFI tests the
hardware of your computers like the memory, the hard disk, and then loads the operating system from
the solid state drive (SSD). When a desktop computer is powered on , the UEFI/BIOS performs these
steps:
1. Takes control of the processor of your computer
2. Tests the hardware components
3. Loads the operating system from your hard drive
Raspberry Pi Bootloaders
Like any embedded Linux device, the Raspberry PI does not have a BIOS by default. Indeed, it uses a
combination of Bootloaders. Bootloaders are programs used to link your hardware to your operating
system.
In the following illustration you can find the sequence of the booting process on the Raspberry Pi.
● Also, you can find the same information using the command dmesg | more in the terminal.
Kernel and User Space
● The kernel space is the area that the Linux kernel runs in. It’s an area of the system memory, but the
area that regular applications run in is called user space, and there is a hard boundary between the
kernel and the user space; this is to prevent the kernel from crashing, in case the user wrote bad code.
● The Linux kernel has the full access of the physical recourse, including memory on the Raspberry
PI board.
More commands on Linux (some system commands)
Git is a system that allows you to track your changes of the software you are developing.
There are two types of version control systems:
● Distributed: Like Git. Using such systems, you cannot pull down changes but you can clone the entire
repository. "Clone" means copy, and it can become the master copy if required.
● Centralized: Like Apache (SVN), works on systems like that where you will find a master copy of
your project, and then you can pull down changes.
For more details you can check out git.kernel.org
Questions for Chapter 3
Electronics components
Digital Multimeter
DMM is an electrical device used to measure the voltage, current, and resistance of a circuit.
If you don’t have one, buy one that has the following features:
● Auto range: To automatically detect the range of the measurements.
● Auto power off: To save power and not waste your battery.
● True RMS: A multimeter with this feature uses real calculations to analyze phase-controlled devices
like solid state drives.
Introduction to electric circuits
● Ohm’s Law→ V = I X R
This is the most important equation you will need.
● V for Voltage . Voltage is the potential difference between two points on a circuit. For example, if you
have a buffer tank of water which is connected to the tap, water will flow if you turn on the tap because
the height of the tank and the gravity, but if the tap was at the same height as the top of the water tank,
water wouldn't flow because in this case there is no potential energy. Voltage also exhibits the same
behavior; if the one side has a higher voltage than the other side , the current will flow across the
component.
● I for Current. Measured in amperes (A), current is the flow of the electrical charge. Like in the water
tank example, the current will be the flow of the water from the tank to the tap.
● R for Resistance (R). Resistance is measured in ohms (Ω), and is something that reduces the flow of
current through the dissipation of the power; power(P) in watts(W), P = V X I.
For example if you want to buy a resistor that limits the current to 100mA using a 5v supply, you can
calculate it as the following R = V
R ⁄ ( IR = 5 V) ⁄ (100 mA) = 50 Ω, and the power will be P = VI = 0.5W.
components
● A voltage regulator is a device that takes the varying input voltage and outputs a constant voltage, the
Raspberry Pi B+ and Raspberry Pi 2/3 models have a dual efficiency PWM DC TO DC converter that
can apply different fixed voltage levels on-board if there is a 5v, 3.3v and a 1.8v output. You can use
the 5v and 3.3v on the Raspberry Pi GPIO headers, and the board can support up to 300mA on the 5v
(pins 2 and 4).
And 50mA on the 3.3v pins (pins 1 and 17).
● If you want a larger current, you can use an external regulator which is used for components like
motors.
A diode is a semiconductor that allows the current to pass in one direction.
Capacitor
A capacitor is an electrical component used to store electrical energy.
● The first number is the first digit for the value.
● The second number is the second digit for the value.
● The third number is the number of zeros.
For example:
104 = 100000pF = 100nF = 0.1μF
Transistors
Transistors are one of the core components of any microprocessor or any electronic system. We use
transistors to amplify a signal on or off. You can also use it as a switch.
Questions for Chapter 4
Programming a Raspberry Pi
Introduction
In this chapter we will use many programming languages for the Raspberry Pi, including scripting and
compiling languages. Take a look at the structure and syntax of each language and the advantages and
disadvantages of each language (with examples), but we will mainly focus on the Python programming
language.
Any programming language available on Linux will be also available on the Raspberry Pi , then you
can choose the suitable language depending on the kind of application you are developing.
If you would like to do any of the following:
● Write device drivers for Linux
● Develop graphical user interfaces
● Design web applications
● Design a mobile application
Each choice will impact the option of the suitable language needed for that particular task, but there is a
difference between the development for embedded systems and the development for other platforms
like desktop, web, or mobile applications when you are developing for the embedded system. You
should keep the following in mind:
● You should write clean code.
● You should optimize the code only if you complete it.
● You should have a good understanding of the hardware you are developing on.
Languages on the Raspberry Pi
By now you must be thinking, “What programming language should I use on the Raspberry Pi to
guarantee the best performance?" Actually, this is a fairly difficult question to answer because, as we
said before, it depends on what type of the application you are developing.
● Interpreted: The source code won’t be translated directly to machine code, but the interpreter will
read your code and then execute it line by line.
● Compiled: The compiler will translate the language directly to the machine code (0s and 1s).
● JIT: Just in time compiled means it has the feature of the compiled language, which is translating the
source code directly into machine code. It also has the interpreter language, which is translated into the
code line by line.
Also you may use Cython, this allow you to generate C code from your Python code. We will show
some examples using Cython and the extended version of Python.
Write the following commands on the terminal if you want to set the CPU frequency.
$sudo apt install cpufrequtils
$cpufreq-info
Set clock freq write the following commands.
$sudo cpufreq-set -g performance
$cpufreq-info
$sudo cpufreq-set –f 700MHz
$cpufreq-info
/system/class/gpio $ cd gpio4
/system/class/gpio/gpio4 $ ls
A scripting language is a type of computer programming that is used to write scripts that are interpreted
directly with no compiler.
There are many types like:
● Python : It’s a great and very easy language to learn and use for scripting and object-oriented support
features.
● Bash : A good choice for short tasks and you don’t need advanced programming structures.
● Perl : You can use this language for text or process data. It allows you to write code in object-oriented
paradigms.
● Lua : This scripting language is used a lot with embedded applications. It is a lightweight language
and supports object-oriented programming styles.
Example: Drive the LED using Bash.
LED-IO = 5 # use a variable called LED with value 5
Function blinkLED
{
Echo $1 >> “/sys/class/gpio/gpio$LED_IO/value”
}
If [$# -ne 1]; then
echo “No command has been entered”.
echo “ on or off ”
echo –e ” setup the LED ”
exit 2
if
echo”The command has been entered is $1”
if [“$1” == “setup”]; then
echo “IO $1”
echo ”the LED is on”
echo $LED_IO >> “sys/class/IO/export”
sleep 1
echo “away” >> “sys/class/IO$LED_IO/direction”
elif [“$1” == “on”]; then
do return en
end
if arg[1] == “off” then
print(“The LED is on”)
wirteIO(“LED4_PIN”, “val”, “1”)
elseif arg[1] == “configure “then
print(“the LED is off”)
WirteIO(LED4_PIN, “val”, “0”)
Elesif arg[1] == “configure”
Print(“configure the IO”)
WriteIO(SYSFS_DIR, “xport”, LED_NUM)
Os.execute()
WriteIO(LED4_PIN,”DIR”,”out”)
Elseif arg[1]==”sta”then
Print(“turn IO off”
Print(“find the LED sta”)
File=io.open(LED4_PIN..”val”,”r”)
File:close()
Else
Print(“please insert a valid command”)
End
Print(“the end”)
SYS_DIR = “/sys/class/IO”
LED_NUM = “4”
Print(“incorrect argument”)
Sys.exit(4)
If.argv[1]==”on”
Print(“the LED is on”)
wLED(fname=”val”, val=”1”)
Introduction
In this chapter you will use what you have learned in the five previous chapters about Linux,
programming, and electronics basics, so you will start working with the general purpose inputs/outputs
on the Raspberry Pi, as well as work with Pulse Width Modulation (PWM). At the end, you will work
with the Wiring Pi Library, so let’s get started…
After showing you how to administrate Linux and practice different commands on the command line,
building electronic circuits, and programming using different languages it’s now time to integrate all of
these things to control the Raspberry Pi in different ways like:
● Using the buses, for example SPI and I2C.
● Using UART on the GPIO.
● Communicating through Wi-Fi or Bluetooth with electronic components.
● Connecting your USB devices like keyboards, Wi-Fi modules, etc.
Now we will use the GPIO header to connect the Raspberry Pi to circuits. The next example will
provide you a view of the functions of the GPIO header, you will find that many of the pins are
multiplexed, which means that the same pin can do more than one.
● Pull up resistor : From its name, it pulls the voltage of the wire that connected to its source when the
other components on the line are inactive, and they are disconnected.
● Pull down resistor: It works like the pull up resistor, but it's connected to the ground and holds the
signal when the other devices are disconnected.
There is a C++ class with the sysfs GPIO functions on the Raspberry Pi to make it much easier to use.
You transfer it to any embedded Linux device. There is another approach called memory-mapped that
you will see at the end of the chapter, but keep in mind that all of these approaches are specific to the
Raspberry Pi board.
#define GPIO_Address “/sys/class/gpio”
Namespace Raspberry {
enum GPIO_DIR{IN, OUT};
enum GPIO_VAL {low=0, HIGH=1};
enum GPIO_EDGE {none, rise, fall, both}
};
Class GPIO {
private:
int number, debounceTime;
string name, address;
public:
GPIO(int number);
Virtual int getNumber(){return number;}
{
This->threadRunning =false;
}
// input
Virtual int setEdgeType(IO_EDGE);
Virtual IO_EDGE getEdge();
Virtual int waitEdge();
Virtual int waitEdge(callbackType callback);
Virtual void waitEdgeClose(){this->threadRunning = false;}
Virtual ~IO(); // destructor
Private:
Int write(string address, string fname, string val);
File c++control.cpp
#include<iostream>
#include<unistd.h> //for usleep function
#include”GPIO.h”
Using namespce Raspberry
Using namespace std;
Int main()
{
GPIO outIO(17);
outIO.setDIR(OUT);
{
outIO.setVal(HIGH);
usleep(400000);
outIO.setVal(LOW);
usleep(400000);
}
inIO.setDIR(INPUT);
cout << “input state is”<<inIO.getVal() <<endl;
outIOlstreamOpen()
for(int i =0; I < 100000000; i++)
{
outIO.streamWrite(HIGH);
outIO.streamWrite(LOW);
}
outIO.close();
return 0;
In the following figure you will see the performance of the code when the write() method is used; it is
flashing at 129 kHz.
POSIX
Ptherads is a set of functions written in the C language to allow you to implement threads with C/C++
programs. You will need threads when you want to run some parts of your code at the same time.
Pulse Width Modulation - LED Fading
The Raspberry Pi has the capability (PWM) to provide analog to digital conversion (DAC), which is
usually used for motor devices.
All Raspberry Pi boards have Pulse Width Modulation pins.
We will use the PWM feature to fade an LED by changing the duty cycle value.
Create file call LEDFading.cpp.
Then write the following code:
#include <iostream>
#include <wiringPi.h>
#include <unistd.h>
Using namespace std;
#define LED_PIN 18
#define Button_PIN 27
Bool run = true;
Void buttPress(void)
{
Cout<< “you pressed the Button”;
Run = false
}
Int main ()
{
wiringPiSetupIO();
pinMode(LED_PIN, OUTPUT);
pinMode(Button_PIN, INPUT);
wirinPisr(Button_PIN, INT_EDGE_Rise, &buttPress);
}
}
return 0;
}
}
Questions for Chapter 6
1. Describe the difference between pull-up and pull-down resistors.
2. What is Pulse Width Modulation? How many pins are on the Raspberry Pi?
3. List the purposes of using the general input output pin on the Raspberry Pi.
4. Using C++, write a program to control servo motors using the PWM pin on the
Raspberry Pi.
5. What is the benefit of using POSIX?
Chapter 7
In this chapter you will work with the following communication protocols:
● SPI: serial peripheral interface
● I2C: inter integrated circuit
● UART: Universal Asynchronous Receiver/Transmitter
I2C
The I2C protocol or IIC is a protocol with two wires that were invented by the Philips company. The
benefit of this protocol is to connect microcontrollers with other peripheral devices. You can use it with
the Raspberry Pi for the following reasons::
● The Raspberry Pi will act as the master device.
● The other devices will connect to the Raspberry Pi and will act as slaves on the same wire.
To configure the I2C on the Raspberry Pi, open the terminal and write the following:
Config.txt | grep i2c_arm
Then save and restart; let’s make it available.
After the restart, open the terminal and write the following:
Sudo modprobe i2c-bcm2708
Sudo modprobe i2c-dev
Lsmod | grep i2c
I2C1: Serial data on PIN3, Serial clock on PIN5, not enabled by default.
I2C0: Serial data on PIN27, Serial clock on PIN28, this is used for HAT management.
To change the baud rate, open the terminal and then write the following:
Sudo cat /sys/module/i2c_bcm2708/parameter/baudrate
Reboot and then write the following
Sudo cat /sys/module/i2c_bcm2708/parameter/baudrate 4000
I2C in C programming
#include<Linux/i2c.h>
#include<Linux/i2c-dev.h>
#define size 19
Int bTOD (char b)
{
Int main()
{
Int file;
Printf(“test is starting \n”);
If(file=open(“/dev/i2c-1”, o_RDWR < 0)
{
perror(“ cannot open your bus\n ”);
return 1;
}
If(ioct1(file, I2C_SLAVE, 0x68) < 0)
{
Perror (“cannot connect the sensor”);
Return 1;
}
Char writeBuff[1] = {0x00};
If (write(file, writeBuff, 1)!=1
{
Perror(“Failed to set your entered address\n”);
Return 1;
}
Char buff(Size);
If(read(file, buff, Size)!=Size)
{
Perror(“Failed to your data in the buffer\n”);
}
Printf(“Time is %02d:%02d:%02d\n”, bTOD(buff[0]));
Float temp = buff[0x11] + ((buff [0x12] >>6)*0.25);
Printf(“the temp : %f\n”, temp);
Close(file);
Return 1;
}
SPI BUS
SPI stands for Serial Peripheral Interface. It’s a fast, full duplex serial data link that allows devices like
the Raspberry Pi to communicate with other devices, but in short distances, so such as I2C the SPI
Protocol is also synchronous. But I2c is not a full duplex bus unlike the SPI, so if you use SPI you can
send and receive the data at the same time. We will use the SPI bus to drive a seven segment LED
Display using an 8-bit shift register.
Now let’s take a look at the differences between IIC and SPI.
IIC : Two wires, 128 devices can be attached. SPI : Four wires, and also needs to connect it with logic if
you want to attach more than one slave device.
IIC : It uses half duplex with 400000Hz. SPI : It uses full duplex with 32MHz.
IIC : You will need to connect pull-up resistors. SPI : There is no need for pull-up resistors.
IIC : The most important feature is that you can have multiple masters. SPI: Very simple but no more
than one master device.
SPI bus works using one of the four modes that are chosen based on the specification defined in the
data sheet of the SPI device. The data can be synchronized by the clock signal and any of the
communication modes. The polarity can be defined if the clock is low or high.
SPI Modes
Mode : 0, polarity : 0 (low), clock Phase : 0
Mode : 1, polarity : 0 (low), clock Phase : 1
Mode : 2, polarity : 1 (high), clock Phase : 0
Mode : 3, polarity : 1 (high), clock Phase : 1
● There is no defined maximum data rate with the SPI protocol, also no flow control, and no
communication acknowledgement.
Raspberry Pi and SPI Protocol
The GPIO header on the Raspberry Pi that has the SPI bus is disabled by default, but you can enable
the bus by the following steps:
● Add an entry to the file /boot/config.txt/etc/modules
Cat config.txt | grep spi
Cat modules | grep spi
Sudo reboot
Ls spi*
● The benefit of SPI0_MOSI is to transfer the data from the Raspberry Pi to the 74HC595 Serial input
(pin 14). You can send 8 bits at a time.
● SPI_CE0_N is connected to the Register Clock input to latch the 74HC595 to the output pins to light
the LEDs.
#include <stdio.h>
#include<cnt1.h>
#include<unistd.h>
#include<stdint.h>
#include<linuxspi/spidev.h>
Transfer.le = le;
Transfer.speed_hez = 1000000; // speed in herz
Transfer.b_per_w = 8; // bits per word
Transfer.del_us = 0; // delay in micro second
Transfer.cx_change = 0; //chip affect transfer
Return -1;
}
If(ioct1(lg, SPI_TOC_WR_MODE, &mode)==-1))
{
Perror(“SPI: Cannot get the mode of SPI”);
Return -1;
}
Printf(“SPI Mode: %d\n”, mode);
Printf(“count in hexa from 0 to F”);
Return -1;
}
Printf(“%5d\r”, i); //print the nun in the terminal window
fflush(stout); // flus the output
usleep(60000) // delay for 600ms in each loop
}
Close(lg);
Return 0;
}
You can use the ioct1() function to override the current settings of the device, but if you add xx you can
read and write.
●SPI_IOC_XX_MOE: The transfer mode of SPI (0-3)
● SPI_IOC_XX_BITS_PER_WORD: determine the number of bits in each word
● SPI_IOC_XX_LSB_FIRST: 0 is MSB, 1 is LSB
● Can be interfaced to RS physical interfaces to enable long distance communication more than 15
meters, but you need to know the UART settings in advance like the baud rate, size, and checking type.
UART in C Programming
#include <stdio.h>
#include<fcnt1.h>
#include<unistd.h>
#include<termios.h>
Include<string.h>
{
Perror(“UART: cannot write to the output\n”);
Return -1;
}
Write(myFile, “\n\r”,2);
Close(myFile);
Return 0;
}
In the above code we have used the termios structure.
The termios structure has many members:
● tcflag_t c_iflag: to set the input modes
● tcflag_t c_oflag: to set the output modes
2. Define UART.
3. Implement the UART in C.
4. List the advantages of SPI.
Chapter 8
In this chapter you will learn how to use Python to develop basic encryption, user input, and graphical
user interfaces.
Let’s start with the "hello world" example as in any programming language.
Create a file named hello.py using the nano text editor.
Nano –c hello.py
Within the file write the following code:
#!/usr/bin/python3
#hello.py
Print (“Hello World”)
After writing the code, save and exit. You can run the file using the following command:
Python3 hello.py
You should know more about strings if you want to start with Python.
A string is a sequence of characters stored together as a value. We will write code to get the user’s
input, using string manipulation to switch the letters and then print the encrypted message of the user
input. You can use text editors that can be directly on your Raspberry Pi or via VNC or SSH. There are
many text editors you can choose from:
● Nano: You can work with this editor from the terminal.
● IDLE3: This editor includes syntax highlighting and context help, but this program requires x-
windows or x11 to run remotely. We will use Python 3, so make sure that you run IDL3 and not IDLE.
●Geany: This editor is an Integrated Development Environment (IDE) that supports many
programming languages, syntax highlighting, auto completion, and very easy code navigation. This is a
rich editor , but not for beginners and it will be slow on the Raspberry Pi. If you want to install Geany,
write the following command:
Sudo apt-get install Geany
To make sure that the Geany editor uses Python 3:
Click on the Execute button to run the code. You will need to change the build commands. Load the
file.
Click build and set build commands and then change Python to Python 3.
Let’s create the program
#!/usr/bin/python3
#ecryptionprogram.py
#takes the input and encrypt it
def encrpytText(input_text,key);
output=””
for letter in input_text:
#Ascii Uppercase 65-90 lowercase 97 -122
Ascii_val = ord(letter)
#now write the following code to exclude non characters from encryption
If(ord(“A”) > Ascii_val) or (Ascii_val > ord(“Z”)):
Output+=letter
Else:
#write this code to apply the encryption key
Key_val = Ascii_val + key
#make sure that we use A-Z regardless of key
Return output
#Test
Def main()
Print (“please enter any text to encrypt”)
#get user input
Try:
Us_input = input();
Sc_result = ecryptText(us_input, 10)
Print (“output: ”, sc_result)
Print(“to un-scramble , pls press enter”)
Input()
Un_result = ecryptText(Sc_result, -10)
The preceding code implements a basic method to encode the text using a character substitution called
the Caesar Cipher, named after Julius Caesar, who used this method to send his secret orders to the
army.
We have defined two functions; encryptText() and main().
When the code is running, the main function contains the user’s input using the input() command. The
result is stored as a string in the us_ input variable.
Us_input = input()
● Keep in mind that the input() function can’t handle non ASCII characters, so we will use try()
function to solve this problem, which will cause UnicodeDecodeError.
We also call the encryptText() function with two parameters; the text to be encrypted, and the key.
After that, the output will be printed.
Sc_result = ecryptText(us_input, 10)
Print(“Output:” + Sc_result)
At the end, we will use input() to get the user input. The encryptText() will perform a simple form of
encryption by shifting the position of the letters. That means substituting the letter with another letter
based on the key; for example, if the letter is “A” and the key is 3 the output will be “D.” This table
shows you the idea of the Caesar Cipher.
In our example, “A” = 65, the key = 3, so the output = 65 +3 = 68 which is “D.”
After that, we will make sure that we have an empty string to build our result (output = “”), and then we
will set our key to encrypt the text.
The input_text variable will contain strings that are stored as a list (a list is something like an array).
You can access every item in the list using input_text[0] for the first item and so on. Python also allows
you to loop through a list using the line of code for “item” in “items”, to access each item.
The letter in input_text : This line allows you to break up the input by looping it through for each item
inside and to set the letter equal to that, so if the input is equal to HELLO, it will run the code five times
for H,E,L,L, and O. This allow you to read every letter separately, and then add the new encrypted
letter to the output string.
%(ord(“Z”) –ord(“A”)+1)
If the entered value is not between the values for A or Z, then you will allow the value to wrap around
(after calculating the modulus the total number of letters between A and Z, which is 26). This works if
the key is larger than 26 and if you are counting in the opposite way, for example:
if the key was negative, the decryption key will be positive.
The following figure will show you the basic form of encryption, you will supply the method and the
key to the one you want to read your message:
If you would like to send the message without the key and the method to the receiver, you will do the
following as in the figure:
First, you will encrypt it and send the message over to the other one, and then they encrypt it again with
their own encryption and send it back. The message at this point has two layers of the applied
encryption. Now you can remove your encryption. At the end, the other side will receive the message
with his/her encryption, which he/she can remove to read the message.
You should keep in mind that there are 25 encryption combinations.
You can run the file directly; Python will set _name_to the main global attribute with this code.
If __name__ ==”__main__”:
main()
Now let’s create key.py and write the following code
#!/user/bin/python3
#key.py
Import encryptdecrypt as ENC
Key_1 = 20
Key_2 = 50
Print(“enter your text: ”)
#get user input
Us_input = input()
#send message
encodKey = ENC.encryptText(us_input, key_1)
print(us_1: send message encrypted with Key_1:” + encodKey)
encodKey2 = ENC.encryptText(encodKEY1KEY2, -KEY1)
print(“us_1: removes KEY1 & returns with KEY2(KEY2):” + encodKey2)
#Receiver will remove the encryption
Msg_res = ENC.encryptText(encodKEY2, -KEY2)
Using files
In this part you will learn how to use and specify a file, via the command line, that will be read and
encoded to produce the output file.
Now let’s create a file named myFile.txt. Write the following code:
#!/user/bin/python3
#myfile.py
RG_KEY = 3
RG_LEN = 4
try:
with open(out,’w’) as f_out:
for line in in_content:
out_line = ENC.encryptText(line, en_key)
f_out.writelines(out_line)
except IOError:
print(“cannot open %s” %(out))
print(“the process is complete %s ” %(out) )
finally:
print(“complete”)
● To run the programs, write the following Python 3 myfile.py in the out key.
For instance, to encrypt myFile.txt and output it as encrypted.txt, use 20 as the key by writing the
following command:
Python3 myfile.py in.txt encrypted.txt 20
If you want to show the result, use less encrypted.txt and enter Q to exit.
If you want to decrypt encrypted.txt and output it as decrypted.txt, use -20.
● Python myFile.py encrypted.txt decrypted.txt -20
This code requires us to use parameters that are provided in the terminal window. You will access them
by importing the Python module called sys. Like you did before, you will also import your
encrypt/decrypt module by the import command. You will use the part to allow you to refer to it using
ENC.
Next, you will set the values to define what each command-line parameter will represent. If you run it ,
you will see that sys.argv[] is an array of values like in the following array:
[‘myfile.py’, ‘in.txt’, ‘encrypted.txt’, ‘20’]
So the input file will be at index 1 in the list, then the output file, and finally, the key with the total
number of parameters RG_LEN = 4.
● Next, you will define the convertFile() function that you will call upon later from the next block of
code.
● If you want to step away from errors, you will check if the length of the sys.argv value matches the
number of parameters from the terminal window. This will make sure that the user has supplied you
with enough, and you shouldn’t try to reference items in the sys.argv[] list that don’t exist. You will
return a short message to explain what you are expecting.
● You will now call the convertFile() function via the terminal window values and making use of
Python’s built in exception handling features to ensure that errors are responded to accordingly.
● The line try/except code allow us to try to run some code and handle any exceptions (errors) in the
program itself, and to halt any sudden stop.
The try code is accompanied by the following options:
● except valError: If an error occurs, a specific type of exception can be specified and handled with the
action, depending on the error you wish to handle. For valError, you could check if the value is a float
value and convert it to an integer or prompt for a new one. Multiple exceptions can be caught using
except (valError, IOError) as required.
● except: This is to catch all cases of any possible exceptions that you have not dealt with. This point
may the code be called from other places.
● else: This part of code is always executed if the try code is right and there is no exception, or any
errors in the code will not be handled by the try/except block.
● finally: The finally part of code will always executed , even if there is no exception or if there is a
problem with the try code.
● In other programming languages you will see something like try and except it, maybe try and catch,
or also raise and throw as equivalents.
DES=0
Key_k = 1
CM = 2
Print(“Start Menu: ”)
Try:
With open(fileN) as f:
myMenuFile = f.readlines()
except IOError:
print(“cannot open %s” %(fileN))
for item in myMenuFile
line = item.split(‘,’)
print (“(%s):%s” % (line[KEY_k], line[DES]))
#Get the user input
Run = True
While(run)
Us_input = input()
#check the input
Freq
Show core temp, t, sudo /opt/vc/bin/vcgencmd measure temp
Exit,x,
● You can add your command and you can customize the list based on your needs..
If you want to execute any other programs from a Python script, you will need to use the command
“call”. You only wish to use the call part of the subprocess module, so you can simply use the
subprocess import call.
● Open the file and read the lines in a menufile array. You can process each item as follows:
Line [‘Start’, ‘Desk’,‘d’, ‘starty’]
You can access each section using the print statement separately, so you can print the key you need to
press for a specific command and the description of the command.
Us_input == line[KEY_k]
The call command will require a command and its parameters to be a list, so you will use the split()
function to break the command part into a list (every space in the statement will use the function).You
should note that after\n is the end of the line character after starty, and this is the end of the line
character from mymenu.ini. You will remove the first using the function rstrip() that is used to remove
any whitespace.
Start:
Menu:
(d): start Desk
(i): Show ip Address
(s): show cpu speed
(t): show core temp
(y): exit
In this part, you will mainly work with the command line. You will also work with the Raspberry Pi by
using a graphical user interface (GUI).
It will be very easy to get the input from the graphical user interface in a natural way. Python supports
this. Much like any other programming language, you will use the Tkinter module that provides a lot of
good controls and tools to create graphical user interfaces.
The app you will make is to convert the encryption application into a graphical user interface instead of
using the command line.
Make sure that you have completed the instructions in the previous part; encryptdecrypt.py program
If you want to use Tkinter (one of add-ons of python), you will need to make sure that it is installed. By
default it will be installed on the standard Raspbian image, but let’s confirm that by importing it for a
Python shell.
>>> import Tkinter
If it doesn’t exist you will see an error (import error). In any case, you can install it using the command:
Sudo apt-get install python3-tk
If it did load , you will use the following command to read more:
>> help (tkinter)
Also, you can find a lot of information about the classes, functions and methods by writing the
following command:
>>> help(tkinter.Button)
If you want to list any valid commands, you should write the following command in your shell:
>>> dir (tkinter.button)
Now let’s use the tkinter to develop a GUI for the encrypt program:
#!/usr/bin/python3
#encrypt.py
Import encrypt as ENC
Import tkinter as TK
def encbutton():
encryptVal.set(ENC.encryptText(encryptVal.get(), keyVal.get))
def decButton():
encryptVal.set(ENC.encryptText(encryptVal.get(). –keyVal.get()))
#Tkinter application
Root =TK.TK()
Root.title(“Enc/Dec application”)
#control values
encryptVal = TK.StringVar()
enryptVal.set(“this is a message”)
keyVal = TK.IntVar()
keyVal.set(20)
promp = “Enter your message to encrypt: ”
Key_k = “Key: ”
Labl_1 = TK.label(root, text = promp, width=len(promp), bg=’red’ )
texEnter=tk.Entry(root, textvariable =encryptVal, width = len(promp))
encbutton = TK.Button(root, text=”enc”, command=encbutton)
decButton = TK.Button(root, text=”dec”, command=decbutton)
labl_2 = TK.label(root, textvariable=keyVal, width=9)
#Layout
Labl_1.grid(row=0, cloumnspan=2, sticky=TK.E + TK.w)
texEnter.grid(row=1, cloumnspan=2, sticky=TK.E+TK.W)
encbutton.grid(row=2, column=0, sticky=TK.E)
decbutton.grid(row=2, column=0, sticky=TK.W)
labl_2grid(row=3, column=1, sticky=TK.W)
TK.mainloop() #end of the program
In this program we start by importing modules
First one is the encrypt/decrypt file and the second one is the tkinter module.
The encbutton() and decbutton functions will be run when click on the encrypt and decrypt buttons
Now let’s take a look at the code
Labl_1 = TK.labe1(root, text=promp, width=len(promp), bg=’red’)
All of the controls have to be linked to the window, you have to determine your tkinter window root.
You will set the text using the text variable as shown. You have to set it to a string named promp that
we defined previously with the text. You also can set the width to match the number of characters of
the message, but it’s not necessary to do that. You set the background color by using bg = ‘red’.
In the next line of code, you defined the textEntry(root, textvariable=encryptVal, width=len(promp)),
you also defined textvariable as a useful way to link variables to the contents of the box that is a string
variable. You can access the text using textEnter.get() if you want, but this will allow you to separate
the data you got it from the code which handles the graphical user interface. Use a Tkinter StringVar()
to access it directly. The encryptVal variable used to update the Entry widget is linked to the .set()
command.
Encbutton = TK.button(root, text=t”Encrypt”, command=encButton)
decbutton = TK.button(root, text=”decrypt”, command=encButton)
In this case, you can set a function to call it when the button is pressed:
def encbutton():
encryptVal.set(ENC.encryptText(encryptVal.get(), keyVal.get))
One of the features of the Raspberry Pi is to set it from home computers; it has the ability to interface
with any hardware.
The General purpose input – output (GPIO) pins can control a lot of low level electronics from LEDs to
motors and displays.
#RGB LED
# now setup the hardware
RGB_Ena = 1; RGB_Dis = 0
#LED Configuration
RGB_R = 16; RGB_G = 18; RGB_B=22
RGB = (RGB_R, RGB_G, RGB_B)
Def led_set():
#wiring
GPIO.setmode(GPIO.BOARD)
#ports
For val in RGB:
GPIO.setup(val, GPIO.OUT)
Def main():
Led_set()
For val in RGB:
GPIO.output(val, RGB_Ena)
Print(“LED is on now ”)
Time.sleep(7)
GPIO.output(val, RGB_Dis)
Print (“LED is off now ”)
Try:
Main()
Finally:
GPIO.cleanup()
#!/usr/bin/python3
#control.py
Import time
Import RPi.GPIO as GPIO
Import os
#close the script
debugging = True
nd = True
#setup the hardware
#GPIO
#config
MODE = GPIO.BOARD
Sht_BIN = 7
LD = 12
Def gpio_Set():
#wiring
GPIO.semode(GPIO.MODE)
#ports
GPIO.setupt(sht_BIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.Setup(LD,GPIO.OUT)
Def doShut():
If(debugging):print(“you pressed the button”)
Time.sleep(4)
If GPIO.input(Sht_BIN):
If(debugging):print(“skip the shutdown (<4sec)”)
else:
if(debugging):print(“do you want to shut down the RPi NOW”)
GPIO.output(LD,0)
Time.sleep(0.6)
GPIO.output(LD, 1)
If(ND):os.system(“flite –tWarning 3 2 1’ ”)
If (debugging == false):os.system(“sudo shutdown h now”)
If(debugging):GPIO.cleanup()
If(debugging):exit()
def main():
GPIO_set()
GPIO.output(LD, 1)
While True:
If(debugging):print(“you can press the button”)
If GPIO.input(sht_BTN)==False:
doShut()
time.sleep(2)
try:
main()
finally:
GPIO.cleanup()
print(“every ting is closed now. The End”)
#End of the program
Questions for Chapter 8
1. Using Python, create a file and put your name and your friends names into that file.
2. Design and develop an LED blinking system using a button and 3 LEDs.
3. Make the three LEDs blink in sequence order.
4. Design a graphical user interface to control the system in Question 3.
Chapter 9
Final Project
In this chapter you will build a media center on the Raspberry Pi board.
The first thing you will do is choose an operating system. I mean the appropriate operating system for
the project because you will focus on making the Pi into a media center. There are two operating
systems for this purpose; the first one is OpenELEC (Open Embedded Linux Entertainment Center),
and the second one is OSMC(Open Source Media Center). In this project you will use the OSMC , so
let’s do the following:
● Download the OS.
● Install the OS on the SD card.
Now go to the main page and then choose DOWNLOADS. There, you will find a list of all the options
of the operating systems you can choose from, or you can start working with Noobs that provide a look
at what the Raspberry PI can do. You will find under these lists a third party operating system, and at
this part you will find the OSMC, so just click on it.
● After completing the download, you can now install it. Make sure that you have the appropriate SD
card that you can use on the Raspberry Pi. If you don’t have WinRAR, just go to the WinRAR website
and install it and extract the image.
Now it’s time to burn the operating system onto the SD card. Make sure that the file is ended with .img,
then open the image burning program and burn it.
After burning the image on the SD card, you can set up everything now. You will need the following
hardware:
The power supply
This power supply will make the difference to the Raspberry Pi, because if the pi is underpowered it
will tell you it doesn’t enough power during high-CPU usage.
● This operating system uses a front end called Kodi. In this part you are going to become very familiar
with the OSMC (Operating System Media Center), and you are going to do the following:
● Work and navigate the keyboard
● Start looking at the settings
● Set up and configure the network
OSMC has a lot of different ways that you can use the content. I will show you how to stream it from
different sources.
The Files menu is where videos can be found. We will discover how to get videos into the right place
so you can watch them later. The most important thing you should know is the video add-ons. This is
where Kodi comes in, and you will spend a lot of time adding new programs and watching your
favorite videos.
Music
This screen is like the video screen. You can store your sounds or audio files if you open it from this
screen. Like with videos , if you stored a collection of audio files somewhere, you can access it from
the OSMC from this screen as well. Also, you will find the music add-ons like the video add-ons.
The settings
● File manager: If you want to transfer something from a USB onto the Raspberry Pi like pictures or
movies, you will open the directory from the file manager.
● System info: This will give an overview of the things running on the Raspberry Pi, and it also
provides you with information like the IP address, summary, storage, memory, and so on.
● Profiles: The profiles are something like the users on the Windows operating system; you add users,
delete, and edit something like the privileges similar to any operating system.
MyOSMC
This screen handles hardware, overclocking, networking, and controls to connect the OSMC from
another computer in case you want to transfer the file.
Wi-Fi
If you want to connect to the Internet wirelessly, you will use the Wi-Fi.
And you can set up it from this screen as shown:
After plugging your Wi-Fi dongle and running your OSMC, you can go to the network and then click
"Wireless." Click yes and finally apply.
If you want to install new applications on the OSMC, you will navigate over to videos: Add-ons and
press enter. Any apps(add-ons) that have been installed will be found here.
There are many choices you can choose from. You will scroll a long list of choices and take time to
choose one. You can install it easily by dimming anything and then pressing enter, but you should look
at the language of the app because the same app may have multilingual versions and you may prefer a
specific one.
After installing a few apps , press backspace to see what apps you have installed.
Music add-ons
If you interested in music you can also do the same thing. There are a lot of streaming options available
that you can add on the Raspberry Pi. You can go to music by using the keyboard and pressing enter on
music.
Move and copy your files
You will use now the file manager to copy or move files. From the main page, go to "settings" and then
choose "file manager."
● In this figure you can see that there is a directory called Super Repo. If you plugged in your USB,
you can see the directory listed on the file manager screen.
● After inserting your USB stick, scroll to your USB until you see your files and then copy any file you
want. For example, llc.mp3, then go to any directory you want and paste it there.
●If you want to play the DVDs and ISOs , the Raspberry Pi can do that but you will need to do the
following:
Get the codec, go back to www.raspberrypi.org
● Click on "shop" until you reach to the Raspberry Pi Swag Store and press on that. There are many
categories like buy a Pi, Codecs, and so on.
● You will use codec/OS, so choose this.
● For DVDs, you will need an MPEG-2 LICENSE KEY, so you will purchase the codec and then press
on the license “please click here to buy your mpeg-2 license key.”
Go to MyOSMC from the main menu, then pi config, and finally to GPU Mem & Codec.
● Keep in mind that not all of the Raspberry Pi boards will process this code.
● If you want to play a DVD you will need to add an external DVD reader to the Raspberry Pi that you
connect via USB to your computer.
Networking
● In this part you will learn how to connect your OSMC over the network.
● You should connect with computers in your home network.
● Everything you will do with your home network can be done with larger networks.
● Some of the benefits of connecting your OSMC is to watch your movies on TV, for example.
● You will focus on your home network instead of Raspberry Pi and OSMC.
Sharing in Windows
● You should remember how to share with Windows, Samba, and SMB.
● Sharing is one of the easiest things that you can do in Windows. After installing Windows , if you
want to share a folder you can just click on it, choose "properties," and then click sharing.
Sharing in Linux
● If you are using the Linux operating system, you can use SSH (secure shell).
If you want to share your Linux computer and the OSMC, simply do the following:
Open the terminal window and then write this command:
Sudo systememct1 enable sshd
If your computer didn’t process this command, don’t worry.
You can try the other command:
Sudo service ssh start
And then write the following:
● When you want to connect to a remote folder, your computer will be like a local folder.
● It will be more complex to setup the Network File Share than an SSH.
Because you will make the other users someone other than yourself , so you will need to set the
permissions.
Sudo mkdir any name / nfs
Sudo shown user: user /nfs
Chmod 777 /nfs
Sudo nano /etc/exports
/nfs *(rw)
Samba
This is the last option to share media from your Linux computer to OSMC, and it is Samba.
Now open the terminal window and write the following command:
Sudo nano / etc/samba/smb.conf
We can scroll down all the way and then add our information for the folder we are sharing.
[sharing name]
Path = /samba
Writable = yes
Guest ok = yes