KEMBAR78
Fiot 3rd Unit Notes | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
22 views33 pages

Fiot 3rd Unit Notes

This document introduces Python programming, covering its characteristics, installation on Windows and Linux, and various data types such as numbers, strings, lists, tuples, and dictionaries. It also explains control flow statements like if, for, while, and the use of break and continue. Additionally, it discusses data structures in Python, including lists, dictionaries, tuples, and sets, along with type conversions.

Uploaded by

sarani sattineni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views33 pages

Fiot 3rd Unit Notes

This document introduces Python programming, covering its characteristics, installation on Windows and Linux, and various data types such as numbers, strings, lists, tuples, and dictionaries. It also explains control flow statements like if, for, while, and the use of break and continue. Additionally, it discusses data structures in Python, including lists, dictionaries, tuples, and sets, along with type conversions.

Uploaded by

sarani sattineni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit 3

Introduction to python programming

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

 Python is a widely used general- purpose ,high level programming language.


 It was created by Guido van Rossum in 1991 and further developed by the python software
foundation.
 Python is a versatile language which is easy to script and easy to read.
 Its syntax is very easy
 Its supports interfacing with wide range hardware platforms
 it is free and open source in nature
 It is available for installation into PC with windows, Linux and Mac.

Characteristics of python

Multi-paradigm programming language:

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.

The key benefits of Python are:

 Easy-to-learn, read and maintain - very few keywords,less syntax construction

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

Installing Python on Ubuntu Linux

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.

Working with Numbers in Python

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

Working with Strings in Python

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

Working with Lists in Python

>>>fruits='apple', 'orange', 'banana','mango']


>>>type (fruits).
<type 'list'>
>>>len (fruits)
4
>>>fruits[1]
'orange'
>>>fruits[1:3]
['orange', 'banana']
>>>fruits[1:]
['orange', 'banana', 'mango']

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.

Working with Tuples in Python

>>>fruits("apple", "mango", "banana", "pineapple")


>>>fruits
('apple', 'mango', 'banana', 'pineapple')
>>>type (fruits)
<type tuple'>
#Get length of tuple
>>>len (fruits)
4

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.

Box 6.6: Working with Dictionaries in Python

>>>student ('name':'Mary','id':'8776','major':'CS')
>>>student ('major': 'CS", 'name': 'Mary','id': '8776)
>>>type (student)
#Get length of a dictionary
>>>len(student)
3

In programming, data type is an important concept.

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:

Text Type: Str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: set, frozenset
Boolean Type: Bool
Binary Types: bytes, bytearray, memoryview

Numeric
A numeric value is any representation of data which has a numeric value. Python identifies three types of
numbers:

 Integer: Positive or negative whole numbers (without a fractional part)

 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"}

Mutable and Immutable Objects


Data objects of the above types are stored in a computer's memory for processing. Some of these values
can be modified during processing, but contents of others can't be altered once they are created in the
memory.
Number values, strings, and tuple are immutable, which means their contents can't be alteredOn
the other hand, collection of items in a List or Dictionary object can be modified. It is possible to add,
delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.

Types of Data Structures in Python

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.

1my_list = [] #create empty list


2print(my_list)
3my_list = [1, 2, 3, 'example', 3.132] #creating list with data
4print(my_list)

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.

1my_dict = {} #empty dictionary


2print(my_dict)
3my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
4print(my_dict)
Output:
{}
{1: ‘Python’, 2: ‘Java’}

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.

1my_set = {1, 2, 3, 4, 5, 5, 5} #create set


2print(my_set)

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

Control flow of python


Lets us look at the control flow statements in Python.

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.

for statement examples

helloString = "Hello World"


fruits =[‘apple', 'orange','banana', 'manga']
student = 'name': 'Mary', 'id': '8776', 'major': 'CS

#looping over characters in a string


For c in hellostring:
Print c
#looping over items in a list
i=0
For item in fruits:
Print “fruits-%d : %s” % (i,item)

#looping over keys in dictionary


For key in student:
Print “%s: %s” %(key,student[key])

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.

For example (no pun intended):


>>> # Measure some strings:
words = ['cat', 'window', 'defenestrate']
>>> for w in words:
print(w, len(w))
cat 3
window 6
defenestrate 12
3. While

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

#Prints even numbers upto 100


>>> i=0
>>> while i<-100:
if 1%2== 0:
print i
i= i+1

4. Range

The range statement in Python generates a list of numbers in arithmetic progression.

Examples of range statement

#Generate a list of numbers from 0-9


>>>range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Generate a list of numbers from 10 - 100 with increments of 10
>>>range (10, 110,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90,100]

The Range() Function

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.

#Break statement example

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

Break and Continue Statements, and else Clauses on Loops

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.

pass statement example

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.

Example of a function in Python

students = ( '1': {'name': 'Bob, 'grade': 2.5},


‘2’ :{‘name': Mary 'grade':3.5},
3 {'name': 'David', 'grade': 4.2},
‘4’{'name': 'John', 'grade': 4.1},
5 {'name': 'Alex', 'grade': 3.8})
( def averageGrade (students):
"This function computes the average grade"
sum =0.0
for key in students: sum = sum + students [key]['grade'
average = sum/len(students)
return average
Avg= averageGrade (students)
print "The average garde is: %0.2f" % (avg)

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.

Example of function with default arguments

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

Example of passing by reference

>>>def displayFruits (fruits):


print "There are d fruits in the list" % (len(fruits))
for item in fruits:
print item
print "Adding one more fruit"
fruits.append('mango')
>>>fruits=['banana', 'pear', 'apple']
>>>displayFruits(fruits)
There are 3 fruits in the list
banana
Pear
apple
Adding one more fruit
>>>print "There are d fruits in the list" * (len(fruits))
There are 4 fruits in the 1ist

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.

Example of reading an entire file

>>>fp= open {‘file.txt’,’r’}


>>content = fp.read()
>>>print content
Python supports more than one programming paradigms including object-oriented programming and
structured programming
Python is an interpreted language and does not require an explicit compilation step.
>>>fp.close()

Example of writing to a file

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

What is an loT Devicе

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

Basic building blocks of an loT Device

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.

Figure 7.1: Block diagram of an IoT Device

Introduction to raspberry pi

 Raspberry Pi is a low-cost mini-computer with the physical size of a credit card.


 Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a normal desktop
computer can do.
 in addition to this, Raspberry Pi also allows interfacing sensors and actuators through the general
purpose I/O pins.
 Since Raspberry Pi runs Linux operating system, it supports Python "out of the box".

About the Board

Raspberry Pi board with the various components/peripherals labeled. .

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

FIG: Raspberry pi GPIO HEADER


Explain in detail the Raspberry pi interfaces ?
OR
What is the use of SPI and I2C interfaces on Raspberry pi ?

Raspberry Pi has Serial (UART), SPI and I2C interfaces for Data transfer.

Serial/ UART Interface:


Universal Asynchronous Receiver Transmitter (UART) based data transmission is an
asynchronous form of serial data transmission. UART based serial data transmission doesn’t
require a clock signal to synchronize the transmitting end and receiving end for transmission.
Instead it relies upon the pre-defined agreement between the transmitting device and
receiving device. The serial communication settings for both transmitter and receiver should
be set as identical. The start and stop of communication is indicated through inserting special
bits in the data stream. While sending a byte of data, a start bit is added first and a stop bit is
added at the end of the bit stream. The least significant bit of the data byte follows the ‘start’
bit. Interface is done as shown in figure .

Figure: UART Interfac


SPI Interface:
The Serial Peripheral Interface Bus (SPI) is a synchronous bi-directional full duplex four-
wire serial interface bus. The concept of SPI was introduced by Motorola. SPI is a single
master multi-slave system. It is possible to have a system where more than one SPI device
can be master, provided the condition only one master device is active at any given point of
time, is satisfied. The Interface can be done as shown in figure.
SPI requires four signal lines for communication. They are:
 Master Out Slave In (MOSI): Signal line carrying the data from master to slave
device. It is also known as Slave Input/Slave Data In (SI/SDI).
 Master In Slave Out (MISO): Signal line carrying the data from slave to master
device. It is also known as Slave Output (SO/SDO).
 Serial Clock (SCLK): Signal line carrying the clock signals.
Slave Select (SS): Signal line for slave device select. It is an active low signal.

Figure: SPI Interface

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’

device only. The Interface can be done as shown in figure.

Figure : I2C Interface


Programming Raspberry Pi with Python

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.

Controlling LED with Raspberry Pi

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

Python program for blinking LED

import RPi.GPIO as GPIO


import time. GPIO.
setmode (GPIO.BCМ)
GPIO.setup(18, GPIO.OUT)
while True:
GPIO.output (18, True)
time.sleep(1)
GPIO.output (18, False)
time.sleep (1)

Interfacing an LED and Switch with Raspberry Pi

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.

Python program for controlling an LED with a switch

from time import sleep


import RPi.GPIO as GPIO
GPIO.setmode (GPIO.BCM)
#Switch Pin
GPIO.setup (25, GP10.IN)
LED Pin GPIO.setup (18, GPIO.OUT)
State=false
def toggleLED (pin):
state = not state
GPIO.output (pin, state)
while True:
try:
if (GPIO.input(25) == True):
toggleLED (pin)
sleep(.01)
except KeyboardInterrupt:
exit()

Examples of python programs using Raspberry Pi

5) Write a python program on Raspberry pi to blink an LED


? Ans:
Interface an LED to Raspberry Pi which blinks with delay of 5 seconds.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(22,True)
time.sleep(5)
GPIO.output(22,
False) time.sleep(5)
try:
while(True):
#to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt:
#cleanup GPIO settings before exiting
gpio.cleanup()
6) Write a python program to control an LED using SWITCH by interfacing them
to Raspberry Pi
Ans :
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO. BOARD)
led = 18 # pin is connected to LED and it should be OUT GPIO:24
switch = 22 # pin is connected to SWITC and it should be IN GPIO:25
GPIO.setup(led, GPIO.OUT, initial=0)
GPIO.setup(switch,
GPIO.IN) def
glow_led(event):
if event == switch:
GPIO.output(led, True)
time.sleep(5)
GPIO.output(led, False)
GPIO.add_event_detect(switch, GPIO.RISING , callback = glow_led, bouncetime = 1)
try:
while(True):
#to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt:
#cleanup GPIO settings before exiting
GPIO.cleanup()
7) Write Python program to control an LED using LDR Sensor by interfacing them
to Raspberry Pi
Ans :

import RPi.GPIO as GPIO


import time
light = 33 #Board number GPIO 13
led = 22 # GPIO 25
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(light,GPIO.IN)
GPIO.setup(led, GPIO.OUT)
def read_light():
while True:
light_state = GPIO.input(light)
if light_state == 0:
GPIO.output(led,
False) time.sleep(1)
print("Light Detected")

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

IOT (Internet Of Things)


 Creating an interactive environment 
 Network of devices connected together

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

 Sensor and actuator interfaced with Raspberry Pi


 Read data from the sensor
 Control the actuator according to the reading from the sensor
 Connect the actuator to a device
Write a python program to display Temperature, Humidity using DHT Sensor
Ans :
#Before executing this program intsall Adafruit_DHT11 Library using follwing
command
#sudo apt-get install Adafruit_DHT11
import time
import Adafruit_DHT
#Set the type of sensor and the pin for sensor
sensor = Adafruit_DHT.DHT11
pin = 4
while(1):
try:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
print ("Humidity ="+str(humidity))
print ("Temperature ="+str(temperature))
except ValueError:
print ("Unable to read data")

You might also like