Fiot 3rd Unit Notes
Fiot 3rd Unit Notes
Topics:
1. introduction to python programming
2. Introduction to raspberry Pi
3. Interfacing raspberry Pi with basic pheripherals
4. Implementation of IOT with raspberry Pi
1. Introduction to python
Characteristics of python
Python supports more than one programming paradigms including object-oriented programming and
structured programming
Interpreted Language
Python is an interpreted language and does not require an explicit compilation step. The Python
interpreter executes the program source code directly, statement by statement, as a processor or scripting
engine does.
Interactive Language
Python provides an interactive mode in which the user can submit commands at the Python prompt and
interact with the interpreter directly.
Object and procedure oriented- procedure or functions are allowed to reuse the code.
Extendable- Allows integration of low level modules written in languages such as C/C+.
Scalable- it provides a manageable structure for large programs
Portable- python program can do directly executed from source code and can be copied from one
host to other.
Broad library support- python packages for applications such as machine learning, image
processing, cryptography, network programming, etc.
How to install python on windows
Python is a highly portable language that works on various platforms such as Windows, Linux, Mac, etc.
This section describes the Python installation steps for Windows and Linux:
Python binaries for Windows can be downloaded from http://www.python.org/getit. For the examples and
exercise in this book, you would require Python 2.7 which can be directly downloaded from:
http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi Once the python binary is installed you can run
the python shell at the command prompt using > python Linux Box 6.1 provides the commands for
installing Python on Ubuntu.
4Install Dependencies
sudo apt-get install build-essential
sudo apt-get install
libreadline-gplv2-dev libncursesw5-dev
libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev 1ibbz2-dev
#Download Python
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar -xvf Python-2.7.5.tgz
cd Python-2.7.5
#Install Python ./configure make
sudo make install
Datatypes in python
1. Numbers
Number data type is used to store numeric values. Numbers are immutable data types, therefore changing
the value of a number data type results in a newly allocated object. shows some examples of working with
numbers.
#Integer
>>>a=5
>>>type (a)
<type int'>
#Floating Point.
>>>b-2.5
>>>type (b)
2. Strings
A string is simply a list of characters in order. There are no limits to the number of characters you can
have in a string. A string which has zero characters is called an empty string. shows examples of working
with strings.
#Create string
>>>s-"Hello World!"
>>>type (s)
<type 'str'>
#String concatenation
>>>t="This is sample program."
>>> s+t
>>>
'Hello World! This is sample program."
#Get length of string
>>>len (s)
12
3. Lists
List is a compound data type used to group together other values. List items need not all have the same
type. A list contains items separated by commas and enclosed within square brackets.
4. Tuples
A tuple is a sequence data type that is similar to the list. A tuple consists of a number of values separated
by commas and enclosed within parentheses. Unlike lists, the elements of tuples cannot be changed, so
tuples can be thought of as read-only lists. Box 6.5 shows examples of working with tuples.
5. Dictionaries
Dictionary is a mapping data type or a kind of hash table that maps keys to values. Keys in a dictionary
can be of any data type, though numbers and strings are commonly used for keys. Values in a dictionary
can be any data type or object. Box 6.6 shows examples on working with dictionaries.
>>>student ('name':'Mary','id':'8776','major':'CS')
>>>student ('major': 'CS", 'name': 'Mary','id': '8776)
>>>type (student)
#Get length of a dictionary
>>>len(student)
3
Variables can store data of different types, and different types can do different things. Python has the
following data types built-in by default, in these categories:
Numeric
A numeric value is any representation of data which has a numeric value. Python identifies three types of
numbers:
Float: Any real number with a floating point representation in which a fractional component is
denoted by a decimal symbol or scientific notation
Complex number: A number with a real and imaginary component represented as x+yj. x and
y are floats and j is -1(square root of -1 called an imaginary number)
Boolean
Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. true and false are not
valid booleans and Python will throw an error for them.
Sequence Type
A sequence is an ordered collection of similar or different data types. Python has the following builtin
sequence data types:
String: A string value is a collection of one or more characters put in single, double or triple
quotes.
List : A list object is an ordered collection of one or more data items, not necessarily of the same
type, put in square brackets.
Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the
same type, put in parentheses.
Dictionary
A dictionary object is an unordered collection of data in a key:value pair form. A collection of such pairs
is enclosed in curly brackets.
For example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}
Python has implicit support for Data Structures which enable you to store and access data. These
structures are called List, Dictionary, Tuple and Set.
Lists
Lists are used to store data of different data types in a sequential manner. There are addresses assigned to
every element of the list, which is called as Index.
The index value starts from 0 and goes on until the last element called the positive index. There is
also negative indexing which starts from -1 enabling you to access elements from the last to first. Let us
now understand lists better with the help of an example program.
Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you do not pass any
elements inside the square brackets, you get an empty list as the output.
Output:
[]
[1, 2, 3, ‘example’, 3.132]
Dictionary
Dictionaries are used to store key-value pairs. To understand better, think of a phone directory where
hundreds and thousands of names and their corresponding numbers have been added. Now the constant
values here are Name and the Phone Numbers which are called as the keys. And the various names and
phone numbers are the values that have been fed to the keys. If you access the values of the keys, you will
obtain all the names and phone numbers. So that is what a key-value pair is. And in
Python, this structure is stored using Dictionaries. Let us understand this better with an example program.
Creating a Dictionary
Dictionaries can be created using the flower braces or using the dict() function. You need to add the key-
value pairs whenever you work with dictionaries.
Tuple
Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be
changed no matter what. The only exception is when the data inside the tuple is mutable, only then the
tuple data can be changed. The example program will help you understand better.
Creating a Tuple
You create a tuple using parenthesis or using the tuple() function.
1my_tuple = (1, 2, 3) #create tuple
2print(my_tuple)
Output:
(1, 2, 3)
Sets
Sets are a collection of unordered elements that are unique. Meaning that even if the data is repeated more
than one time, it would be entered into the set only once. It resembles the sets that you have learnt in
arithmetic. The operations also are the same as is with the arithmetic sets.
An example program would help you understand better.
Creating a set
Sets are created using the flower braces but instead of adding key-value pairs, you just pass values to it.
Output:
{1, 2, 3, 4, 5}
Туpe Conversions
examples of type conversions. Type conversion examples
#Convert to string
>>> a=10000
>>>str(a)
‘10000’
Convert to int
>>>b="2013"
>>>1nt (b)
2013
#Convert to float
>>>float (b)
2013.0
#Convert to long
>>>long (b)
2013L
#Convert to list
>>>s = "aeiou"
>>>list (s)
[ 'a', 'e'. 'i, 'o', 'u']
#Convert to set
>>>x['mango','apple','banana','mango','banana']
>>>set (x)
set (['mango', 'apple', 'banana'])
1. If
The if statement in Python is similar to the if statement in other languages. Box 6.8 shows some
examples of the if statement.
if statement examples
>>>a= 25.5
>>>if a>10000:
print "More"
else:
print "Less"
Output
More
Example 2:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
x=0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
...
print('More')
...
More
2. For
The for statement in Python iterates over items of any sequence (list, string, etc.) in the order in
which they appear in the sequence. This behavior is different from the for statement in other languages
such as C in which an initialization, incrementing and stopping criteria are provided.
the for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always
iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define
both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any
sequence (a list or a string), in the order that they appear in the sequence.
The while statement in Python executes the statements within the while loop as long as the while
condition is true.
shows a while statement example
.while statement examples
4. Range
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions:
>>> for i in range(5):
print(i)
0
1
2
3
4
The given end point is never part of the generated sequence; range(10) generates 10 values, the legal
indices for items of a sequence of length 10. It is possible to let the range start at another number, or to
specify a different increment (even negative; sometimes this is called the ‘step’):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
5. break/continue
The break and continue statements in Python are similar to the statements in C. The break statement
breaks out of the for/while loop whereas the continue statement continues with the next iteration.
>>>y=1
>>>for x in range (4, 256,4) :
Y=y * x
if y > 512:
break
print y
4
32
384
#Continue statement example
>>>fruits*['apple','orange', 'banana','mango']
>>>for item in fruits:
If item == "banana":
continue
else:
print item
apple
orange
mango
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion
of the iterable (with for) or when the condition becomes false (with while), but not when the loop is
terminated by a break statement. This is exemplified by the following loop, which searches for prime
numbers:
>>>
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
6. pass
The pass statement in Python is a null operation. The pass statement is used when a statement is required
syntactically but you do not want any command or code to execute.
fruits['apple','orange', 'banana','mango')
for item in fruits:
if item == "banana":
pass
else:
Print item
Apple
orange
Functions in python
A function is a block of code that takes information in (in the form of parameters), does some
computation, and returns a new piece of information based on the parameter information.
A function in Python is a block of code that begins with the keyword def followed by the function
name and parentheses. The function parameters are enclosed within the parenthesis.
The code block within a function begins after a colon that comes after the parenthesis enclosing
the parameters. The first statement of the function body can optionally be a documentation string or
docstring. Box 6.14 shows an example of a function that computes the average grade given a dictionary
containing student records.
Functions can have default values of the parameters. If a function with default values is called with fewer
parameters or without any parameter, the default values of the parameters are used as shown in the
example in Box 6.15.
>>>def displayFruits(fruits-['apple','orange']):
print "There are id fruits in the list" % (len(fruits))
for item in fruits:
print item
#Using default arguments
>>>displayFruits()
apple orange
>>>fruits =['banana', 'pear', 'mango]
>>>displayFruits (fruits)
Banana
pear
Mango
All parameters in the Python functions are passed by reference. Therefore, if a parameter is changed
within a function the change also reflected back in the calling function.
shows an example of parameter passing by reference.
Modules
Python allows organizing of the program code into different modules which improves the code
readability and management. A module is a Python file that defines some functionality in the form of
functions or classes. Modules can be imported using the import keyword. Modules to be imported must
be present in the search path.shows the example of a student module that contains two functions and
shows an example of importing the student module and using it.
Module student
def averageGrade (students):
sum =0.0
for key in students:
Sum= sum + students[key]['grade']
average = sum/len (students)
return average
def printRecords (students):
print "There are d students" %(len(students))
i=1
for key in students:
print "Student-%d: " % (1)
print "Name: " + students[key]['name']
print "Grade: "+ str(student s[key]'grade'])
i= i+1.
Packages
Python package is hierarchical file structure that consists of modules and subpackages. Packages allow
better organization of modules related to a single application environment.
1. JSON: JavaScript Object Notation (JSON) is an easy to read and write data- interchange format.
JSON is used as an alternative to XML and is is easy for machines to parse and generate. JSON is built
on two structures - a collection of name-value pairs (e.g. a Python dictionary) and ordered lists of
values (e.g.. a Pythonlist).
2. XML: XML (Extensible Markup Language) is a data format for structured document interchange.
The Python minidom library provides a minimal implementation of the Document Object Model
interface and has an API similar to that in other languages.
3. HTTPLib & URLLib: HTTPLib2 and URLLib2 are Python libraries used in
network/internetprogramming
4. SMTPLib: Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending email and
routing e-mail between mail servers. The Python smtplib module provides an SMTP client session
object that can be used to send email.
5. NumPy: NumPy is a package for scientific computing in Python. NumPy provides support for
large multi-dimensional arrays andmatrices
6. Scikit-learn: Scikit-learn is an open source machine learning library for Python that provides
implementations of various machine learning algorithms for classification, clustering, regression and
dimension reduction problems.
File Handling
Python allows reading and writing to files using the file object. The open(filename, mode) function is
used to get a file object.
The mode can be read (r), write (w), append (a), read and write (r+ or w+), read-binary (rb), write-
binary (wb), etc.
example of reading an entire file with read function. After the file contents have been read the close
function is called which closes the file object.
>>>fo open('filel.txt','w'
>>>content ='This is an example of writing to a file in Python’.
>>>fa.write (content)
>>>fo.close()
Classes
Python is an Object-Oriented Programming (OOP) language. Python provides all the standard features of
Object Oriented Programming such as classes, class variables, class methods, inheritance, function
overloading, and operator overloading. Let us briefly look at these OOP concepts:
Class
A class is simply a representation of a type of object and user-defined prototype for an object that is
composed of three things: a name, attributes, and operations/methods.
Instance/Object
Object is an instance of the data structure defined by a class.
Inheritance
Inheritance is the process of forming a new class from an existing class or base class.
Function overloading
Function overloading is a form of polymorphism that allows a function to have different meanings,
depending on its context.
Operator overloading
Operator overloading is a form of polymorphism that allows assignment of more than one function to a
particular operator.
Function overriding
Function overriding allows a child class to provide a specific implementation of a function that is already
provided by the base class. Child class implementation of the overridden function has the same name,
parameters and return type as the function in the base class. Box 6.33 shows an example of a Class. The
variable studentCount is a class variable that is shared by all instances of the class Student and is accessed
by Student.studentCount. The variables name, id and grades are instance variables which are specific to
each instance of the class. There is a special method by the name _init () which is the class constructor.
The class constructor initializes a new instance when it is created. The function del() is the class
destructor.
Examples of a class
>>>class Student:
studentCount C definit (self, name, id):
print "Constructor called"
self.name= name
self.id= id =student.student Count+
self.grades=
def-del (self):
print "Destructor called"
def getStudentCount (self):
return Student.studentCount
def addGrade(self,key, value):
self.grades|key|-value
def getGrade(self, key):
return self.grades|key)
def printGrades (self):
for key in self.grades:
print key + ": " + self.grades key]
>>>s Student ('Steve',98928') Constructor called
>>>s.addGrade ('Math',90)
>>>s.addGrade ('Physics',85')
>>>s.printGrades ()
Physics: 85
Math: 90
>>>mathgrade s.getGrade('Math')
>>>print mathgrade
90
>>>count s.getStudent Count ()
>>>print count 1
>>>del a
Destructor called
loT Physical Devices & Endpoints As described earlier, a "Thing" in Internet of Things (IoT) can be any
object that has a unique identifier and which can send/receive data (including user data) over a network
(e.g., smart phone, smart TV, computer, refrigerator, car, etc.).
IoT devices are connected to the Internet and send information about themselves or about their
surroundings (e.g. information sensed by the connected sensors) over a network (to other devices or
servers/storage) or allow actuation upon the physical entities/environment around them remotely. Some
examples of IoT devices are listed below:
A home automation device that allows remotely monitoring the status of appliances and controlling
the appliances.
An industrial machine which sends information abouts its operation and health monitoring data to a
server.
A car which sends information about its location to a cloud-based service.
A wireless-enabled wearable device that measures data about a person such as the number of steps
walked and sends the data to a cloud-based servicе.
An IoT device can consist of a number of modules based on functional attributes, such as: .
Sensing: Sensors can be either on-board the IoT device or attached to the device. IoT device can
collect various types of information from the on-board or attached sensors such as temperature, humidity,
light intensity, etc. The sensed information can be communicated either to other devices or cloud-based
servers/storage.
Actuation: IoT devices can have various types of actuators attached that allow taking actions
upon the physical entities in the vicinity of the device. For example, a relay switch connected to an IoT
device can turn an appliance on/off based on the commands sent to the device.
Communication: Communication modules are responsible for sending collected data to other
devices or cloud-based servers/storage and receiving data from other devices and commands from remote
applications.
Analysis & Processing: Analysis and processing modules are responsible for making sense of the
collected data.
The representative IoT device used for the examples in this book is the widely used single-board
mini computer called Raspberry Pi. The use of Raspberry Pi is intentional since these devices are widely
accessible, inexpensive, and available from multiple vendors. Furthermore, extensive information is
available on their programming and use both on the Internet.
The principles we teach in Bahga & Madisetti, 2015 7.2 Exemplary Device: Raspberry Pi 179 this
book are just as applicable to other (including proprietary) IoT endpoints, in addition to Raspberry Pi.
Before we look at the specifics of Raspberry Pi, let us first look at the building blocks of a generic single-
board computer (SBC) based IoT device.
Figure 7.1 shows a generic block diagram of a single-board computer (SBC) based IoT device that
includes CPU, GPU, RAM, storage and various types of interfaces and peripherals.
Introduction to raspberry pi
.Processor & RAM: Raspberry Pi is based on an ARM processor. The latest version of Raspberry Pi
(Model B, Revision 2) comes with 700 MHz Low Power ARM1176JZ-F processor and 512 MB
SDRAM.
USB Ports: Raspberry Pi comes with two USB 2.0 ports. The USB ports on Raspberry Pi can
provide a current upto 100mA. For connecting devices that draw current more than 100mA, an
external USB powered hub is required.
Ethernet Ports: Raspberry Pi comes with a standard RJ45 Ethernet port. You can connect an
Ethernet cable or a USB Wifi adapter to provide Internet connectivity.
HDMI Output: The HDMI port on Raspberry Pi provides both video and audio output. You can
connect the Raspberry Pi to a monitor using an HDMI cable. For monitors that have a DVI port but
no HDMI port, you can use an HDMI to DVI adapter/cable.
Composite Video Output: Raspberry Pi comes with a composite video output with an RCA jack that
supports both PAL and NTSC video output. The RCA jack can be used to connect old televisions that
have an RCA input only.
Audio Output: Raspberry Pi has a 3.5mm audio output jack. This audio jack is used for providing
audio output to old televisions along with the RCA jack for video. The audio quality from this jack is
inferior to the HDMI output.
GPIO Pins: Raspberry Pi comes with a number of general purpose input/ouput pins. Figure 7.3
shows the Raspberry Pi GPIO headers. There are four types of pins on Raspberry Pi - true GPIO pins,
I2C interface pins, SPI interface pins and serial Rx and Tx pins.
Display Serial Interface (DSI): The DSI interface can be used to connect an LCD panel to
Raspberry Pi.
Camera Serial Interface (CSI): The CSI interface can be used to connect a camera module to
Raspberry Pi.
Status LEDs: Raspberry Pi has five status LEDs. Table 7.1 lists Raspberry Pi status LEDs and their
functions.
SD Card Slot: Raspberry Pi does not have a built in operating system and storage. You can plug-in
an SD card loaded with a Linux image to the SD card slot.
Appendix-A provides instructions on setting up New Out-of-the-Box Software (NOOBS) on Raspberry
Pi. You will require atleast an 8GB SD card for setting up NOOBS.
Power Input: Raspberry Pi has a micro-USB connector for power input.
Fig: Raspberry Pi Board
Linux on Raspberry Pi
Raspberry Pi supports various flavors of Linux including: Raspbian Raspbian Linux is a Debian
Wheezy port optimized for Raspberry Pi. This is the recommended Linux for Raspberry Pi. Appendix-1
provides instructions on setting up Raspbian on Raspberry Pi.
Raspberry Pi has Serial (UART), SPI and I2C interfaces for Data transfer.
I2C Interface:
The Inter Integrated Circuit Bus (I2C–Pronounced ‘I square C’) is a synchronous bi-
directional half duplex (one-directional communication at a given point of time) two wire serial
interface bus The I2C bus comprise of two bus lines, namely: Serial Clock–SCL and Serial
Data–SDA.
SCL line is responsible for generating synchronization clock pulses and SDA is responsible
for transmitting the serial data across devices.
I2C bus is a shared bus system to which many number of I2C devices can be connected.
Devices connected to the I2C bus can act as either ‘Master’ device or ‘Slave’ device. The
‘Master’ device is responsible for controlling the communication by initiating/terminating
data transfer, sending data and generating necessary synchronization clock pulses. ‘Slave’
devices wait for the commands from the master and respond upon receiving the commands.
Master’ and ‘Slave’ devices can act as either transmitter or receiver. Regardless whether a
master is acting as transmitter or receiver, the synchronization clock signal is generated by the
‘Master’
In this section you will learn how to get started with developing Python programs on Raspberry
Pi. Raspberry Pi runs Linux and supports Python out of the box. Therefore, you can run any Python
program that runs on a normal computer. However, it is the general purpose input/output capability
provided by the GPIO pins on Raspberry Pi that makes it useful device for Internet of Things. You can
interface a wide variety of sensor and actuators with Raspberry Pi using the GPIO pins and the SPI, 12C
and serial interfaces. Input from the sensors connected to Raspberry Pi can be processed and various
actions can be taken, for instance, sending data to a server, sending an email, triggering a relay switch.
Let us start with a basic example of controlling an LED from Raspberry Pi. Figure 7.9 shows the
schematic diagram of connecting an LED to Raspberry Pi.
how to turn the LED on/off from command line. In this example the LED is connected to GPIO
pin 18. You can connect the LED to any other GPIO pin as well. a Python program for blinking an LED
connected to Raspberry Pi every second. The program uses the RPi. GPIO module to control the GPIO on
Raspberry Pi. In this program we set pin 18 direction to output and then write True/False alternatively
after a delay of one second.
switching LED on/off from Raspberry Pi console
$echo 18 > /sys/class/gpio/export
$cd /ays/class/gpio/gpio18
#Set pin 18 direction to out
Secho out > direction
#Turn LED on
$echo 1 > value
#Turn LED off
$echo 0 > value
Now let us look at a more detailed example involving an LED and a switch that is used to control
the LED. the schematic diagram of connecting an LED and switch to Raspberry Pi. a Python program
for controlling an LED with a switch. In this example the LED is connected to GPIO pin 18 and switch is
connected to pin 25. In the infinite while loop the value of pin 25 is checked and the state of LED is
toggled if the switch is pressed.
This example shows how to get input from GPIO pins and process the input and take some action.
The action in this example is toggling the state of an LED. Let us look at another example, in which the
action is an email alert. a Python program for sending an email on switch press. This program uses the
Python SMTP library for sending an email when the switch connected to Raspberry Pi is pressed.
elif light_state == 1:
print("Light Not Detected")
GPIO.output(led, True)
time.sleep(1)
time.sleep(.3)
def destroy(): #When program ending, the function is executed.
GPIO.cleanup()
if name == ' main ': #Program starting from
here try:
setup()
read_light()
except KeyboardInterrupt:
destroy()
implementation of IoT with Raspberry Pi
Sensor
Electronic element
Converts physical quantity into electrical signals
Can be analog or digital
Actuator
Mechanical/Electro-mechanical device
Converts energy into motion
Mainly used to provide controlled motion to other components
System Overview